use background encoding as default input-mode, add missing caps initialization
[gst-plugin-dreamsource.git] / src / gstdreamvideosource.c
1 /*
2  * GStreamer dreamvideosource
3  * Copyright 2014-2015 Andreas Frisch <fraxinas@opendreambox.org>
4  *
5  * This program is licensed under the Creative Commons
6  * Attribution-NonCommercial-ShareAlike 3.0 Unported
7  * License. To view a copy of this license, visit
8  * http://creativecommons.org/licenses/by-nc-sa/3.0/ or send a letter to
9  * Creative Commons,559 Nathan Abbott Way,Stanford,California 94305,USA.
10  *
11  * Alternatively, this program may be distributed and executed on
12  * hardware which is licensed by Dream Property GmbH.
13  *
14  * This program is NOT free software. It is open source, you are allowed
15  * to modify it (if you keep the license), but it may not be commercially
16  * distributed other than under the conditions noted above.
17  */
18
19 #ifdef HAVE_CONFIG_H
20 #include <config.h>
21 #endif
22
23 #include <gst/gst.h>
24 #include "gstdreamvideosource.h"
25
26 GST_DEBUG_CATEGORY_STATIC (dreamvideosource_debug);
27 #define GST_CAT_DEFAULT dreamvideosource_debug
28
29 GType gst_dreamvideosource_input_mode_get_type (void)
30 {
31         static volatile gsize input_mode_type = 0;
32         static const GEnumValue input_mode[] = {
33                 {GST_DREAMVIDEOSOURCE_INPUT_MODE_LIVE, "GST_DREAMVIDEOSOURCE_INPUT_MODE_LIVE", "live"},
34                 {GST_DREAMVIDEOSOURCE_INPUT_MODE_HDMI_IN, "GST_DREAMVIDEOSOURCE_INPUT_MODE_HDMI_IN", "hdmi_in"},
35                 {GST_DREAMVIDEOSOURCE_INPUT_MODE_BACKGROUND, "GST_DREAMVIDEOSOURCE_INPUT_MODE_BACKGROUND", "background"},
36                 {0, NULL, NULL},
37         };
38
39         if (g_once_init_enter (&input_mode_type)) {
40                 GType tmp = g_enum_register_static ("GstDreamVideoSourceInputMode", input_mode);
41                 g_once_init_leave (&input_mode_type, tmp);
42         }
43         return (GType) input_mode_type;
44 }
45
46 enum
47 {
48         SIGNAL_GET_DTS_OFFSET,
49         LAST_SIGNAL
50 };
51
52 enum
53 {
54         ARG_0,
55         ARG_CAPS,
56         ARG_BITRATE,
57         ARG_INPUT_MODE
58 };
59
60 static guint gst_dreamvideosource_signals[LAST_SIGNAL] = { 0 };
61
62 #define DEFAULT_BITRATE     2048
63 #define DEFAULT_FRAMERATE   25
64 #define DEFAULT_WIDTH       1280
65 #define DEFAULT_HEIGHT      720
66 #define DEFAULT_INPUT_MODE  GST_DREAMVIDEOSOURCE_INPUT_MODE_BACKGROUND
67 #define DEFAULT_BUFFER_SIZE 50
68
69 static GstStaticPadTemplate srctemplate =
70     GST_STATIC_PAD_TEMPLATE ("src",
71         GST_PAD_SRC,
72         GST_PAD_ALWAYS,
73         GST_STATIC_CAPS ("video/x-h264, "
74         "width = { 720, 1280, 1920 }, "
75         "height = { 576, 720, 1080 }, "
76         "framerate = { 25/1, 30/1, 50/1, 60/1 }, "
77         "display-aspect-ratio = { 5/4, 16/9 }, "
78         "stream-format = (string) byte-stream, "
79         "profile = (string) main")
80     );
81
82 #define gst_dreamvideosource_parent_class parent_class
83 G_DEFINE_TYPE (GstDreamVideoSource, gst_dreamvideosource, GST_TYPE_PUSH_SRC);
84
85 static GstCaps *gst_dreamvideosource_getcaps (GstBaseSrc * bsrc, GstCaps * filter);
86 static gboolean gst_dreamvideosource_setcaps (GstBaseSrc * bsrc, GstCaps * caps);
87 static GstCaps *gst_dreamvideosource_fixate (GstBaseSrc * bsrc, GstCaps * caps);
88 static gboolean gst_dreamvideosource_query (GstBaseSrc * bsrc, GstQuery * query);
89
90 static gboolean gst_dreamvideosource_unlock (GstBaseSrc * bsrc);
91 static gboolean gst_dreamvideosource_unlock_stop (GstBaseSrc * bsrc);
92 static void gst_dreamvideosource_dispose (GObject * gobject);
93 static GstFlowReturn gst_dreamvideosource_create (GstPushSrc * psrc, GstBuffer ** outbuf);
94
95 static void gst_dreamvideosource_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec);
96 static void gst_dreamvideosource_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec);
97
98 static GstStateChangeReturn gst_dreamvideosource_change_state (GstElement * element, GstStateChange transition);
99 static gint64 gst_dreamvideosource_get_dts_offset (GstDreamVideoSource *self);
100
101 static gboolean gst_dreamvideosource_encoder_init (GstDreamVideoSource * self);
102 static void gst_dreamvideosource_encoder_release (GstDreamVideoSource * self);
103
104 static void gst_dreamvideosource_read_thread_func (GstDreamVideoSource * self);
105
106 #ifdef PROVIDE_CLOCK
107 static GstClock *gst_dreamvideosource_provide_clock (GstElement * elem);
108 // static GstClockTime gst_dreamvideosource_get_encoder_time_ (GstClock * clock, GstBaseSrc * bsrc);
109 #endif
110
111 static void
112 gst_dreamvideosource_class_init (GstDreamVideoSourceClass * klass)
113 {
114         GObjectClass *gobject_class;
115         GstElementClass *gstelement_class;
116         GstBaseSrcClass *gstbsrc_class;
117         GstPushSrcClass *gstpush_src_class;
118
119         gobject_class = (GObjectClass *) klass;
120         gstelement_class = (GstElementClass *) klass;
121         gstbsrc_class = (GstBaseSrcClass *) klass;
122         gstpush_src_class = (GstPushSrcClass *) klass;
123
124         gobject_class->set_property = gst_dreamvideosource_set_property;
125         gobject_class->get_property = gst_dreamvideosource_get_property;
126         gobject_class->dispose = gst_dreamvideosource_dispose;
127
128         gst_element_class_add_pad_template (gstelement_class,
129                                             gst_static_pad_template_get (&srctemplate));
130
131         gst_element_class_set_static_metadata (gstelement_class,
132             "Dream Video source", "Source/Video",
133             "Provide an h.264 video elementary stream from Dreambox encoder device",
134             "Andreas Frisch <fraxinas@opendreambox.org>");
135
136         gstelement_class->change_state = gst_dreamvideosource_change_state;
137
138         gstbsrc_class->get_caps = gst_dreamvideosource_getcaps;
139         gstbsrc_class->set_caps = gst_dreamvideosource_setcaps;
140         gstbsrc_class->query = gst_dreamvideosource_query;
141         gstbsrc_class->fixate = gst_dreamvideosource_fixate;
142         gstbsrc_class->unlock = gst_dreamvideosource_unlock;
143         gstbsrc_class->unlock_stop = gst_dreamvideosource_unlock_stop;
144
145         gstpush_src_class->create = gst_dreamvideosource_create;
146
147 #ifdef PROVIDE_CLOCK
148         gstelement_class->provide_clock = GST_DEBUG_FUNCPTR (gst_dreamvideosource_provide_clock);
149 //      g_type_class_ref (GST_TYPE_SYSTEM_CLOCK);
150 #endif
151
152         g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_BITRATE,
153           g_param_spec_int ("bitrate", "Bitrate (kb/s)",
154             "Bitrate in kbit/sec", 16, 200000, DEFAULT_BITRATE,
155             G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
156
157         g_object_class_install_property (gobject_class, ARG_CAPS,
158           g_param_spec_boxed ("caps", "Caps",
159             "The caps for the source stream", GST_TYPE_CAPS,
160             G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
161
162         g_object_class_install_property (gobject_class, ARG_INPUT_MODE,
163           g_param_spec_enum ("input-mode", "Input Mode",
164             "Select the input source of the video stream",
165             GST_TYPE_DREAMVIDEOSOURCE_INPUT_MODE, DEFAULT_INPUT_MODE,
166             G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
167
168         gst_dreamvideosource_signals[SIGNAL_GET_DTS_OFFSET] =
169                 g_signal_new ("get-dts-offset",
170                 G_TYPE_FROM_CLASS (klass),
171                 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
172                 G_STRUCT_OFFSET (GstDreamVideoSourceClass, get_dts_offset),
173                 NULL, NULL, gst_dreamsource_marshal_INT64__VOID, G_TYPE_INT64, 0);
174
175         klass->get_dts_offset = gst_dreamvideosource_get_dts_offset;
176 }
177
178 static gint64
179 gst_dreamvideosource_get_dts_offset (GstDreamVideoSource *self)
180 {
181         GST_DEBUG_OBJECT (self, "gst_dreamvideosource_get_dts_offset %" GST_TIME_FORMAT"", GST_TIME_ARGS (self->dts_offset) );
182         return self->dts_offset;
183 }
184
185 static void gst_dreamvideosource_set_bitrate (GstDreamVideoSource * self, uint32_t bitrate)
186 {
187         g_mutex_lock (&self->mutex);
188         uint32_t vbr = bitrate*1000;
189         if (!self->encoder || !self->encoder->fd)
190         {
191                 self->video_info.bitrate = bitrate;
192                 g_mutex_unlock (&self->mutex);
193                 return;
194         }
195
196         int ret = ioctl(self->encoder->fd, VENC_SET_BITRATE, &vbr);
197         if (ret != 0)
198         {
199                 GST_WARNING_OBJECT (self, "can't set video bitrate to %i bytes/s!", vbr);
200                 g_mutex_unlock (&self->mutex);
201                 return;
202         }
203         GST_INFO_OBJECT (self, "set video bitrate to %i kBytes/s", bitrate);
204         self->video_info.bitrate = bitrate;
205         g_mutex_unlock (&self->mutex);
206 }
207
208 static gboolean gst_dreamvideosource_set_format (GstDreamVideoSource * self, VideoFormatInfo * info)
209 {
210         g_mutex_lock (&self->mutex);
211         if (!self->encoder || !self->encoder->fd)
212         {
213                 self->video_info = *info;
214                 g_mutex_unlock (&self->mutex);
215                 return TRUE;
216         }
217
218         if (info->fps_n > 0)
219         {
220                 int venc_fps = 0;
221                 switch (info->fps_n) {
222                         case 25:
223                                 venc_fps = rate_25;
224                                 break;
225                         case 30:
226                                 venc_fps = rate_30;
227                                 break;
228                         case 50:
229                                 venc_fps = rate_50;
230                                 break;
231                         case 60:
232                                 venc_fps = rate_60;
233                                 break;
234                         default:
235                                 GST_ERROR_OBJECT (self, "invalid framerate %d/%d", info->fps_n, info->fps_d);
236                                 goto fail;
237                 }
238                 if (!ioctl(self->encoder->fd, VENC_SET_FRAMERATE, &venc_fps))
239                         GST_INFO_OBJECT (self, "set framerate to %d/%d -> ioctrl(%d, VENC_SET_FRAMERATE, &%d)", info->fps_n, info->fps_d, self->encoder->fd, venc_fps);
240                 else
241                 {
242                         GST_WARNING_OBJECT (self, "can't set framerate to %d/%d -> ioctrl(%d, VENC_SET_FRAMERATE, &%d)", info->fps_n, info->fps_d, self->encoder->fd, venc_fps);
243                         goto fail;
244                 }
245         }
246
247         if (info->width && info->height)
248         {
249                 int venc_size = 0;
250                 if ( info->width == 720 && info->height == 576 )
251                         venc_size = fmt_720x576;
252                 else if ( info->width == 1280 && info->height == 720)
253                         venc_size = fmt_1280x720;
254                 else if ( info->width == 1920 && info->height == 1080)
255                         venc_size = fmt_1920x1080;
256                 else
257                 {
258                         GST_ERROR_OBJECT (self, "invalid resolution %dx%d", info->width, info->height);
259                         goto fail;
260                 }
261                 if (!ioctl(self->encoder->fd, VENC_SET_RESOLUTION, &venc_size))
262                         GST_INFO_OBJECT (self, "set resolution to %dx%d -> ioctrl(%d, VENC_SET_RESOLUTION, &%d)", info->width, info->height, self->encoder->fd, venc_size);
263                 else
264                 {
265                         GST_WARNING_OBJECT (self, "can't set resolution to %dx%d -> ioctrl(%d, VENC_SET_RESOLUTION, &%d)", info->width, info->height, self->encoder->fd, venc_size);
266                         goto fail;
267                 }
268         }
269
270         self->video_info = *info;
271         g_mutex_unlock (&self->mutex);
272         return TRUE;
273
274 fail:
275         g_mutex_unlock (&self->mutex);
276         return FALSE;
277 }
278
279 void gst_dreamvideosource_set_input_mode (GstDreamVideoSource *self, GstDreamVideoSourceInputMode mode)
280 {
281         g_return_if_fail (GST_IS_DREAMVIDEOSOURCE (self));
282         GEnumValue *val = g_enum_get_value (G_ENUM_CLASS (g_type_class_ref (GST_TYPE_DREAMVIDEOSOURCE_INPUT_MODE)), mode);
283         if (!val)
284         {
285                 GST_ERROR_OBJECT (self, "no such input_mode %i!", mode);
286                 return;
287         }
288         const gchar *value_nick = val->value_nick;
289
290         g_mutex_lock (&self->mutex);
291         if (!self->encoder || !self->encoder->fd)
292         {
293                 self->input_mode = mode;
294                 goto out;
295         }
296         int int_mode = mode;
297         int ret = ioctl(self->encoder->fd, VENC_SET_SOURCE, &int_mode);
298         if (ret != 0)
299         {
300                 GST_WARNING_OBJECT (self, "can't set input mode to %s (%i) error: %s", value_nick, mode, strerror(errno));
301                 goto out;
302         }
303         GST_INFO_OBJECT (self, "successfully set input mode to %s (%i)", value_nick, mode);
304         self->input_mode = mode;
305
306 out:
307         g_mutex_unlock (&self->mutex);
308         return;
309 }
310
311 GstDreamVideoSourceInputMode gst_dreamvideosource_get_input_mode (GstDreamVideoSource *self)
312 {
313         GstDreamVideoSourceInputMode result;
314         g_return_val_if_fail (GST_IS_DREAMVIDEOSOURCE (self), -1);
315         g_mutex_lock (&self->mutex);
316         result =self->input_mode;
317         g_mutex_unlock (&self->mutex);
318         return result;
319 }
320
321 gboolean
322 gst_dreamvideosource_plugin_init (GstPlugin *plugin)
323 {
324         GST_DEBUG_CATEGORY_INIT (dreamvideosource_debug, "dreamvideosource", 0, "dreamvideosource");
325         return gst_element_register (plugin, "dreamvideosource", GST_RANK_PRIMARY, GST_TYPE_DREAMVIDEOSOURCE);
326 }
327
328 static void
329 gst_dreamvideosource_init (GstDreamVideoSource * self)
330 {
331         self->current_caps = NULL;
332         self->new_caps = NULL;
333
334         self->dts_valid = FALSE;
335         self->encoder = NULL;
336         self->descriptors_available = 0;
337         self->input_mode = DEFAULT_INPUT_MODE;
338
339         self->buffer_size = DEFAULT_BUFFER_SIZE;
340         g_queue_init (&self->current_frames);
341         self->readthread = NULL;
342
343         g_mutex_init (&self->mutex);
344         g_cond_init (&self->cond);
345         READ_SOCKET (self) = -1;
346         WRITE_SOCKET (self) = -1;
347
348         gst_base_src_set_format (GST_BASE_SRC (self), GST_FORMAT_TIME);
349         gst_base_src_set_live (GST_BASE_SRC (self), TRUE);
350
351         self->encoder = NULL;
352         self->encoder_clock = NULL;
353
354 #ifdef dump
355         self->dumpfd = open("/media/hdd/movie/dreamvideosource.dump", O_WRONLY | O_CREAT | O_TRUNC);
356         GST_DEBUG_OBJECT (self, "dumpfd = %i (%s)", self->dumpfd, (self->dumpfd > 0) ? "OK" : strerror(errno));
357 #endif
358 }
359
360 static gboolean gst_dreamvideosource_encoder_init (GstDreamVideoSource * self)
361 {
362         GST_LOG_OBJECT (self, "initializating encoder...");
363         self->encoder = malloc (sizeof(EncoderInfo));
364
365         if (!self->encoder) {
366                 GST_ERROR_OBJECT (self,"out of space");
367                 return FALSE;
368         }
369
370         char fn_buf[32];
371         sprintf(fn_buf, "/dev/venc%d", 0);
372         self->encoder->fd = open(fn_buf, O_RDWR | O_SYNC);
373         if (self->encoder->fd <= 0) {
374                 GST_ERROR_OBJECT (self,"cannot open device %s (%s)", fn_buf, strerror(errno));
375                 free(self->encoder);
376                 self->encoder = NULL;
377                 return FALSE;
378         }
379
380         self->encoder->buffer = malloc(VBUFSIZE);
381         if (!self->encoder->buffer) {
382                 GST_ERROR_OBJECT(self,"cannot alloc buffer");
383                 return FALSE;
384         }
385
386         self->encoder->cdb = (unsigned char *)mmap (0, VMMAPSIZE, PROT_READ, MAP_PRIVATE, self->encoder->fd, 0);
387
388         if (!self->encoder->cdb || self->encoder->cdb == MAP_FAILED) {
389                 GST_ERROR_OBJECT(self, "cannot alloc buffer: %s (%i)", strerror(errno), errno);
390                 self->encoder->cdb = NULL;
391                 return FALSE;
392         }
393
394         int control_sock[2];
395         if (socketpair (PF_UNIX, SOCK_STREAM, 0, control_sock) < 0)
396         {
397                 GST_ERROR_OBJECT(self, "cannot create control sockets: %s (%i)", strerror(errno), errno);
398                 return FALSE;
399         }
400         READ_SOCKET (self) = control_sock[0];
401         WRITE_SOCKET (self) = control_sock[1];
402         fcntl (READ_SOCKET (self), F_SETFL, O_NONBLOCK);
403         fcntl (WRITE_SOCKET (self), F_SETFL, O_NONBLOCK);
404
405         gst_dreamvideosource_set_bitrate (self, self->video_info.bitrate);
406         gst_dreamvideosource_set_format (self, &self->video_info);
407         gst_dreamvideosource_set_input_mode (self, self->input_mode);
408
409         GST_LOG_OBJECT (self, "encoder %s successfully initialized", fn_buf);
410         return TRUE;
411 }
412
413 static void gst_dreamvideosource_encoder_release (GstDreamVideoSource * self)
414 {
415         GST_LOG_OBJECT (self, "releasing encoder...");
416         if (self->encoder) {
417                 if (self->encoder->buffer)
418                         free(self->encoder->buffer);
419                 if (self->encoder->cdb)
420                         munmap(self->encoder->cdb, VMMAPSIZE);
421                 if (self->encoder->fd)
422                         close(self->encoder->fd);
423                 free(self->encoder);
424         }
425         self->encoder = NULL;
426         close (READ_SOCKET (self));
427         close (WRITE_SOCKET (self));
428         READ_SOCKET (self) = -1;
429         WRITE_SOCKET (self) = -1;
430         if (self->encoder_clock) {
431                 gst_object_unref (self->encoder_clock);
432                 self->encoder_clock = NULL;
433         }
434 }
435
436 static void
437 gst_dreamvideosource_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec)
438 {
439         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (object);
440
441         switch (prop_id) {
442                 case ARG_CAPS:
443                 {
444                         if (self->new_caps)
445                                 gst_caps_unref (self->new_caps);
446                         self->new_caps = gst_caps_copy (gst_value_get_caps (value));
447                         gst_pad_mark_reconfigure (GST_BASE_SRC_PAD (GST_BASE_SRC(object)));
448                         break;
449                 }
450                 case ARG_BITRATE:
451                         gst_dreamvideosource_set_bitrate(self, g_value_get_int (value));
452                         break;
453                 case ARG_INPUT_MODE:
454                         gst_dreamvideosource_set_input_mode (self, g_value_get_enum (value));
455                         break;
456                 default:
457                         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
458                         break;
459         }
460 }
461
462 static void
463 gst_dreamvideosource_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec)
464 {
465         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (object);
466
467         switch (prop_id) {
468                 case ARG_CAPS:
469                         g_value_take_boxed (value, gst_dreamvideosource_getcaps (GST_BASE_SRC(object), GST_CAPS_ANY));
470                         break;
471                 case ARG_BITRATE:
472                         g_value_set_int (value, self->video_info.bitrate/1000);
473                         break;
474                 case ARG_INPUT_MODE:
475                         g_value_set_enum (value, gst_dreamvideosource_get_input_mode (self));
476                         break;
477                 default:
478                         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
479                         break;
480         }
481 }
482
483 static GstCaps *
484 gst_dreamvideosource_getcaps (GstBaseSrc * bsrc, GstCaps * filter)
485 {
486         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (bsrc);
487         GstCaps *caps;
488
489         g_mutex_lock (&self->mutex);
490         if (self->new_caps)
491         {
492                 GST_DEBUG_OBJECT (self, "gst_dreamvideosource_getcaps has new_caps: %" GST_PTR_FORMAT " / current_caps: %" GST_PTR_FORMAT "", self->new_caps, self->current_caps);
493                 if (self->current_caps)
494                 {
495                         caps = gst_caps_new_empty ();
496                         gst_caps_replace (&caps, self->new_caps);
497                         self->new_caps = NULL;
498                 }
499                 else
500                         caps = gst_caps_copy (self->new_caps);
501         } else if (self->current_caps == NULL) {
502                 GstPadTemplate *pad_template;
503                 pad_template = gst_element_class_get_pad_template (GST_ELEMENT_GET_CLASS(self), "src");
504                 if (pad_template)
505                         caps = gst_caps_copy (gst_pad_template_get_caps (pad_template));
506                 else
507                         caps = gst_caps_new_empty ();
508
509                 caps = gst_pad_template_get_caps (pad_template);
510         } else
511                 caps = gst_caps_copy(self->current_caps);
512
513         GST_LOG_OBJECT (self, "gst_dreamvideosource_getcaps %" GST_PTR_FORMAT " filter %" GST_PTR_FORMAT, caps, filter);
514
515         if (filter) {
516                 GstCaps *intersection;
517                 intersection = gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
518                 gst_caps_unref (caps);
519                 caps = intersection;
520         }
521
522         GST_LOG_OBJECT (self, "return caps %" GST_PTR_FORMAT, caps);
523         g_mutex_unlock (&self->mutex);
524         return caps;
525 }
526
527 static gboolean
528 gst_dreamvideosource_setcaps (GstBaseSrc * bsrc, GstCaps * caps)
529 {
530         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (bsrc);
531         GstCaps *current_caps;
532         const GstStructure *structure;
533         VideoFormatInfo info;
534         gboolean ret;
535         const GValue *framerate;
536
537         g_mutex_lock (&self->mutex);
538         structure = gst_caps_get_structure (caps, 0);
539
540         current_caps = gst_pad_get_current_caps (GST_BASE_SRC_PAD (bsrc));
541
542         GST_LOG_OBJECT (self, "gst_dreamvideosource_setcaps parameter %" GST_PTR_FORMAT " self->current_caps=%" GST_PTR_FORMAT " pad's current_caps=%" GST_PTR_FORMAT "  new_caps=%" GST_PTR_FORMAT"", caps, current_caps, self->current_caps, self->new_caps);
543
544         if (current_caps && gst_caps_is_equal (current_caps, caps)) {
545                 GST_LOG_OBJECT (self, "New caps equal to old ones: %" GST_PTR_FORMAT, caps);
546                 ret = TRUE;
547         } else {
548                 GstState state;
549                 gst_element_get_state (GST_ELEMENT(self), &state, NULL, 1*GST_MSECOND);
550                 if (state == GST_STATE_PLAYING)
551                 {
552                         GST_WARNING_OBJECT (self, "can't change caps while in PLAYING state %" GST_PTR_FORMAT, caps);
553                         g_mutex_unlock (&self->mutex);
554                         return TRUE;
555                 }
556                 else if (gst_structure_has_name (structure, "video/x-h264"))
557                 {
558                         memset (&info, 0, sizeof(VideoFormatInfo));
559                         ret = gst_structure_get_int (structure, "width", &info.width);
560                         ret &= gst_structure_get_int (structure, "height", &info.height);
561                         framerate = gst_structure_get_value (structure, "framerate");
562                         if (GST_VALUE_HOLDS_FRACTION(framerate)) {
563                                 info.fps_n = gst_value_get_fraction_numerator (framerate);
564                                 info.fps_d = gst_value_get_fraction_denominator (framerate);
565                         }
566                         GST_DEBUG_OBJECT (self, "set caps %" GST_PTR_FORMAT, caps);
567                         gst_caps_replace (&self->current_caps, caps);
568
569                         g_mutex_unlock (&self->mutex);
570                         if (gst_caps_is_fixed(caps) && gst_dreamvideosource_set_format(self, &info))
571                                 ret = gst_pad_push_event (bsrc->srcpad, gst_event_new_caps (caps));
572                 }
573                 else {
574                         GST_WARNING_OBJECT (self, "unsupported caps: %" GST_PTR_FORMAT, caps);
575                         ret = FALSE;
576                 }
577         }
578         if (current_caps)
579                 gst_caps_unref (current_caps);
580         g_mutex_unlock (&self->mutex);
581         return ret;
582 }
583
584 static GstCaps *
585 gst_dreamvideosource_fixate (GstBaseSrc * bsrc, GstCaps * caps)
586 {
587         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (bsrc);
588         GstStructure *structure;
589
590         caps = gst_caps_make_writable (caps);
591         structure = gst_caps_get_structure (caps, 0);
592
593         if (gst_structure_has_field (structure, "width"))
594                 gst_structure_fixate_field_nearest_int (structure, "width", DEFAULT_WIDTH);
595         if (gst_structure_has_field (structure, "height"))
596                 gst_structure_fixate_field_nearest_int (structure, "height", DEFAULT_HEIGHT);
597         if (gst_structure_has_field (structure, "framerate"))
598                 gst_structure_fixate_field_nearest_fraction (structure, "framerate", DEFAULT_FRAMERATE, 1);
599         if (gst_structure_has_field (structure, "display-aspect-ratio"))
600                 gst_structure_fixate_field_nearest_fraction (structure, "display-aspect-ratio", DEFAULT_WIDTH, DEFAULT_HEIGHT);
601
602         caps = GST_BASE_SRC_CLASS (parent_class)->fixate (bsrc, caps);
603         GST_DEBUG_OBJECT (self, "fixated caps: %" GST_PTR_FORMAT, caps);
604         return caps;
605 }
606
607 static gboolean gst_dreamvideosource_query (GstBaseSrc * bsrc, GstQuery * query)
608 {
609         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (bsrc);
610         gboolean ret = TRUE;
611
612         switch (GST_QUERY_TYPE (query)) {
613                 case GST_QUERY_LATENCY:{
614                         if (self->video_info.fps_n) {
615                                 GstClockTime min, max;
616
617                                 g_mutex_lock (&self->mutex);
618                                 min = gst_util_uint64_scale_ceil (GST_SECOND, self->video_info.fps_d, self->video_info.fps_n);
619                                 g_mutex_unlock (&self->mutex);
620
621                                 max = self->buffer_size * min;
622
623                                 gst_query_set_latency (query, TRUE, min, max);
624                                 GST_DEBUG_OBJECT (bsrc, "set LATENCY QUERY %" GST_PTR_FORMAT, query);
625                                 ret = TRUE;
626                         } else {
627                                 ret = FALSE;
628                         }
629                         break;
630                 }
631                 default:
632                         ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
633                         break;
634         }
635         return ret;
636 }
637
638 static gboolean gst_dreamvideosource_unlock (GstBaseSrc * bsrc)
639 {
640         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (bsrc);
641         GST_DEBUG_OBJECT (self, "stop creating buffers");
642         g_mutex_lock (&self->mutex);
643         self->flushing = TRUE;
644         GST_DEBUG_OBJECT (self, "set flushing TRUE");
645         g_cond_signal (&self->cond);
646         g_mutex_unlock (&self->mutex);
647         return TRUE;
648 }
649
650 static gboolean gst_dreamvideosource_unlock_stop (GstBaseSrc * bsrc)
651 {
652         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (bsrc);
653         GST_DEBUG_OBJECT (self, "start creating buffers...");
654         g_mutex_lock (&self->mutex);
655         self->flushing = FALSE;
656         g_queue_foreach (&self->current_frames, (GFunc) gst_buffer_unref, NULL);
657         g_queue_clear (&self->current_frames);
658         g_mutex_unlock (&self->mutex);
659         return TRUE;
660 }
661
662 static void gst_dreamvideosource_read_thread_func (GstDreamVideoSource * self)
663 {
664         EncoderInfo *enc = self->encoder;
665         GstDreamSourceReadthreadState state = READTHREADSTATE_NONE;
666         GstBuffer *readbuf;
667
668         if (!enc) {
669                 GST_WARNING_OBJECT (self, "encoder device not opened!");
670                 return;
671         }
672
673         GST_DEBUG_OBJECT (self, "enter read thread");
674
675         GstMessage *message;
676         GValue val = { 0 };
677
678         message = gst_message_new_stream_status (GST_OBJECT_CAST (self), GST_STREAM_STATUS_TYPE_ENTER, GST_ELEMENT_CAST (GST_OBJECT_PARENT(self)));
679         g_value_init (&val, GST_TYPE_G_THREAD);
680         g_value_set_boxed (&val, self->readthread);
681         gst_message_set_stream_status_object (message, &val);
682         g_value_unset (&val);
683         GST_DEBUG_OBJECT (self, "posting ENTER stream status");
684         gst_element_post_message (GST_ELEMENT_CAST (self), message);
685         GstClockTime clock_time, base_time;
686         gboolean discont = TRUE;
687
688         while (TRUE) {
689                 readbuf = NULL;
690                 {
691                         if (state == READTHREADSTATE_STOP)
692                                 goto stop_running;
693
694                         struct pollfd rfd[2];
695                         int timeout, nfds;
696
697                         rfd[0].fd = READ_SOCKET (self);
698                         rfd[0].events = POLLIN | POLLERR | POLLHUP | POLLPRI;
699                         rfd[1].revents = 0;
700                         rfd[1].events = POLLIN;
701                         nfds = 1;
702                         timeout = 0;
703
704                         if (state <= READTRREADSTATE_PAUSED)
705                                 timeout = 200;
706                         else if (state == READTRREADSTATE_RUNNING && self->descriptors_available == 0)
707                         {
708                                 rfd[1].fd = enc->fd;
709                                 self->descriptors_count = 0;
710                                 timeout = 200;
711                                 nfds = 2;
712                         }
713
714                         int ret = poll(rfd, nfds, timeout);
715
716                         if (G_UNLIKELY (ret == -1))
717                         {
718                                 GST_ERROR_OBJECT (self, "SELECT ERROR!");
719                                 goto stop_running;
720                         }
721                         else if ( ret == 0 && self->descriptors_available == 0 )
722                         {
723                                 g_mutex_lock (&self->mutex);
724                                 gst_clock_get_internal_time(self->encoder_clock);
725                                 if (self->flushing)
726                                 {
727                                         GST_DEBUG_OBJECT (self, "FLUSHING!");
728                                         g_cond_signal (&self->cond);
729                                         g_mutex_unlock (&self->mutex);
730                                         continue;
731                                 }
732                                 g_mutex_unlock (&self->mutex);
733                                 GST_DEBUG_OBJECT (self, "SELECT TIMEOUT");
734                                 discont = TRUE;
735 //                              readbuf = gst_buffer_new();
736                         }
737                         else if ( rfd[0].revents )
738                         {
739                                 char command;
740                                 READ_COMMAND (self, command, ret);
741                                 switch (command) {
742                                         case CONTROL_STOP:
743                                                 GST_DEBUG_OBJECT (self, "CONTROL_STOP!");
744                                                 state = READTHREADSTATE_STOP;
745                                                 break;
746                                         case CONTROL_PAUSE:
747                                                 GST_DEBUG_OBJECT (self, "CONTROL_PAUSE!");
748                                                 state = READTRREADSTATE_PAUSED;
749                                                 break;
750                                         case CONTROL_RUN:
751                                                 GST_DEBUG_OBJECT (self, "CONTROL_RUN");
752                                                 state = READTRREADSTATE_RUNNING;
753                                                 break;
754                                         default:
755                                                 GST_ERROR_OBJECT (self, "illegal control socket command %c received!", command);
756                                 }
757                                 continue;
758                         }
759                         else if ( G_LIKELY(rfd[1].revents & POLLIN) )
760                         {
761                                 int rlen = read(enc->fd, enc->buffer, VBUFSIZE);
762                                 if (G_UNLIKELY (!self->encoder_clock))
763                                 {
764                                         GST_DEBUG_OBJECT(self, "no encoder clock yet... continue");
765                                         continue;
766                                 }
767                                 clock_time = gst_clock_get_internal_time (self->encoder_clock);
768                                 base_time = gst_element_get_base_time(GST_ELEMENT(self));
769                                 if (rlen <= 0 || rlen % VBDSIZE ) {
770                                         if ( errno == 512 )
771                                                 goto stop_running;
772                                         GST_WARNING_OBJECT (self, "read error %s (%i)", strerror(errno), errno);
773                                         goto stop_running;
774                                 }
775                                 self->descriptors_available = rlen / VBDSIZE;
776                                 GST_LOG_OBJECT (self, "encoder buffer was empty, %d descriptors available", self->descriptors_available);
777                         }
778                 }
779
780                 while (self->descriptors_count < self->descriptors_available)
781                 {
782                         GstClockTime encoder_dts = GST_CLOCK_TIME_NONE;
783                         GstClockTime encoder_pts = GST_CLOCK_TIME_NONE;
784                         GstClockTime result_dts = GST_CLOCK_TIME_NONE;
785                         GstClockTime result_pts = GST_CLOCK_TIME_NONE;
786                         gint64 dts_pts_offset;
787                         gboolean skip_frame = FALSE;
788
789                         off_t offset = self->descriptors_count * VBDSIZE;
790                         VideoBufferDescriptor *desc = (VideoBufferDescriptor*)(&enc->buffer[offset]);
791
792                         uint32_t f = desc->stCommon.uiFlags;
793
794                         GST_LOG_OBJECT (self, "descriptors_count=%d, descriptors_available=%d\tuiOffset=%d, uiLength=%d", self->descriptors_count, self->descriptors_available, desc->stCommon.uiOffset, desc->stCommon.uiLength);
795
796                         if (G_UNLIKELY (f & CDB_FLAG_METADATA))
797                         {
798                                 GST_LOG_OBJECT (self, "CDB_FLAG_METADATA... skip outdated packet");
799                                 self->descriptors_count = self->descriptors_available;
800                                 continue;
801                         }
802
803                         // uiDTS since kernel driver booted
804                         if (f & VBD_FLAG_DTS_VALID && desc->uiDTS)
805                         {
806                                 encoder_dts = MPEGTIME_TO_GSTTIME(desc->uiDTS);
807                                 GST_LOG_OBJECT (self, "f & VBD_FLAG_DTS_VALID && encoder's uiDTS=%" GST_TIME_FORMAT"", GST_TIME_ARGS(encoder_dts));
808
809                                 g_mutex_lock (&self->mutex);
810                                 if (G_UNLIKELY (self->dts_offset == GST_CLOCK_TIME_NONE && self->flushing == FALSE))
811                                 {
812                                         if (self->dreamaudiosrc)
813                                         {
814                                                 guint64 audiosource_dts_offset;
815                                                 g_signal_emit_by_name(self->dreamaudiosrc, "get-dts-offset", &audiosource_dts_offset);
816                                                 if (audiosource_dts_offset != GST_CLOCK_TIME_NONE)
817                                                 {
818                                                         GST_DEBUG_OBJECT (self, "use DREAMAUDIOSOURCE's dts_offset=%" GST_TIME_FORMAT "", GST_TIME_ARGS (audiosource_dts_offset) );
819                                                         self->dts_offset = audiosource_dts_offset;
820                                                 }
821                                         }
822                                         if (self->dts_offset == GST_CLOCK_TIME_NONE)
823                                         {
824                                                 self->dts_offset = encoder_dts - clock_time;
825                                                 GST_DEBUG_OBJECT (self, "use encoder_dts-clock_time as dts_offset (%" GST_TIME_FORMAT" = %" GST_TIME_FORMAT" - %" GST_TIME_FORMAT")", GST_TIME_ARGS (self->dts_offset), GST_TIME_ARGS (encoder_dts), GST_TIME_ARGS (clock_time));
826                                         }
827                                 }
828                                 if (G_UNLIKELY (self->dts_valid == FALSE))
829                                         self->dts_valid = TRUE;
830                                 g_mutex_unlock (&self->mutex);
831                         }
832
833                         g_mutex_lock (&self->mutex);
834                         if (G_UNLIKELY (self->dts_valid == FALSE))
835                         {
836                                 GST_DEBUG_OBJECT (self, "dts_valid not set, skipping frame...");
837                                 self->descriptors_count++;
838                                 g_mutex_unlock (&self->mutex);
839                                 break;
840                         }
841                         else
842                                 g_mutex_unlock (&self->mutex);
843
844 //                      if (self->video_info.fps_d)
845 //                              GST_BUFFER_DURATION(readbuf) = gst_util_uint64_scale (GST_SECOND, self->video_info.fps_d, self->video_info.fps_n);
846
847                         if (!skip_frame && encoder_dts != GST_CLOCK_TIME_NONE)
848                         {
849                                 if (f & CDB_FLAG_PTS_VALID)
850                                         encoder_pts = MPEGTIME_TO_GSTTIME(desc->stCommon.uiPTS);
851                                 else
852                                         encoder_pts = encoder_dts;
853                                 dts_pts_offset = encoder_pts - encoder_dts;
854
855                                 GstClockTime orig_dts_clock_time = encoder_dts - self->dts_offset;
856                                 GstClockTime orig_pts_clock_time = orig_dts_clock_time + dts_pts_offset;
857                                 GstClockTime calib_dts_clock_time = orig_dts_clock_time;
858
859                                 GstClockTime internal, external;
860                                 GstClockTime rate_n, rate_d;
861                                 GstClockTimeDiff diff;
862
863                                 gst_clock_get_calibration (self->encoder_clock, &internal, &external, &rate_n, &rate_d);
864
865                                 if (internal > orig_dts_clock_time) {
866                                         diff = internal - orig_dts_clock_time;
867                                         diff = gst_util_uint64_scale (diff, rate_n, rate_d);
868                                         calib_dts_clock_time = external - diff;
869                                 } else {
870                                         diff = orig_dts_clock_time - internal;
871                                         diff = gst_util_uint64_scale (diff, rate_n, rate_d);
872                                         calib_dts_clock_time = external + diff;
873                                 }
874
875                                 if ( calib_dts_clock_time < base_time )
876                                 {
877                                         GST_DEBUG_OBJECT (self, "calib_dts_clock_time < base_time, skipping frame...");
878                                         skip_frame = TRUE;
879                                 }
880                                 result_dts = calib_dts_clock_time - base_time;
881                                 result_pts = result_dts + dts_pts_offset;
882
883 #define extra_timestamp_debug
884 #ifdef extra_timestamp_debug
885                                 GstClockTime my_int_time = gst_clock_get_internal_time(self->encoder_clock);
886                                 GstClockTime pipeline_int_time = GST_CLOCK_TIME_NONE;
887                                 GstClock *elemclk = gst_element_get_clock (GST_ELEMENT (self));
888                                 if (elemclk)
889                                 {
890                                         pipeline_int_time = gst_clock_get_internal_time(elemclk);
891                                         gst_object_unref (elemclk);
892                                 }
893
894                                 GST_LOG_OBJECT (self, "post-calibration\n"
895                                 "%" GST_TIME_FORMAT "=base_time       %" GST_TIME_FORMAT "=clock_time            %" PRId64 "=dts_pts_offset\n"
896                                 "%" GST_TIME_FORMAT "=encoder_dts     %" GST_TIME_FORMAT "=orig_dts_clock_time   %" GST_TIME_FORMAT "=calib_dts_clock_time   %" GST_TIME_FORMAT "=result_dts\n"
897                                 "%" GST_TIME_FORMAT "=encoder_pts     %" GST_TIME_FORMAT "=orig_pts_clock_time                                            %" GST_TIME_FORMAT "=result_pts\n"
898                                 "%" GST_TIME_FORMAT "=internal        %" GST_TIME_FORMAT "=external              %" GST_TIME_FORMAT "=diff\n"
899                                 "%" GST_TIME_FORMAT "=rate_n          %" GST_TIME_FORMAT "=rate_d\n"
900                                 "%" GST_TIME_FORMAT "=my_int_time     %" GST_TIME_FORMAT "=pipeline_int_time\n"
901                                 ,
902                                 GST_TIME_ARGS (base_time), GST_TIME_ARGS (clock_time), dts_pts_offset,
903                                 GST_TIME_ARGS (encoder_dts), GST_TIME_ARGS (orig_dts_clock_time), GST_TIME_ARGS (calib_dts_clock_time), GST_TIME_ARGS (result_dts),
904                                 GST_TIME_ARGS (encoder_pts), GST_TIME_ARGS (orig_pts_clock_time), GST_TIME_ARGS (result_pts),
905                                 GST_TIME_ARGS (internal), GST_TIME_ARGS (external), GST_TIME_ARGS (diff),
906                                 GST_TIME_ARGS (rate_n), GST_TIME_ARGS (rate_d),
907                                 GST_TIME_ARGS (my_int_time), GST_TIME_ARGS (pipeline_int_time)
908                                 );
909 #endif
910                         }
911
912                         if (!skip_frame)
913                         {
914                                 readbuf = gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY, enc->cdb, VMMAPSIZE, desc->stCommon.uiOffset, desc->stCommon.uiLength, self, NULL);
915                                 if (result_dts != GST_CLOCK_TIME_NONE)
916                                 {
917                                         GST_BUFFER_DTS(readbuf) = result_dts;
918                                         GST_BUFFER_PTS(readbuf) = result_pts;
919                                 }
920                         }
921
922 #ifdef dump
923                         int wret = write(self->dumpfd, (unsigned char*)(enc->cdb + desc->stCommon.uiOffset), desc->stCommon.uiLength);
924                         GST_LOG_OBJECT (self, "read %i dumped %i total %" G_GSIZE_FORMAT " ", desc->stCommon.uiLength, wret, gst_buffer_get_size (*outbuf) );
925 #endif
926                         self->descriptors_count++;
927                         break;
928                 }
929
930                 if (self->descriptors_count == self->descriptors_available)
931                 {
932                         GST_LOG_OBJECT (self, "self->descriptors_count == self->descriptors_available -> release %i consumed descriptors", self->descriptors_count);
933                         /* release consumed descs */
934                         if (write(enc->fd, &self->descriptors_count, sizeof(self->descriptors_count)) != sizeof(self->descriptors_count)) {
935                                 GST_WARNING_OBJECT (self, "release consumed descs write error!");
936                                 goto stop_running;
937                         }
938                         self->descriptors_available = 0;
939                 }
940
941                 if (readbuf)
942                 {
943                         g_mutex_lock (&self->mutex);
944                         if (!self->flushing)
945                         {
946                                 while (g_queue_get_length (&self->current_frames) >= self->buffer_size)
947                                 {
948                                         GstBuffer * oldbuf = g_queue_pop_head (&self->current_frames);
949                                         GST_WARNING_OBJECT (self, "dropping %" GST_PTR_FORMAT " because of queue overflow! buffers count=%i", oldbuf, g_queue_get_length (&self->current_frames));
950                                         gst_buffer_unref(oldbuf);
951                                         GST_BUFFER_FLAG_SET ((GstBuffer *) g_queue_peek_head (&self->current_frames), GST_BUFFER_FLAG_DISCONT);
952                                 }
953                                 if (discont)
954                                 {
955                                         GST_BUFFER_FLAG_SET (readbuf, GST_BUFFER_FLAG_DISCONT);
956                                         discont = FALSE;
957                                 }
958                                 g_queue_push_tail (&self->current_frames, readbuf);
959                                 GST_INFO_OBJECT (self, "read %" GST_PTR_FORMAT " to queue...", readbuf );
960                                 g_cond_signal (&self->cond);
961                         }
962                         else
963                                 gst_buffer_unref(readbuf);
964 //                      g_cond_signal (&self->cond);
965                         g_mutex_unlock (&self->mutex);
966                 }
967         }
968
969         g_assert_not_reached ();
970         return;
971
972         stop_running:
973         {
974                 g_mutex_unlock (&self->mutex);
975                 g_cond_signal (&self->cond);
976                 GST_DEBUG ("stop running, exit thread");
977                 message = gst_message_new_stream_status (GST_OBJECT_CAST (self), GST_STREAM_STATUS_TYPE_ENTER, GST_ELEMENT_CAST (GST_OBJECT_PARENT(self)));
978                 g_value_init (&val, GST_TYPE_G_THREAD);
979                 g_value_set_boxed (&val, self->readthread);
980                 gst_message_set_stream_status_object (message, &val);
981                 g_value_unset (&val);
982                 GST_DEBUG_OBJECT (self, "posting LEAVE stream status");
983                 gst_element_post_message (GST_ELEMENT_CAST (self), message);
984                 return;
985         }
986 }
987
988 static GstFlowReturn
989 gst_dreamvideosource_create (GstPushSrc * psrc, GstBuffer ** outbuf)
990 {
991         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (psrc);
992
993         GST_LOG_OBJECT (self, "new buffer requested. queue has %i buffers", g_queue_get_length (&self->current_frames));
994
995         g_mutex_lock (&self->mutex);
996         while (g_queue_is_empty (&self->current_frames) && !self->flushing)
997         {
998                 GST_INFO_OBJECT (self, "waiting for buffer from encoder");
999                 g_cond_wait (&self->cond, &self->mutex);
1000         }
1001
1002         *outbuf = g_queue_pop_head (&self->current_frames);
1003         g_mutex_unlock (&self->mutex);
1004
1005         if (*outbuf)
1006         {
1007                 GST_INFO_OBJECT (self, "pushing %" GST_PTR_FORMAT ". queue has %i buffers", *outbuf, g_queue_get_length (&self->current_frames));
1008                 return GST_FLOW_OK;
1009         }
1010         GST_INFO_OBJECT (self, "FLUSHING");
1011         return GST_FLOW_FLUSHING;
1012 }
1013
1014
1015 static GstStateChangeReturn gst_dreamvideosource_change_state (GstElement * element, GstStateChange transition)
1016 {
1017         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (element);
1018         GstStateChangeReturn sret = GST_STATE_CHANGE_SUCCESS;
1019         int ret;
1020
1021         switch (transition) {
1022                 case GST_STATE_CHANGE_NULL_TO_READY:
1023                 {
1024                         if (!gst_dreamvideosource_encoder_init (self))
1025                         {
1026                                 GError *err = g_error_new (GST_RESOURCE_ERROR, GST_RESOURCE_ERROR_READ, "Can't initialize encoder device");
1027                                 GstMessage *msg = gst_message_new_error (GST_OBJECT (self), err, NULL);
1028                                 gst_element_post_message (element, msg);
1029                                 g_error_free (err);
1030                                 return GST_STATE_CHANGE_FAILURE;
1031                         }
1032                         GST_DEBUG_OBJECT (self, "GST_STATE_CHANGE_NULL_TO_READY");
1033                         break;
1034                 }
1035                 case GST_STATE_CHANGE_READY_TO_PAUSED:
1036                         GST_LOG_OBJECT (self, "GST_STATE_CHANGE_READY_TO_PAUSED");
1037                         self->dreamaudiosrc = gst_bin_get_by_name_recurse_up(GST_BIN(GST_ELEMENT_PARENT(self)), "dreamaudiosource0");
1038                 #ifdef PROVIDE_CLOCK
1039                         if (self->dreamaudiosrc)
1040                         {
1041                                 self->encoder_clock = gst_element_provide_clock (self->dreamaudiosrc);
1042                                 GST_DEBUG_OBJECT (self, "using dreamaudiosrc's encoder_clock = %" GST_PTR_FORMAT, self->encoder_clock);
1043                         } else {
1044                                 self->encoder_clock = gst_dreamsource_clock_new ("GstDreamVideoSinkClock", self->encoder->fd);
1045                                 GST_OBJECT_FLAG_SET (self, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
1046                                 GstMessage* msg;
1047                                 msg = gst_message_new_clock_provide (GST_OBJECT_CAST (element), self->encoder_clock, TRUE);
1048                                 GST_DEBUG_OBJECT (self, "new clock: %" GST_PTR_FORMAT " %" GST_PTR_FORMAT " typename=%s", self->encoder_clock, msg, GST_MESSAGE_TYPE_NAME(msg));
1049                                 gst_element_post_message (element, msg);
1050                         }
1051                 #endif
1052                         self->dts_offset = GST_CLOCK_TIME_NONE;
1053                         self->flushing = TRUE;
1054                         self->readthread = g_thread_try_new ("dreamvideosrc-read", (GThreadFunc) gst_dreamvideosource_read_thread_func, self, NULL);
1055                         GST_DEBUG_OBJECT (self, "started readthread @%p", self->readthread );
1056                         break;
1057                 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1058                         g_mutex_lock (&self->mutex);
1059                         GST_LOG_OBJECT (self, "GST_STATE_CHANGE_PAUSED_TO_PLAYING");
1060                         self->dts_valid = FALSE;
1061                         GstClock *pipeline_clock = gst_element_get_clock (GST_ELEMENT (self));
1062                         if (pipeline_clock)
1063                         {
1064                                 if (self->dreamaudiosrc)
1065                                         GST_DEBUG_OBJECT (self, "dreamaudiosource owns the clock and is responsible for slaving it");
1066                                 else if (pipeline_clock != self->encoder_clock)
1067                                 {
1068                                         gst_clock_set_master (self->encoder_clock, pipeline_clock);
1069                                         GST_DEBUG_OBJECT (self, "slaved %" GST_PTR_FORMAT "to pipeline_clock %" GST_PTR_FORMAT "", self->encoder_clock, pipeline_clock);
1070                                 }
1071                                 else
1072                                         GST_DEBUG_OBJECT (self, "encoder_clock is master clock");
1073                         }
1074                                 else
1075                                         GST_WARNING_OBJECT (self, "no pipeline clock!");
1076                         ret = ioctl(self->encoder->fd, VENC_START);
1077                         if ( ret != 0 )
1078                                 goto fail;
1079                         self->descriptors_available = 0;
1080                         CLEAR_COMMAND (self);
1081                         g_mutex_unlock (&self->mutex);
1082                         break;
1083                 default:
1084                         break;
1085         }
1086
1087         if (GST_ELEMENT_CLASS (parent_class)->change_state)
1088                 sret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1089
1090         switch (transition) {
1091                 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1092                         g_mutex_lock (&self->mutex);
1093                         SEND_COMMAND (self, CONTROL_RUN);
1094                         GST_INFO_OBJECT (self, "started encoder!");
1095                         g_mutex_unlock (&self->mutex);
1096                         break;
1097                 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1098                         g_mutex_lock (&self->mutex);
1099                         self->flushing = TRUE;
1100                         GST_DEBUG_OBJECT (self, "GST_STATE_CHANGE_PLAYING_TO_PAUSED self->descriptors_count=%i self->descriptors_available=%i", self->descriptors_count, self->descriptors_available);
1101                         SEND_COMMAND (self, CONTROL_PAUSE);
1102                         if (self->descriptors_count < self->descriptors_available)
1103                                 self->descriptors_count = self->descriptors_available;
1104                         if (self->descriptors_count)
1105                                 write(self->encoder->fd, &self->descriptors_count, sizeof(self->descriptors_count));
1106                         ret = ioctl(self->encoder->fd, VENC_STOP);
1107                         if ( ret != 0 )
1108                                 goto fail;
1109 #ifdef PROVIDE_CLOCK
1110                         gst_clock_set_master (self->encoder_clock, NULL);
1111 #endif
1112                         GST_INFO_OBJECT (self, "stopped encoder!");
1113                         g_mutex_unlock (&self->mutex);
1114                         break;
1115                 case GST_STATE_CHANGE_PAUSED_TO_READY:
1116                         GST_DEBUG_OBJECT (self,"GST_STATE_CHANGE_PAUSED_TO_READY");
1117 #ifdef PROVIDE_CLOCK
1118                         gst_element_post_message (element, gst_message_new_clock_lost (GST_OBJECT_CAST (element), self->encoder_clock));
1119                         if (!self->dreamaudiosrc)
1120                                 gst_clock_set_calibration (self->encoder_clock, 0, 0, 1, 1);
1121 #endif
1122                         GST_DEBUG_OBJECT (self, "stopping readthread @%p...", self->readthread);
1123                         SEND_COMMAND (self, CONTROL_STOP);
1124                         g_thread_join (self->readthread);
1125                         if (self->dreamaudiosrc)
1126                                 gst_object_unref(self->dreamaudiosrc);
1127                         self->dreamaudiosrc = NULL;
1128                         break;
1129                 case GST_STATE_CHANGE_READY_TO_NULL:
1130                         gst_dreamvideosource_encoder_release (self);
1131                         GST_DEBUG_OBJECT (self,"GST_STATE_CHANGE_READY_TO_NULL");
1132                         break;
1133                 default:
1134                         break;
1135         }
1136
1137         return sret;
1138 fail:
1139         GST_ERROR_OBJECT(self,"can't perform encoder ioctl! error: %s (%i)", strerror(errno), errno);
1140         g_mutex_unlock (&self->mutex);
1141         return GST_STATE_CHANGE_FAILURE;
1142 }
1143
1144 static void
1145 gst_dreamvideosource_dispose (GObject * gobject)
1146 {
1147         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (gobject);
1148 #ifdef PROVIDE_CLOCK
1149         if (self->encoder_clock) {
1150                 gst_object_unref (self->encoder_clock);
1151                 self->encoder_clock = NULL;
1152         }
1153 #endif
1154 #ifdef dump
1155         close(self->dumpfd);
1156 #endif
1157         if (self->current_caps)
1158                 gst_caps_unref(self->current_caps);
1159         if (self->new_caps)
1160                 gst_caps_unref(self->new_caps);
1161         g_mutex_clear (&self->mutex);
1162         g_cond_clear (&self->cond);
1163         GST_DEBUG_OBJECT (self, "disposed");
1164         G_OBJECT_CLASS (parent_class)->dispose (gobject);
1165 }
1166
1167 #ifdef PROVIDE_CLOCK
1168 static GstClock *gst_dreamvideosource_provide_clock (GstElement * element)
1169 {
1170         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (element);
1171
1172         if (!self->encoder || self->encoder->fd < 0)
1173         {
1174                 GST_DEBUG_OBJECT (self, "encoder device not started, can't provide clock!");
1175                 return NULL;
1176         }
1177
1178         if (!self->encoder_clock)
1179         {
1180                 GST_DEBUG_OBJECT (self, "this element is not the clock provider!");
1181                 return NULL;
1182         }
1183
1184         return GST_CLOCK_CAST (gst_object_ref (self->encoder_clock));
1185 }
1186 #endif