fix a few warnings
[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_LIVE
67 #define DEFAULT_BUFFER_SIZE 30
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_ELEMENT_ERROR (self, RESOURCE, OPEN_READ_WRITE, (NULL), GST_ERROR_SYSTEM);
398                 return GST_STATE_CHANGE_FAILURE;
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         if (self->new_caps)
490         {
491                 GST_LOG_OBJECT (self, "gst_dreamvideosource_getcaps has new_caps %" GST_PTR_FORMAT "", self->new_caps);
492                 if (self->current_caps)
493                 {
494                         gst_caps_replace (&caps, self->new_caps);
495                         self->new_caps = NULL;
496                 }
497                 else
498                         caps = gst_caps_copy (self->new_caps);
499         } else if (self->current_caps == NULL) {
500                 GstPadTemplate *pad_template;
501                 pad_template = gst_element_class_get_pad_template (GST_ELEMENT_GET_CLASS(self), "src");
502                 g_return_val_if_fail (pad_template != NULL, NULL);
503                 caps = gst_pad_template_get_caps (pad_template);
504         } else
505                 caps = gst_caps_copy(self->current_caps);
506
507         GST_LOG_OBJECT (self, "gst_dreamvideosource_getcaps %" GST_PTR_FORMAT " filter %" GST_PTR_FORMAT, caps, filter);
508
509         if (filter) {
510                 GstCaps *intersection;
511                 intersection = gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
512                 gst_caps_unref (caps);
513                 caps = intersection;
514         }
515
516         GST_LOG_OBJECT (self, "return caps %" GST_PTR_FORMAT, caps);
517         return caps;
518 }
519
520 static gboolean
521 gst_dreamvideosource_setcaps (GstBaseSrc * bsrc, GstCaps * caps)
522 {
523         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (bsrc);
524         GstCaps *current_caps;
525         const GstStructure *structure;
526         VideoFormatInfo info;
527         gboolean ret;
528         const GValue *framerate;
529
530         g_mutex_lock (&self->mutex);
531         structure = gst_caps_get_structure (caps, 0);
532
533         current_caps = gst_pad_get_current_caps (GST_BASE_SRC_PAD (bsrc));
534
535         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);
536
537         if (current_caps && gst_caps_is_equal (current_caps, caps)) {
538                 GST_LOG_OBJECT (self, "New caps equal to old ones: %" GST_PTR_FORMAT, caps);
539                 ret = TRUE;
540         } else {
541                 GstState state;
542                 gst_element_get_state (GST_ELEMENT(self), &state, NULL, 1*GST_MSECOND);
543                 if (state == GST_STATE_PLAYING)
544                 {
545                         GST_WARNING_OBJECT (self, "can't change caps while in PLAYING state %" GST_PTR_FORMAT, caps);
546                         g_mutex_unlock (&self->mutex);
547                         return TRUE;
548                 }
549                 else if (gst_structure_has_name (structure, "video/x-h264"))
550                 {
551                         memset (&info, 0, sizeof(VideoFormatInfo));
552                         ret = gst_structure_get_int (structure, "width", &info.width);
553                         ret &= gst_structure_get_int (structure, "height", &info.height);
554                         framerate = gst_structure_get_value (structure, "framerate");
555                         if (GST_VALUE_HOLDS_FRACTION(framerate)) {
556                                 info.fps_n = gst_value_get_fraction_numerator (framerate);
557                                 info.fps_d = gst_value_get_fraction_denominator (framerate);
558                         }
559                         GST_DEBUG_OBJECT (self, "set caps %" GST_PTR_FORMAT, caps);
560                         gst_caps_replace (&self->current_caps, caps);
561
562                         g_mutex_unlock (&self->mutex);
563                         if (gst_caps_is_fixed(caps) && gst_dreamvideosource_set_format(self, &info))
564                                 ret = gst_pad_push_event (bsrc->srcpad, gst_event_new_caps (caps));
565                 }
566                 else {
567                         GST_WARNING_OBJECT (self, "unsupported caps: %" GST_PTR_FORMAT, caps);
568                         ret = FALSE;
569                 }
570         }
571         if (current_caps)
572                 gst_caps_unref (current_caps);
573         g_mutex_unlock (&self->mutex);
574         return ret;
575 }
576
577 static GstCaps *
578 gst_dreamvideosource_fixate (GstBaseSrc * bsrc, GstCaps * caps)
579 {
580         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (bsrc);
581         GstStructure *structure;
582
583         caps = gst_caps_make_writable (caps);
584         structure = gst_caps_get_structure (caps, 0);
585
586         if (gst_structure_has_field (structure, "width"))
587                 gst_structure_fixate_field_nearest_int (structure, "width", DEFAULT_WIDTH);
588         if (gst_structure_has_field (structure, "height"))
589                 gst_structure_fixate_field_nearest_int (structure, "height", DEFAULT_HEIGHT);
590         if (gst_structure_has_field (structure, "framerate"))
591                 gst_structure_fixate_field_nearest_fraction (structure, "framerate", DEFAULT_FRAMERATE, 1);
592         if (gst_structure_has_field (structure, "display-aspect-ratio"))
593                 gst_structure_fixate_field_nearest_fraction (structure, "display-aspect-ratio", DEFAULT_WIDTH, DEFAULT_HEIGHT);
594
595         caps = GST_BASE_SRC_CLASS (parent_class)->fixate (bsrc, caps);
596         GST_DEBUG_OBJECT (self, "fixated caps: %" GST_PTR_FORMAT, caps);
597         return caps;
598 }
599
600 static gboolean gst_dreamvideosource_query (GstBaseSrc * bsrc, GstQuery * query)
601 {
602         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (bsrc);
603         gboolean ret = TRUE;
604
605         switch (GST_QUERY_TYPE (query)) {
606                 case GST_QUERY_LATENCY:{
607                         if (self->video_info.fps_n) {
608                                 GstClockTime min, max;
609
610                                 g_mutex_lock (&self->mutex);
611                                 min = gst_util_uint64_scale_ceil (GST_SECOND, self->video_info.fps_d, self->video_info.fps_n);
612                                 g_mutex_unlock (&self->mutex);
613
614                                 max = self->buffer_size * min;
615
616                                 gst_query_set_latency (query, TRUE, min, max);
617                                 GST_DEBUG_OBJECT (bsrc, "set LATENCY QUERY %" GST_PTR_FORMAT, query);
618                                 ret = TRUE;
619                         } else {
620                                 ret = FALSE;
621                         }
622                         break;
623                 }
624                 default:
625                         ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
626                         break;
627         }
628         return ret;
629 }
630
631 static gboolean gst_dreamvideosource_unlock (GstBaseSrc * bsrc)
632 {
633         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (bsrc);
634         GST_DEBUG_OBJECT (self, "stop creating buffers");
635         g_mutex_lock (&self->mutex);
636         self->flushing = TRUE;
637         GST_DEBUG_OBJECT (self, "set flushing TRUE");
638         g_cond_signal (&self->cond);
639         g_mutex_unlock (&self->mutex);
640         return TRUE;
641 }
642
643 static gboolean gst_dreamvideosource_unlock_stop (GstBaseSrc * bsrc)
644 {
645         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (bsrc);
646         GST_DEBUG_OBJECT (self, "start creating buffers...");
647         g_mutex_lock (&self->mutex);
648         self->flushing = FALSE;
649         g_queue_foreach (&self->current_frames, (GFunc) gst_buffer_unref, NULL);
650         g_queue_clear (&self->current_frames);
651         g_mutex_unlock (&self->mutex);
652         return TRUE;
653 }
654
655 static void gst_dreamvideosource_read_thread_func (GstDreamVideoSource * self)
656 {
657         EncoderInfo *enc = self->encoder;
658         GstDreamSourceReadthreadState state = READTHREADSTATE_NONE;
659         GstBuffer *readbuf;
660
661         if (!enc) {
662                 GST_WARNING_OBJECT (self, "encoder device not opened!");
663                 return;
664         }
665
666         GST_DEBUG_OBJECT (self, "enter read thread");
667
668         GstMessage *message;
669         GValue val = { 0 };
670
671         message = gst_message_new_stream_status (GST_OBJECT_CAST (self), GST_STREAM_STATUS_TYPE_ENTER, GST_ELEMENT_CAST (GST_OBJECT_PARENT(self)));
672         g_value_init (&val, GST_TYPE_G_THREAD);
673         g_value_set_boxed (&val, self->readthread);
674         gst_message_set_stream_status_object (message, &val);
675         g_value_unset (&val);
676         GST_DEBUG_OBJECT (self, "posting ENTER stream status");
677         gst_element_post_message (GST_ELEMENT_CAST (self), message);
678         GstClockTime clock_time, base_time;
679         gboolean discont = TRUE;
680
681         while (TRUE) {
682                 readbuf = NULL;
683                 {
684                         if (state == READTHREADSTATE_STOP)
685                                 goto stop_running;
686
687                         struct pollfd rfd[2];
688                         int timeout, nfds;
689
690                         rfd[0].fd = READ_SOCKET (self);
691                         rfd[0].events = POLLIN | POLLERR | POLLHUP | POLLPRI;
692                         rfd[1].revents = 0;
693                         rfd[1].events = POLLIN;
694                         nfds = 1;
695                         timeout = 0;
696
697                         if (state <= READTRREADSTATE_PAUSED)
698                                 timeout = 200;
699                         else if (state == READTRREADSTATE_RUNNING && self->descriptors_available == 0)
700                         {
701                                 rfd[1].fd = enc->fd;
702                                 self->descriptors_count = 0;
703                                 timeout = 200;
704                                 nfds = 2;
705                         }
706
707                         int ret = poll(rfd, nfds, timeout);
708
709                         if (G_UNLIKELY (ret == -1))
710                         {
711                                 GST_ERROR_OBJECT (self, "SELECT ERROR!");
712                                 goto stop_running;
713                         }
714                         else if ( ret == 0 && self->descriptors_available == 0 )
715                         {
716                                 g_mutex_lock (&self->mutex);
717                                 gst_clock_get_internal_time(self->encoder_clock);
718                                 if (self->flushing)
719                                 {
720                                         GST_DEBUG_OBJECT (self, "FLUSHING!");
721                                         g_cond_signal (&self->cond);
722                                         g_mutex_unlock (&self->mutex);
723                                         continue;
724                                 }
725                                 g_mutex_unlock (&self->mutex);
726                                 GST_DEBUG_OBJECT (self, "SELECT TIMEOUT");
727                                 discont = TRUE;
728 //                              readbuf = gst_buffer_new();
729                         }
730                         else if ( rfd[0].revents )
731                         {
732                                 char command;
733                                 READ_COMMAND (self, command, ret);
734                                 switch (command) {
735                                         case CONTROL_STOP:
736                                                 GST_DEBUG_OBJECT (self, "CONTROL_STOP!");
737                                                 state = READTHREADSTATE_STOP;
738                                                 break;
739                                         case CONTROL_PAUSE:
740                                                 GST_DEBUG_OBJECT (self, "CONTROL_PAUSE!");
741                                                 state = READTRREADSTATE_PAUSED;
742                                                 break;
743                                         case CONTROL_RUN:
744                                                 GST_DEBUG_OBJECT (self, "CONTROL_RUN");
745                                                 state = READTRREADSTATE_RUNNING;
746                                                 break;
747                                         default:
748                                                 GST_ERROR_OBJECT (self, "illegal control socket command %c received!", command);
749                                 }
750                                 continue;
751                         }
752                         else if ( G_LIKELY(rfd[1].revents & POLLIN) )
753                         {
754                                 int rlen = read(enc->fd, enc->buffer, VBUFSIZE);
755                                 if (G_UNLIKELY (!self->encoder_clock))
756                                 {
757                                         GST_DEBUG_OBJECT(self, "no encoder clock yet... continue");
758                                         continue;
759                                 }
760                                 clock_time = gst_clock_get_internal_time (self->encoder_clock);
761                                 base_time = gst_element_get_base_time(GST_ELEMENT(self));
762                                 if (rlen <= 0 || rlen % VBDSIZE ) {
763                                         if ( errno == 512 )
764                                                 goto stop_running;
765                                         GST_WARNING_OBJECT (self, "read error %s (%i)", strerror(errno), errno);
766                                         goto stop_running;
767                                 }
768                                 self->descriptors_available = rlen / VBDSIZE;
769                                 GST_LOG_OBJECT (self, "encoder buffer was empty, %d descriptors available", self->descriptors_available);
770                         }
771                 }
772
773                 while (self->descriptors_count < self->descriptors_available)
774                 {
775                         GstClockTime encoder_dts = GST_CLOCK_TIME_NONE;
776                         GstClockTime encoder_pts = GST_CLOCK_TIME_NONE;
777                         GstClockTime result_dts = GST_CLOCK_TIME_NONE;
778                         GstClockTime result_pts = GST_CLOCK_TIME_NONE;
779                         gint64 dts_pts_offset;
780                         gboolean skip_frame = FALSE;
781
782                         off_t offset = self->descriptors_count * VBDSIZE;
783                         VideoBufferDescriptor *desc = (VideoBufferDescriptor*)(&enc->buffer[offset]);
784
785                         uint32_t f = desc->stCommon.uiFlags;
786
787                         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);
788
789                         if (G_UNLIKELY (f & CDB_FLAG_METADATA))
790                         {
791                                 GST_LOG_OBJECT (self, "CDB_FLAG_METADATA... skip outdated packet");
792                                 self->descriptors_count = self->descriptors_available;
793                                 continue;
794                         }
795
796                         // uiDTS since kernel driver booted
797                         if (f & VBD_FLAG_DTS_VALID && desc->uiDTS)
798                         {
799                                 encoder_dts = MPEGTIME_TO_GSTTIME(desc->uiDTS);
800                                 GST_LOG_OBJECT (self, "f & VBD_FLAG_DTS_VALID && encoder's uiDTS=%" GST_TIME_FORMAT"", GST_TIME_ARGS(encoder_dts));
801
802                                 g_mutex_lock (&self->mutex);
803                                 if (G_UNLIKELY (self->dts_offset == GST_CLOCK_TIME_NONE && self->flushing == FALSE))
804                                 {
805                                         if (self->dreamaudiosrc)
806                                         {
807                                                 guint64 audiosource_dts_offset;
808                                                 g_signal_emit_by_name(self->dreamaudiosrc, "get-dts-offset", &audiosource_dts_offset);
809                                                 if (audiosource_dts_offset != GST_CLOCK_TIME_NONE)
810                                                 {
811                                                         GST_DEBUG_OBJECT (self, "use DREAMAUDIOSOURCE's dts_offset=%" GST_TIME_FORMAT "", GST_TIME_ARGS (audiosource_dts_offset) );
812                                                         self->dts_offset = audiosource_dts_offset;
813                                                 }
814                                         }
815                                         if (self->dts_offset == GST_CLOCK_TIME_NONE)
816                                         {
817                                                 self->dts_offset = encoder_dts - clock_time;
818                                                 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));
819                                         }
820                                 }
821                                 if (G_UNLIKELY (self->dts_valid == FALSE))
822                                         self->dts_valid = TRUE;
823                                 g_mutex_unlock (&self->mutex);
824                         }
825
826                         g_mutex_lock (&self->mutex);
827                         if (G_UNLIKELY (self->dts_valid == FALSE))
828                         {
829                                 GST_DEBUG_OBJECT (self, "dts_valid not set, skipping frame...");
830                                 self->descriptors_count++;
831                                 g_mutex_unlock (&self->mutex);
832                                 break;
833                         }
834                         else
835                                 g_mutex_unlock (&self->mutex);
836
837 //                      if (self->video_info.fps_d)
838 //                              GST_BUFFER_DURATION(readbuf) = gst_util_uint64_scale (GST_SECOND, self->video_info.fps_d, self->video_info.fps_n);
839
840                         if (!skip_frame && encoder_dts != GST_CLOCK_TIME_NONE)
841                         {
842                                 if (f & CDB_FLAG_PTS_VALID)
843                                         encoder_pts = MPEGTIME_TO_GSTTIME(desc->stCommon.uiPTS);
844                                 else
845                                         encoder_pts = encoder_dts;
846                                 dts_pts_offset = encoder_pts - encoder_dts;
847
848                                 GstClockTime orig_dts_clock_time = encoder_dts - self->dts_offset;
849                                 GstClockTime orig_pts_clock_time = orig_dts_clock_time + dts_pts_offset;
850                                 GstClockTime calib_dts_clock_time = orig_dts_clock_time;
851
852                                 GstClockTime internal, external;
853                                 GstClockTime rate_n, rate_d;
854                                 GstClockTimeDiff diff;
855
856                                 gst_clock_get_calibration (self->encoder_clock, &internal, &external, &rate_n, &rate_d);
857
858                                 if (internal > orig_dts_clock_time) {
859                                         diff = internal - orig_dts_clock_time;
860                                         diff = gst_util_uint64_scale (diff, rate_n, rate_d);
861                                         calib_dts_clock_time = external - diff;
862                                 } else {
863                                         diff = orig_dts_clock_time - internal;
864                                         diff = gst_util_uint64_scale (diff, rate_n, rate_d);
865                                         calib_dts_clock_time = external + diff;
866                                 }
867
868                                 if ( calib_dts_clock_time < base_time )
869                                 {
870                                         GST_DEBUG_OBJECT (self, "calib_dts_clock_time < base_time, skipping frame...");
871                                         skip_frame = TRUE;
872                                 }
873                                 result_dts = calib_dts_clock_time - base_time;
874                                 result_pts = result_dts + dts_pts_offset;
875
876 #define extra_timestamp_debug
877 #ifdef extra_timestamp_debug
878                                 GstClockTime my_int_time = gst_clock_get_internal_time(self->encoder_clock);
879                                 GstClockTime pipeline_int_time = GST_CLOCK_TIME_NONE;
880                                 GstClock *elemclk = gst_element_get_clock (GST_ELEMENT (self));
881                                 if (elemclk)
882                                 {
883                                         pipeline_int_time = gst_clock_get_internal_time(elemclk);
884                                         gst_object_unref (elemclk);
885                                 }
886
887                                 GST_LOG_OBJECT (self, "post-calibration\n"
888                                 "%" GST_TIME_FORMAT "=base_time       %" GST_TIME_FORMAT "=clock_time            %" PRId64 "=dts_pts_offset\n"
889                                 "%" 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"
890                                 "%" GST_TIME_FORMAT "=encoder_pts     %" GST_TIME_FORMAT "=orig_pts_clock_time                                            %" GST_TIME_FORMAT "=result_pts\n"
891                                 "%" GST_TIME_FORMAT "=internal        %" GST_TIME_FORMAT "=external              %" GST_TIME_FORMAT "=diff\n"
892                                 "%" GST_TIME_FORMAT "=rate_n          %" GST_TIME_FORMAT "=rate_d\n"
893                                 "%" GST_TIME_FORMAT "=my_int_time     %" GST_TIME_FORMAT "=pipeline_int_time\n"
894                                 ,
895                                 GST_TIME_ARGS (base_time), GST_TIME_ARGS (clock_time), dts_pts_offset,
896                                 GST_TIME_ARGS (encoder_dts), GST_TIME_ARGS (orig_dts_clock_time), GST_TIME_ARGS (calib_dts_clock_time), GST_TIME_ARGS (result_dts),
897                                 GST_TIME_ARGS (encoder_pts), GST_TIME_ARGS (orig_pts_clock_time), GST_TIME_ARGS (result_pts),
898                                 GST_TIME_ARGS (internal), GST_TIME_ARGS (external), GST_TIME_ARGS (diff),
899                                 GST_TIME_ARGS (rate_n), GST_TIME_ARGS (rate_d),
900                                 GST_TIME_ARGS (my_int_time), GST_TIME_ARGS (pipeline_int_time)
901                                 );
902 #endif
903                         }
904
905                         if (!skip_frame)
906                         {
907                                 readbuf = gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY, enc->cdb, VMMAPSIZE, desc->stCommon.uiOffset, desc->stCommon.uiLength, self, NULL);
908                                 if (result_dts != GST_CLOCK_TIME_NONE)
909                                 {
910                                         GST_BUFFER_DTS(readbuf) = result_dts;
911                                         GST_BUFFER_PTS(readbuf) = result_pts;
912                                 }
913                         }
914
915 #ifdef dump
916                         int wret = write(self->dumpfd, (unsigned char*)(enc->cdb + desc->stCommon.uiOffset), desc->stCommon.uiLength);
917                         GST_LOG_OBJECT (self, "read %i dumped %i total %" G_GSIZE_FORMAT " ", desc->stCommon.uiLength, wret, gst_buffer_get_size (*outbuf) );
918 #endif
919                         self->descriptors_count++;
920                         break;
921                 }
922
923                 if (self->descriptors_count == self->descriptors_available)
924                 {
925                         GST_LOG_OBJECT (self, "self->descriptors_count == self->descriptors_available -> release %i consumed descriptors", self->descriptors_count);
926                         /* release consumed descs */
927                         if (write(enc->fd, &self->descriptors_count, sizeof(self->descriptors_count)) != sizeof(self->descriptors_count)) {
928                                 GST_WARNING_OBJECT (self, "release consumed descs write error!");
929                                 goto stop_running;
930                         }
931                         self->descriptors_available = 0;
932                 }
933
934                 if (readbuf)
935                 {
936                         g_mutex_lock (&self->mutex);
937                         if (!self->flushing)
938                         {
939                                 while (g_queue_get_length (&self->current_frames) >= self->buffer_size)
940                                 {
941                                         GstBuffer * oldbuf = g_queue_pop_head (&self->current_frames);
942                                         GST_WARNING_OBJECT (self, "dropping %" GST_PTR_FORMAT " because of queue overflow! buffers count=%i", oldbuf, g_queue_get_length (&self->current_frames));
943                                         gst_buffer_unref(oldbuf);
944                                         GST_BUFFER_FLAG_SET ((GstBuffer *) g_queue_peek_head (&self->current_frames), GST_BUFFER_FLAG_DISCONT);
945                                 }
946                                 if (discont)
947                                 {
948                                         GST_BUFFER_FLAG_SET (readbuf, GST_BUFFER_FLAG_DISCONT);
949                                         discont = FALSE;
950                                 }
951                                 g_queue_push_tail (&self->current_frames, readbuf);
952                                 GST_INFO_OBJECT (self, "read %" GST_PTR_FORMAT " to queue...", readbuf );
953                                 g_cond_signal (&self->cond);
954                         }
955                         else
956                                 gst_buffer_unref(readbuf);
957 //                      g_cond_signal (&self->cond);
958                         g_mutex_unlock (&self->mutex);
959                 }
960         }
961
962         g_assert_not_reached ();
963         return;
964
965         stop_running:
966         {
967                 g_mutex_unlock (&self->mutex);
968                 g_cond_signal (&self->cond);
969                 GST_DEBUG ("stop running, exit thread");
970                 message = gst_message_new_stream_status (GST_OBJECT_CAST (self), GST_STREAM_STATUS_TYPE_ENTER, GST_ELEMENT_CAST (GST_OBJECT_PARENT(self)));
971                 g_value_init (&val, GST_TYPE_G_THREAD);
972                 g_value_set_boxed (&val, self->readthread);
973                 gst_message_set_stream_status_object (message, &val);
974                 g_value_unset (&val);
975                 GST_DEBUG_OBJECT (self, "posting LEAVE stream status");
976                 gst_element_post_message (GST_ELEMENT_CAST (self), message);
977                 return;
978         }
979 }
980
981 static GstFlowReturn
982 gst_dreamvideosource_create (GstPushSrc * psrc, GstBuffer ** outbuf)
983 {
984         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (psrc);
985
986         GST_LOG_OBJECT (self, "new buffer requested. queue has %i buffers", g_queue_get_length (&self->current_frames));
987
988         g_mutex_lock (&self->mutex);
989         while (g_queue_is_empty (&self->current_frames) && !self->flushing)
990         {
991                 GST_INFO_OBJECT (self, "waiting for buffer from encoder");
992                 g_cond_wait (&self->cond, &self->mutex);
993         }
994
995         *outbuf = g_queue_pop_head (&self->current_frames);
996         g_mutex_unlock (&self->mutex);
997
998         if (*outbuf)
999         {
1000                 GST_INFO_OBJECT (self, "pushing %" GST_PTR_FORMAT ". queue has %i buffers", *outbuf, g_queue_get_length (&self->current_frames));
1001                 return GST_FLOW_OK;
1002         }
1003         GST_INFO_OBJECT (self, "FLUSHING");
1004         return GST_FLOW_FLUSHING;
1005 }
1006
1007
1008 static GstStateChangeReturn gst_dreamvideosource_change_state (GstElement * element, GstStateChange transition)
1009 {
1010         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (element);
1011         GstStateChangeReturn sret = GST_STATE_CHANGE_SUCCESS;
1012         int ret;
1013
1014         switch (transition) {
1015                 case GST_STATE_CHANGE_NULL_TO_READY:
1016                 {
1017                         if (!gst_dreamvideosource_encoder_init (self))
1018                                 return GST_STATE_CHANGE_FAILURE;
1019                         GST_DEBUG_OBJECT (self, "GST_STATE_CHANGE_NULL_TO_READY");
1020                         break;
1021                 }
1022                 case GST_STATE_CHANGE_READY_TO_PAUSED:
1023                         GST_LOG_OBJECT (self, "GST_STATE_CHANGE_READY_TO_PAUSED");
1024                         self->dreamaudiosrc = gst_bin_get_by_name_recurse_up(GST_BIN(GST_ELEMENT_PARENT(self)), "dreamaudiosource0");
1025                 #ifdef PROVIDE_CLOCK
1026                         if (self->dreamaudiosrc)
1027                         {
1028                                 self->encoder_clock = gst_element_provide_clock (self->dreamaudiosrc);
1029                                 GST_DEBUG_OBJECT (self, "using dreamaudiosrc's encoder_clock = %" GST_PTR_FORMAT, self->encoder_clock);
1030                         } else {
1031                                 self->encoder_clock = gst_dreamsource_clock_new ("GstDreamVideoSinkClock", self->encoder->fd);
1032                                 GST_OBJECT_FLAG_SET (self, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
1033                                 GstMessage* msg;
1034                                 msg = gst_message_new_clock_provide (GST_OBJECT_CAST (element), self->encoder_clock, TRUE);
1035                                 GST_DEBUG_OBJECT (self, "new clock: %" GST_PTR_FORMAT " %" GST_PTR_FORMAT " typename=%s", self->encoder_clock, msg, GST_MESSAGE_TYPE_NAME(msg));
1036                                 gst_element_post_message (element, msg);
1037                         }
1038                 #endif
1039                         self->dts_offset = GST_CLOCK_TIME_NONE;
1040                         self->flushing = TRUE;
1041                         self->readthread = g_thread_try_new ("dreamvideosrc-read", (GThreadFunc) gst_dreamvideosource_read_thread_func, self, NULL);
1042                         GST_DEBUG_OBJECT (self, "started readthread @%p", self->readthread );
1043                         break;
1044                 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1045                         g_mutex_lock (&self->mutex);
1046                         GST_LOG_OBJECT (self, "GST_STATE_CHANGE_PAUSED_TO_PLAYING");
1047                         self->dts_valid = FALSE;
1048                         GstClock *pipeline_clock = gst_element_get_clock (GST_ELEMENT (self));
1049                         if (pipeline_clock)
1050                         {
1051                                 if (self->dreamaudiosrc)
1052                                         GST_DEBUG_OBJECT (self, "dreamaudiosource owns the clock and is responsible for slaving it");
1053                                 else if (pipeline_clock != self->encoder_clock)
1054                                 {
1055                                         gst_clock_set_master (self->encoder_clock, pipeline_clock);
1056                                         GST_DEBUG_OBJECT (self, "slaved %" GST_PTR_FORMAT "to pipeline_clock %" GST_PTR_FORMAT "", self->encoder_clock, pipeline_clock);
1057                                 }
1058                                 else
1059                                         GST_DEBUG_OBJECT (self, "encoder_clock is master clock");
1060                         }
1061                                 else
1062                                         GST_WARNING_OBJECT (self, "no pipeline clock!");
1063                         ret = ioctl(self->encoder->fd, VENC_START);
1064                         if ( ret != 0 )
1065                                 goto fail;
1066                         self->descriptors_available = 0;
1067                         CLEAR_COMMAND (self);
1068                         g_mutex_unlock (&self->mutex);
1069                         break;
1070                 default:
1071                         break;
1072         }
1073
1074         if (GST_ELEMENT_CLASS (parent_class)->change_state)
1075                 sret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1076
1077         switch (transition) {
1078                 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1079                         g_mutex_lock (&self->mutex);
1080                         SEND_COMMAND (self, CONTROL_RUN);
1081                         GST_INFO_OBJECT (self, "started encoder!");
1082                         g_mutex_unlock (&self->mutex);
1083                         break;
1084                 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1085                         g_mutex_lock (&self->mutex);
1086                         self->flushing = TRUE;
1087                         GST_DEBUG_OBJECT (self, "GST_STATE_CHANGE_PLAYING_TO_PAUSED self->descriptors_count=%i self->descriptors_available=%i", self->descriptors_count, self->descriptors_available);
1088                         SEND_COMMAND (self, CONTROL_PAUSE);
1089                         if (self->descriptors_count < self->descriptors_available)
1090                                 self->descriptors_count = self->descriptors_available;
1091                         if (self->descriptors_count)
1092                                 write(self->encoder->fd, &self->descriptors_count, sizeof(self->descriptors_count));
1093                         ret = ioctl(self->encoder->fd, VENC_STOP);
1094                         if ( ret != 0 )
1095                                 goto fail;
1096 #ifdef PROVIDE_CLOCK
1097                         gst_clock_set_master (self->encoder_clock, NULL);
1098 #endif
1099                         GST_INFO_OBJECT (self, "stopped encoder!");
1100                         g_mutex_unlock (&self->mutex);
1101                         break;
1102                 case GST_STATE_CHANGE_PAUSED_TO_READY:
1103                         GST_DEBUG_OBJECT (self,"GST_STATE_CHANGE_PAUSED_TO_READY");
1104 #ifdef PROVIDE_CLOCK
1105                         gst_element_post_message (element, gst_message_new_clock_lost (GST_OBJECT_CAST (element), self->encoder_clock));
1106                         if (!self->dreamaudiosrc)
1107                                 gst_clock_set_calibration (self->encoder_clock, 0, 0, 1, 1);
1108 #endif
1109                         GST_DEBUG_OBJECT (self, "stopping readthread @%p...", self->readthread);
1110                         SEND_COMMAND (self, CONTROL_STOP);
1111                         g_thread_join (self->readthread);
1112                         if (self->dreamaudiosrc)
1113                                 gst_object_unref(self->dreamaudiosrc);
1114                         self->dreamaudiosrc = NULL;
1115                         break;
1116                 case GST_STATE_CHANGE_READY_TO_NULL:
1117                         gst_dreamvideosource_encoder_release (self);
1118                         GST_DEBUG_OBJECT (self,"GST_STATE_CHANGE_READY_TO_NULL");
1119                         break;
1120                 default:
1121                         break;
1122         }
1123
1124         return sret;
1125 fail:
1126         GST_ERROR_OBJECT(self,"can't perform encoder ioctl! error: %s (%i)", strerror(errno), errno);
1127         g_mutex_unlock (&self->mutex);
1128         return GST_STATE_CHANGE_FAILURE;
1129 }
1130
1131 static void
1132 gst_dreamvideosource_dispose (GObject * gobject)
1133 {
1134         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (gobject);
1135 #ifdef PROVIDE_CLOCK
1136         if (self->encoder_clock) {
1137                 gst_object_unref (self->encoder_clock);
1138                 self->encoder_clock = NULL;
1139         }
1140 #endif
1141 #ifdef dump
1142         close(self->dumpfd);
1143 #endif
1144         if (self->current_caps)
1145                 gst_caps_unref(self->current_caps);
1146         if (self->new_caps)
1147                 gst_caps_unref(self->new_caps);
1148         g_mutex_clear (&self->mutex);
1149         g_cond_clear (&self->cond);
1150         GST_DEBUG_OBJECT (self, "disposed");
1151         G_OBJECT_CLASS (parent_class)->dispose (gobject);
1152 }
1153
1154 #ifdef PROVIDE_CLOCK
1155 static GstClock *gst_dreamvideosource_provide_clock (GstElement * element)
1156 {
1157         GstDreamVideoSource *self = GST_DREAMVIDEOSOURCE (element);
1158
1159         if (!self->encoder || self->encoder->fd < 0)
1160         {
1161                 GST_DEBUG_OBJECT (self, "encoder device not started, can't provide clock!");
1162                 return NULL;
1163         }
1164
1165         if (!self->encoder_clock)
1166         {
1167                 GST_DEBUG_OBJECT (self, "this element is not the clock provider!");
1168                 return NULL;
1169         }
1170
1171         return GST_CLOCK_CAST (gst_object_ref (self->encoder_clock));
1172 }
1173 #endif