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