use calibrated timestamps (as suggested by slomo)
[gst-plugin-dreamsource.git] / src / gstdreamaudiosource.c
1 /*
2  * GStreamer dreamaudiosource
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 "gstdreamaudiosource.h"
25
26 GST_DEBUG_CATEGORY_STATIC (dreamaudiosource_debug);
27 #define GST_CAT_DEFAULT dreamaudiosource_debug
28
29 GType gst_dreamaudiosource_input_mode_get_type (void)
30 {
31         static volatile gsize input_mode_type = 0;
32         static const GEnumValue input_mode[] = {
33                 {GST_DREAMAUDIOSOURCE_INPUT_MODE_LIVE, "GST_DREAMAUDIOSOURCE_INPUT_MODE_LIVE", "live"},
34                 {GST_DREAMAUDIOSOURCE_INPUT_MODE_HDMI_IN, "GST_DREAMAUDIOSOURCE_INPUT_MODE_HDMI_IN", "hdmi_in"},
35                 {GST_DREAMAUDIOSOURCE_INPUT_MODE_BACKGROUND, "GST_DREAMAUDIOSOURCE_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 ("GstDreamAudioSourceInputMode", 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 enum
52 {
53         ARG_0,
54         ARG_BITRATE,
55         ARG_INPUT_MODE
56 };
57
58 static guint gst_dreamaudiosource_signals[LAST_SIGNAL] = { 0 };
59
60 #define DEFAULT_BITRATE     128
61 #define DEFAULT_INPUT_MODE  GST_DREAMAUDIOSOURCE_INPUT_MODE_LIVE
62 #define DEFAULT_BUFFER_SIZE 16
63
64 static GstStaticPadTemplate srctemplate =
65     GST_STATIC_PAD_TEMPLATE ("src",
66         GST_PAD_SRC,
67         GST_PAD_ALWAYS,
68         GST_STATIC_CAPS ("audio/mpeg, "
69         "mpegversion = 4,"
70         "stream-format = (string) adts")
71     );
72
73 #define gst_dreamaudiosource_parent_class parent_class
74 G_DEFINE_TYPE (GstDreamAudioSource, gst_dreamaudiosource, GST_TYPE_PUSH_SRC);
75
76 static GstCaps *gst_dreamaudiosource_getcaps (GstBaseSrc * bsrc, GstCaps * filter);
77 static gboolean gst_dreamaudiosource_unlock (GstBaseSrc * bsrc);
78 static gboolean gst_dreamaudiosource_unlock_stop (GstBaseSrc * bsrc);
79 static void gst_dreamaudiosource_dispose (GObject * gobject);
80 static GstFlowReturn gst_dreamaudiosource_create (GstPushSrc * psrc, GstBuffer ** outbuf);
81
82 static void gst_dreamaudiosource_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec);
83 static void gst_dreamaudiosource_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec);
84
85 static GstStateChangeReturn gst_dreamaudiosource_change_state (GstElement * element, GstStateChange transition);
86 static gint64 gst_dreamaudiosource_get_dts_offset (GstDreamAudioSource *self);
87
88 static gboolean gst_dreamaudiosource_encoder_init (GstDreamAudioSource * self);
89 static void gst_dreamaudiosource_encoder_release (GstDreamAudioSource * self);
90
91 static void gst_dreamaudiosource_read_thread_func (GstDreamAudioSource * self);
92
93 #ifdef PROVIDE_CLOCK
94 static GstClock *gst_dreamaudiosource_provide_clock (GstElement * elem);
95 // static GstClockTime gst_dreamaudiosource_get_encoder_time_ (GstClock * clock, GstBaseSrc * bsrc);
96 #endif
97
98 static void
99 gst_dreamaudiosource_class_init (GstDreamAudioSourceClass * klass)
100 {
101         GObjectClass *gobject_class;
102         GstElementClass *gstelement_class;
103         GstBaseSrcClass *gstbasesrc_class;
104         GstPushSrcClass *gstpush_src_class;
105
106         gobject_class = (GObjectClass *) klass;
107         gstelement_class = (GstElementClass *) klass;
108         gstbasesrc_class = (GstBaseSrcClass *) klass;
109         gstpush_src_class = (GstPushSrcClass *) klass;
110
111         gobject_class->set_property = gst_dreamaudiosource_set_property;
112         gobject_class->get_property = gst_dreamaudiosource_get_property;
113         gobject_class->dispose = gst_dreamaudiosource_dispose;
114
115         gst_element_class_add_pad_template (gstelement_class,
116                                             gst_static_pad_template_get (&srctemplate));
117
118         gst_element_class_set_static_metadata (gstelement_class,
119             "Dream Audio source", "Source/Audio",
120             "Provide an audio elementary stream from Dreambox encoder device",
121             "Andreas Frisch <fraxinas@opendreambox.org>");
122
123         gstelement_class->change_state = gst_dreamaudiosource_change_state;
124
125         gstbasesrc_class->get_caps = gst_dreamaudiosource_getcaps;
126         gstbasesrc_class->unlock = gst_dreamaudiosource_unlock;
127         gstbasesrc_class->unlock_stop = gst_dreamaudiosource_unlock_stop;
128
129         gstpush_src_class->create = gst_dreamaudiosource_create;
130
131 #ifdef PROVIDE_CLOCK
132         gstelement_class->provide_clock = GST_DEBUG_FUNCPTR (gst_dreamaudiosource_provide_clock);
133 //      g_type_class_ref (GST_TYPE_SYSTEM_CLOCK);
134 #endif
135
136         g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_BITRATE,
137           g_param_spec_int ("bitrate", "Bitrate (kb/s)",
138             "Bitrate in kbit/sec", 16, 320, DEFAULT_BITRATE,
139             G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
140
141         g_object_class_install_property (gobject_class, ARG_INPUT_MODE,
142           g_param_spec_enum ("input-mode", "Input Mode",
143             "Select the input source of the audio stream",
144             GST_TYPE_DREAMAUDIOSOURCE_INPUT_MODE, DEFAULT_INPUT_MODE,
145             G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
146
147         gst_dreamaudiosource_signals[SIGNAL_GET_DTS_OFFSET] =
148                 g_signal_new ("get-dts-offset",
149                 G_TYPE_FROM_CLASS (klass),
150                 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
151                 G_STRUCT_OFFSET (GstDreamAudioSourceClass, get_dts_offset),
152                 NULL, NULL, gst_dreamsource_marshal_INT64__VOID, G_TYPE_INT64, 0);
153
154         klass->get_dts_offset = gst_dreamaudiosource_get_dts_offset;
155 }
156
157 static gint64
158 gst_dreamaudiosource_get_dts_offset (GstDreamAudioSource *self)
159 {
160         GST_DEBUG_OBJECT (self, "gst_dreamaudiosource_get_dts_offset %" GST_TIME_FORMAT"", GST_TIME_ARGS (self->dts_offset) );
161         return self->dts_offset;
162 }
163
164 static void gst_dreamaudiosource_set_bitrate (GstDreamAudioSource * self, uint32_t bitrate)
165 {
166         g_mutex_lock (&self->mutex);
167         uint32_t abr = bitrate*1000;
168         if (!self->encoder || !self->encoder->fd)
169         {
170                 self->audio_info.bitrate = bitrate;
171                 g_mutex_unlock (&self->mutex);
172                 return;
173         }
174
175         int ret = ioctl(self->encoder->fd, AENC_SET_BITRATE, &abr);
176         if (ret != 0)
177         {
178                 GST_WARNING_OBJECT (self, "can't set audio bitrate to %i bytes/s!", abr);
179                 g_mutex_unlock (&self->mutex);
180                 return;
181         }
182         GST_INFO_OBJECT (self, "set audio bitrate to %i kBytes/s", bitrate);
183         self->audio_info.bitrate = bitrate;
184         g_mutex_unlock (&self->mutex);
185 }
186
187 void gst_dreamaudiosource_set_input_mode (GstDreamAudioSource *self, GstDreamAudioSourceInputMode mode)
188 {
189         g_return_if_fail (GST_IS_DREAMAUDIOSOURCE (self));
190         GEnumValue *val = g_enum_get_value (G_ENUM_CLASS (g_type_class_ref (GST_TYPE_DREAMAUDIOSOURCE_INPUT_MODE)), mode);
191         if (!val)
192         {
193                 GST_ERROR_OBJECT (self, "no such input_mode %i!", mode);
194                 goto out;
195         }
196         const gchar *value_nick = val->value_nick;
197
198         g_mutex_lock (&self->mutex);
199         if (!self->encoder || !self->encoder->fd)
200         {
201                 self->input_mode = mode;
202                 goto out;
203         }
204         int int_mode = mode;
205         int ret = ioctl(self->encoder->fd, AENC_SET_SOURCE, &int_mode);
206         if (ret != 0)
207         {
208                 GST_WARNING_OBJECT (self, "can't set input mode to %s (%i) error: %s", value_nick, mode, strerror(errno));
209                 goto out;
210         }
211         GST_INFO_OBJECT (self, "successfully set input mode to %s (%i)", value_nick, mode);
212         self->input_mode = mode;
213 out:
214         g_mutex_unlock (&self->mutex);
215         return;
216 }
217
218 GstDreamAudioSourceInputMode gst_dreamaudiosource_get_input_mode (GstDreamAudioSource *self)
219 {
220         GstDreamAudioSourceInputMode result;
221         g_return_val_if_fail (GST_IS_DREAMAUDIOSOURCE (self), -1);
222         GST_OBJECT_LOCK (self);
223         result =self->input_mode;
224         GST_OBJECT_UNLOCK (self);
225         return result;
226 }
227
228 gboolean
229 gst_dreamaudiosource_plugin_init (GstPlugin *plugin)
230 {
231         GST_DEBUG_CATEGORY_INIT (dreamaudiosource_debug, "dreamaudiosource", 0, "dreamaudiosource");
232         return gst_element_register (plugin, "dreamaudiosource", GST_RANK_PRIMARY, GST_TYPE_DREAMAUDIOSOURCE);
233 }
234
235 static void
236 gst_dreamaudiosource_init (GstDreamAudioSource * self)
237 {
238         self->encoder = NULL;
239         self->descriptors_available = 0;
240         self->input_mode = DEFAULT_INPUT_MODE;
241
242         self->buffer_size = DEFAULT_BUFFER_SIZE;
243         g_queue_init (&self->current_frames);
244         self->readthread = NULL;
245
246         g_mutex_init (&self->mutex);
247         READ_SOCKET (self) = -1;
248         WRITE_SOCKET (self) = -1;
249
250         gst_base_src_set_format (GST_BASE_SRC (self), GST_FORMAT_TIME);
251         gst_base_src_set_live (GST_BASE_SRC (self), TRUE);
252
253         self->encoder = NULL;
254         self->encoder_clock = NULL;
255
256 #ifdef dump
257         self->dumpfd = open("/media/hdd/movie/dreamaudiosource.dump", O_WRONLY | O_CREAT | O_TRUNC);
258         GST_DEBUG_OBJECT (self, "dumpfd = %i (%s)", self->dumpfd, (self->dumpfd > 0) ? "OK" : strerror(errno));
259 #endif
260 }
261
262 static gboolean gst_dreamaudiosource_encoder_init (GstDreamAudioSource * self)
263 {
264         GST_LOG_OBJECT (self, "initializating encoder...");
265         self->encoder = malloc(sizeof(EncoderInfo));
266
267         if (!self->encoder) {
268                 GST_ERROR_OBJECT (self,"out of space");
269                 return FALSE;
270         }
271
272         char fn_buf[32];
273         sprintf(fn_buf, "/dev/aenc%d", 0);
274         self->encoder->fd = open(fn_buf, O_RDWR | O_SYNC);
275         if (self->encoder->fd <= 0) {
276                 GST_ERROR_OBJECT (self,"cannot open device %s (%s)", fn_buf, strerror(errno));
277                 free(self->encoder);
278                 self->encoder = NULL;
279                 return FALSE;
280         }
281
282         self->encoder->buffer = malloc(ABUFSIZE);
283         if (!self->encoder->buffer) {
284                 GST_ERROR_OBJECT(self,"cannot alloc buffer");
285                 return FALSE;
286         }
287
288         self->encoder->cdb = (unsigned char *)mmap (0, AMMAPSIZE, PROT_READ, MAP_PRIVATE, self->encoder->fd, 0);
289
290         if (!self->encoder->cdb || self->encoder->cdb == MAP_FAILED) {
291                 GST_ERROR_OBJECT(self,"cannot alloc buffer: %s (%d)", strerror(errno));
292                 self->encoder->cdb = NULL;
293                 return FALSE;
294         }
295
296         int control_sock[2];
297         if (socketpair (PF_UNIX, SOCK_STREAM, 0, control_sock) < 0)
298         {
299                 GST_ELEMENT_ERROR (self, RESOURCE, OPEN_READ_WRITE, (NULL), GST_ERROR_SYSTEM);
300                 return GST_STATE_CHANGE_FAILURE;
301         }
302         READ_SOCKET (self) = control_sock[0];
303         WRITE_SOCKET (self) = control_sock[1];
304         fcntl (READ_SOCKET (self), F_SETFL, O_NONBLOCK);
305         fcntl (WRITE_SOCKET (self), F_SETFL, O_NONBLOCK);
306
307         self->memtrack_list = NULL;
308         self->encoder->used_range_min = UINT32_MAX;
309         self->encoder->used_range_max = 0;
310
311         gst_dreamaudiosource_set_bitrate (self, self->audio_info.bitrate);
312         gst_dreamaudiosource_set_input_mode (self, self->input_mode);
313
314 #ifdef PROVIDE_CLOCK
315         self->encoder_clock = gst_dreamsource_clock_new ("GstDreamAudioSourceClock", self->encoder->fd);
316         GST_DEBUG_OBJECT (self, "self->encoder_clock = %" GST_PTR_FORMAT, self->encoder_clock);
317         GST_OBJECT_FLAG_SET (self, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
318 #endif
319
320         GST_LOG_OBJECT (self, "encoder %s successfully initialized", fn_buf);
321         return TRUE;
322 }
323
324 static void gst_dreamaudiosource_encoder_release (GstDreamAudioSource * self)
325 {
326         GST_LOG_OBJECT (self, "releasing encoder...");
327         if (self->encoder) {
328                 if (self->encoder->buffer)
329                         free(self->encoder->buffer);
330                 if (self->encoder->cdb)
331                         munmap(self->encoder->cdb, AMMAPSIZE);
332                 if (self->encoder->fd)
333                         close(self->encoder->fd);
334                 free(self->encoder);
335         }
336         g_list_free(self->memtrack_list);
337         self->encoder = NULL;
338         close (READ_SOCKET (self));
339         close (WRITE_SOCKET (self));
340         READ_SOCKET (self) = -1;
341         WRITE_SOCKET (self) = -1;
342         if (self->encoder_clock) {
343                 gst_object_unref (self->encoder_clock);
344                 self->encoder_clock = NULL;
345         }
346 }
347
348 static void
349 gst_dreamaudiosource_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec)
350 {
351         GstDreamAudioSource *self = GST_DREAMAUDIOSOURCE (object);
352
353         switch (prop_id) {
354                 case ARG_BITRATE:
355                         gst_dreamaudiosource_set_bitrate(self, g_value_get_int (value));
356                         break;
357                 case ARG_INPUT_MODE:
358                              gst_dreamaudiosource_set_input_mode (self, g_value_get_enum (value));
359                         break;
360                 default:
361                         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
362                         break;
363         }
364 }
365
366 static void
367 gst_dreamaudiosource_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec)
368 {
369         GstDreamAudioSource *self = GST_DREAMAUDIOSOURCE (object);
370
371         switch (prop_id) {
372                 case ARG_BITRATE:
373                         g_value_set_int (value, self->audio_info.bitrate/1000);
374                         break;
375                 case ARG_INPUT_MODE:
376                         g_value_set_enum (value, gst_dreamaudiosource_get_input_mode (self));
377                         break;
378                 default:
379                         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
380                         break;
381         }
382 }
383
384 static GstCaps *
385 gst_dreamaudiosource_getcaps (GstBaseSrc * bsrc, GstCaps * filter)
386 {
387         GstDreamAudioSource *self = GST_DREAMAUDIOSOURCE (bsrc);
388         GstPadTemplate *pad_template;
389         GstCaps *caps;
390
391         pad_template = gst_element_class_get_pad_template (GST_ELEMENT_GET_CLASS(self), "src");
392         g_return_val_if_fail (pad_template != NULL, NULL);
393
394         if (self->encoder == NULL) {
395                 GST_DEBUG_OBJECT (self, "encoder not opened -> use template caps");
396                 caps = gst_pad_template_get_caps (pad_template);
397         }
398         else
399         {
400                 caps = gst_caps_make_writable(gst_pad_template_get_caps (pad_template));
401         }
402
403         GST_DEBUG_OBJECT (self, "return caps %" GST_PTR_FORMAT, caps);
404         return caps;
405 }
406
407 static gboolean gst_dreamaudiosource_unlock (GstBaseSrc * bsrc)
408 {
409         GstDreamAudioSource *self = GST_DREAMAUDIOSOURCE (bsrc);
410         GST_DEBUG_OBJECT (self, "stop creating buffers");
411         g_mutex_lock (&self->mutex);
412         self->flushing = TRUE;
413         GST_DEBUG_OBJECT (self, "set flushing TRUE");
414         g_cond_signal (&self->cond);
415         g_mutex_unlock (&self->mutex);
416         return TRUE;
417 }
418
419 static gboolean gst_dreamaudiosource_unlock_stop (GstBaseSrc * bsrc)
420 {
421         GstDreamAudioSource *self = GST_DREAMAUDIOSOURCE (bsrc);
422         GST_DEBUG_OBJECT (self, "start creating buffers...");
423         g_mutex_lock (&self->mutex);
424         self->flushing = FALSE;
425         g_queue_foreach (&self->current_frames, (GFunc) gst_buffer_unref, NULL);
426         g_queue_clear (&self->current_frames);
427         g_mutex_unlock (&self->mutex);
428         return TRUE;
429 }
430
431 static void gst_dreamaudiosource_free_buffer (struct _buffer_memorytracker * memtrack)
432 {
433         GstDreamAudioSource * self = memtrack->self;
434         GST_OBJECT_LOCK(self);
435         GST_TRACE_OBJECT (self, "freeing %" GST_PTR_FORMAT " uiOffset=%i uiLength=%i used_range_min=%i", memtrack->buffer, memtrack->uiOffset, memtrack->uiLength, self->encoder->used_range_min);
436         GList *list = g_list_first (self->memtrack_list);
437         guint abs_minimum = UINT32_MAX;
438         guint abs_maximum = 0;
439         struct _buffer_memorytracker * mt;
440         int count = 0;
441         self->memtrack_list = g_list_remove(list, memtrack);
442         free(memtrack);
443         list = g_list_first (self->memtrack_list);
444         while (list) {
445                 mt = list->data;
446                 if (abs_minimum > 0 && mt->uiOffset < abs_minimum)
447                         abs_minimum = mt->uiOffset;
448                 if (mt->uiOffset+mt->uiLength > abs_maximum)
449                         abs_maximum = mt->uiOffset+mt->uiLength;
450                 count++;
451                 list = g_list_next (list);
452         }
453         GST_TRACE_OBJECT (self, "new abs_minimum=%i, abs_maximum=%i", abs_minimum, abs_maximum);
454         self->encoder->used_range_min = abs_minimum;
455         self->encoder->used_range_max = abs_maximum;
456         GST_OBJECT_UNLOCK(self);
457 }
458
459 static void gst_dreamaudiosource_read_thread_func (GstDreamAudioSource * self)
460 {
461         EncoderInfo *enc = self->encoder;
462         GstBuffer *readbuf;
463
464         if (!enc) {
465                 GST_WARNING_OBJECT (self, "encoder device not opened!");
466                 return;
467         }
468
469         GST_DEBUG_OBJECT (self, "enter read thread");
470
471         GstMessage *message;
472         GValue val = { 0 };
473
474         message = gst_message_new_stream_status (GST_OBJECT_CAST (self), GST_STREAM_STATUS_TYPE_ENTER, GST_ELEMENT_CAST (GST_OBJECT_PARENT(self)));
475         g_value_init (&val, GST_TYPE_G_THREAD);
476         g_value_set_boxed (&val, self->readthread);
477         gst_message_set_stream_status_object (message, &val);
478         g_value_unset (&val);
479         GST_DEBUG_OBJECT (self, "posting ENTER stream status");
480         gst_element_post_message (GST_ELEMENT_CAST (self), message);
481         GstClockTime clock_time;
482
483         while (TRUE) {
484                 readbuf = NULL;
485                 {
486                         struct pollfd rfd[2];
487                         int timeout, nfds;
488
489                         rfd[0].fd = READ_SOCKET (self);
490                         rfd[0].events = POLLIN | POLLERR | POLLHUP | POLLPRI;
491
492                         GST_DEBUG_OBJECT (self, "polling... self->descriptors_available=%i! fd=%i", self->descriptors_available, enc->fd);
493                         if (self->descriptors_available == 0)
494                         {
495                                 rfd[1].fd = enc->fd;
496                                 rfd[1].events = POLLIN;
497                                 self->descriptors_count = 0;
498                                 timeout = 200;
499                                 nfds = 2;
500                         }
501                         else
502                         {
503                                 rfd[1].revents = 0;
504                                 nfds = 1;
505                                 timeout = 0;
506                         }
507
508                         int ret = poll(rfd, nfds, timeout);
509
510                         if (G_UNLIKELY (ret == -1))
511                         {
512                                 GST_ERROR_OBJECT (self, "SELECT ERROR!");
513                                 goto stop_running;
514                         }
515                         else if ( ret == 0 && self->descriptors_available == 0 )
516                         {
517                                 g_mutex_lock (&self->mutex);
518                                 gst_clock_get_internal_time(self->encoder_clock);
519                                 if (self->flushing)
520                                 {
521                                         GST_DEBUG_OBJECT (self, "FLUSHING!");
522                                         g_cond_signal (&self->cond);
523                                         g_mutex_unlock (&self->mutex);
524                                         continue;
525                                 }
526                                 g_mutex_unlock (&self->mutex);
527                                 GST_DEBUG_OBJECT (self, "SELECT TIMEOUT");
528                                 //!!! TODO generate valid dummy payload
529                                 readbuf = gst_buffer_new();
530                         }
531                         else if ( rfd[0].revents )
532                         {
533                                 char command;
534                                 READ_COMMAND (self, command, ret);
535                                 if (command == CONTROL_STOP)
536                                 {
537                                         GST_DEBUG_OBJECT (self, "CONTROL_STOP!");
538                                         goto stop_running;
539                                 }
540                         }
541                         else if ( G_LIKELY(rfd[1].revents & POLLIN) )
542                         {
543                                 clock_time = gst_clock_get_internal_time (self->encoder_clock);
544                                 int rlen = read(enc->fd, enc->buffer, ABUFSIZE);
545                                 if (rlen <= 0 || rlen % ABDSIZE ) {
546                                         if ( errno == 512 )
547                                                 goto stop_running;
548                                         GST_WARNING_OBJECT (self, "read error %s (%i)", strerror(errno), errno);
549                                         goto stop_running;
550                                 }
551                                 self->descriptors_available = rlen / ABDSIZE;
552                                 GST_LOG_OBJECT (self, "encoder buffer was empty, %d descriptors available", self->descriptors_available);
553                         }
554                 }
555
556                 while (self->descriptors_count < self->descriptors_available)
557                 {
558                         GstClockTime base_time = gst_element_get_base_time(GST_ELEMENT(self));
559                         GstClockTime encoder_pts = GST_CLOCK_TIME_NONE;
560                         gint64 dts_pts_offset;
561
562                         off_t offset = self->descriptors_count * ABDSIZE;
563                         AudioBufferDescriptor *desc = (AudioBufferDescriptor*)(&enc->buffer[offset]);
564
565                         uint32_t f = desc->stCommon.uiFlags;
566
567                         if (G_UNLIKELY (f & CDB_FLAG_METADATA))
568                         {
569                                 GST_LOG_OBJECT (self, "CDB_FLAG_METADATA... skip outdated packet");
570                                 self->descriptors_count = self->descriptors_available;
571                                 continue;
572                         }
573
574                         struct _buffer_memorytracker * memtrack = malloc(sizeof(struct _buffer_memorytracker));
575                         if (G_UNLIKELY (!memtrack))
576                         {
577                                 GST_ERROR_OBJECT (self, "can't allocate buffer_memorytracker");
578                                 goto stop_running;
579                         }
580
581                         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);
582
583                         if (self->encoder->used_range_min == UINT32_MAX)
584                                 self->encoder->used_range_min = desc->stCommon.uiOffset;
585
586                         if (self->encoder->used_range_max == 0)
587                                 self->encoder->used_range_max = desc->stCommon.uiOffset+desc->stCommon.uiLength;
588
589 //                      if (desc->stCommon.uiOffset < self->encoder->used_range_max && desc->stCommon.uiOffset+desc->stCommon.uiLength > self->encoder->used_range_min)
590 //                      {
591 //                              GST_WARNING_OBJECT (self, "encoder overwrites buffer memory that is still in use! uiOffset=%i uiLength=%i used_range_min=%i used_range_max=%i", desc->stCommon.uiOffset, desc->stCommon.uiLength, self->encoder->used_range_min, self->encoder->used_range_max);
592 //                              self->descriptors_count++;
593 //                              readbuf = gst_buffer_new();
594 //                              continue;
595 //                      }
596
597                         // uiDTS since kernel driver booted
598                         if (f & CDB_FLAG_PTS_VALID)
599                         {
600                                 encoder_pts = MPEGTIME_TO_GSTTIME(desc->stCommon.uiPTS);
601                                 GST_LOG_OBJECT (self, "f & CDB_FLAG_PTS_VALID && encoder's uiPTS=%" GST_TIME_FORMAT"", GST_TIME_ARGS(encoder_pts));
602
603                                 g_mutex_lock (&self->mutex);
604                                 if (G_UNLIKELY (self->dts_offset == GST_CLOCK_TIME_NONE))
605                                 {
606                                         if (self->dreamvideosrc)
607                                         {
608                                                 guint64 videosource_dts_offset;
609                                                 g_signal_emit_by_name(self->dreamvideosrc, "get-dts-offset", &videosource_dts_offset);
610                                                 if (videosource_dts_offset != GST_CLOCK_TIME_NONE)
611                                                 {
612                                                         GST_DEBUG_OBJECT (self, "use DREAMVIDEOSOURCE's dts_offset=%" GST_TIME_FORMAT "", GST_TIME_ARGS (videosource_dts_offset) );
613                                                         self->dts_offset = videosource_dts_offset;
614                                                 }
615                                         }
616                                         if (self->dts_offset == GST_CLOCK_TIME_NONE)
617                                         {
618                                                 self->dts_offset = encoder_pts;
619                                                 GST_DEBUG_OBJECT (self, "use mpeg stream pts as dts_offset=%" GST_TIME_FORMAT" (%lld)", GST_TIME_ARGS (self->dts_offset), desc->stCommon.uiPTS);
620                                         }
621                                 }
622                                 g_mutex_unlock (&self->mutex);
623                         }
624
625                         if (G_UNLIKELY (self->dts_offset == GST_CLOCK_TIME_NONE))
626                         {
627                                 GST_DEBUG_OBJECT (self, "dts_offset is still unknown, skipping frame...");
628                                 self->descriptors_count++;
629                                 break;
630                         }
631
632                         readbuf = gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY, enc->cdb, AMMAPSIZE, desc->stCommon.uiOffset, desc->stCommon.uiLength, memtrack, (GDestroyNotify) gst_dreamaudiosource_free_buffer);
633
634                         memtrack->self = self;
635                         memtrack->buffer = readbuf;
636                         memtrack->uiOffset = desc->stCommon.uiOffset;
637                         memtrack->uiLength = desc->stCommon.uiLength;
638                         self->memtrack_list = g_list_append(self->memtrack_list, memtrack);
639
640                         if (encoder_pts != GST_CLOCK_TIME_NONE)
641                         {
642                                 GstClockTime pts_clock_time = encoder_pts - self->dts_offset;
643                                 GstClockTime internal, external;
644                                 GstClockTime rate_n, rate_d;
645                                 GstClockTimeDiff diff;
646
647                                 gst_clock_get_calibration (self->encoder_clock, &internal, &external, &rate_n, &rate_d);
648                                 if (internal > pts_clock_time) {
649                                         diff = internal - pts_clock_time;
650                                         diff = gst_util_uint64_scale (diff, rate_n, rate_d);
651                                         pts_clock_time = external - diff;
652                                 } else {
653                                         diff = pts_clock_time - internal;
654                                         diff = gst_util_uint64_scale (diff, rate_n, rate_d);
655                                         pts_clock_time = external + diff;
656                                 }
657
658                                 GST_BUFFER_DTS(readbuf) = pts_clock_time - base_time;
659                                 GST_BUFFER_PTS(readbuf) = pts_clock_time - base_time;
660
661 GST_LOG_OBJECT (self, "post-calibration\n"
662 "%" GST_TIME_FORMAT "=base_time       %" GST_TIME_FORMAT "=clock_time\n"
663 "%" GST_TIME_FORMAT "=encoder_pts     %" GST_TIME_FORMAT "=pts_clock_time     %" GST_TIME_FORMAT "=GST_BUFFER_PTS\n"
664 ,
665         GST_TIME_ARGS (base_time), GST_TIME_ARGS (clock_time),
666         GST_TIME_ARGS (encoder_pts), GST_TIME_ARGS (pts_clock_time), GST_TIME_ARGS (GST_BUFFER_PTS(readbuf))
667 );
668                         }
669
670 #ifdef dump
671                         int wret = write(self->dumpfd, (unsigned char*)(enc->cdb + desc->stCommon.uiOffset), desc->stCommon.uiLength);
672                         GST_LOG_OBJECT (self, "read %i dumped %i total %" G_GSIZE_FORMAT " ", desc->stCommon.uiLength, wret, gst_buffer_get_size (*outbuf) );
673 #endif
674                         self->descriptors_count++;
675                         break;
676                 }
677
678                 if (self->descriptors_count == self->descriptors_available)
679                 {
680                         GST_LOG_OBJECT (self, "self->descriptors_count == self->descriptors_available -> release %i consumed descriptors", self->descriptors_count);
681                         /* release consumed descs */
682                         if (write(enc->fd, &self->descriptors_count, sizeof(self->descriptors_count)) != sizeof(self->descriptors_count)) {
683                                 GST_WARNING_OBJECT (self, "release consumed descs write error!");
684                                 goto stop_running;
685                         }
686                         self->descriptors_available = 0;
687                 }
688
689                 if (readbuf)
690                 {
691                         g_mutex_lock (&self->mutex);
692                         if (!self->flushing)
693                         {
694                                 while (g_queue_get_length (&self->current_frames) >= self->buffer_size)
695                                 {
696                                         GstBuffer * oldbuf = g_queue_pop_head (&self->current_frames);
697                                         GST_WARNING_OBJECT (self, "dropping %" GST_PTR_FORMAT " because of queue overflow! buffers count=%i", oldbuf, g_queue_get_length (&self->current_frames));
698                                         gst_buffer_unref(oldbuf);
699                                 }
700                                 g_queue_push_tail (&self->current_frames, readbuf);
701                         }
702                         else
703                                 gst_buffer_unref(readbuf);
704                         g_cond_signal (&self->cond);
705                         GST_INFO_OBJECT (self, "read %" GST_PTR_FORMAT " to queue", readbuf );
706                         g_mutex_unlock (&self->mutex);
707                 }
708         }
709
710         g_assert_not_reached ();
711         return;
712
713         stop_running:
714         {
715                 g_mutex_unlock (&self->mutex);
716                 g_cond_signal (&self->cond);
717                 GST_DEBUG ("stop running, exit thread");
718                 message = gst_message_new_stream_status (GST_OBJECT_CAST (self), GST_STREAM_STATUS_TYPE_ENTER, GST_ELEMENT_CAST (GST_OBJECT_PARENT(self)));
719                 g_value_init (&val, GST_TYPE_G_THREAD);
720                 g_value_set_boxed (&val, self->readthread);
721                 gst_message_set_stream_status_object (message, &val);
722                 g_value_unset (&val);
723                 GST_DEBUG_OBJECT (self, "posting LEAVE stream status");
724                 gst_element_post_message (GST_ELEMENT_CAST (self), message);
725                 return;
726         }
727 }
728
729 static GstFlowReturn
730 gst_dreamaudiosource_create (GstPushSrc * psrc, GstBuffer ** outbuf)
731 {
732         GstDreamAudioSource *self = GST_DREAMAUDIOSOURCE (psrc);
733
734         GST_LOG_OBJECT (self, "new buffer requested");
735
736         g_mutex_lock (&self->mutex);
737         while (g_queue_is_empty (&self->current_frames) && !self->flushing)
738         {
739                 g_cond_wait (&self->cond, &self->mutex);
740                 GST_INFO_OBJECT (self, "waiting for buffer from encoder");
741         }
742
743         *outbuf = g_queue_pop_head (&self->current_frames);
744         g_mutex_unlock (&self->mutex);
745
746         if (*outbuf)
747         {
748                 GST_INFO_OBJECT (self, "pushing %" GST_PTR_FORMAT "", *outbuf );
749                 return GST_FLOW_OK;
750         }
751         GST_INFO_OBJECT (self, "FLUSHING");
752         return GST_FLOW_FLUSHING;
753 }
754
755 static GstStateChangeReturn gst_dreamaudiosource_change_state (GstElement * element, GstStateChange transition)
756 {
757         GstDreamAudioSource *self = GST_DREAMAUDIOSOURCE (element);
758         GstStateChangeReturn sret = GST_STATE_CHANGE_SUCCESS;
759         int ret;
760
761         switch (transition) {
762                 case GST_STATE_CHANGE_NULL_TO_READY:
763                 {
764                         if (!gst_dreamaudiosource_encoder_init (self))
765                                 return GST_STATE_CHANGE_FAILURE;
766                         GST_DEBUG_OBJECT (self, "GST_STATE_CHANGE_NULL_TO_READY");
767                         break;
768                 }
769                 case GST_STATE_CHANGE_READY_TO_PAUSED:
770                         GST_LOG_OBJECT (self, "GST_STATE_CHANGE_READY_TO_PAUSED");
771                         self->dreamvideosrc = gst_bin_get_by_name_recurse_up(GST_BIN(GST_ELEMENT_PARENT(self)), "dreamvideosource0");
772
773                         self->dts_offset = GST_CLOCK_TIME_NONE;
774 #ifdef PROVIDE_CLOCK
775                         gst_element_post_message (element, gst_message_new_clock_provide (GST_OBJECT_CAST (element), self->encoder_clock, TRUE));
776 #endif
777                         self->flushing = TRUE;
778                         self->readthread = g_thread_try_new ("dreamaudiosrc-read", (GThreadFunc) gst_dreamaudiosource_read_thread_func, self, NULL);
779                         GST_DEBUG_OBJECT (self, "started readthread @%p", self->readthread );
780                         break;
781                 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
782                         g_mutex_lock (&self->mutex);
783                         GST_LOG_OBJECT (self, "GST_STATE_CHANGE_PAUSED_TO_PLAYING");
784                         GstClock *pipeline_clock = gst_element_get_clock (GST_ELEMENT (self));
785                         if (pipeline_clock)
786                         {
787                                 if (pipeline_clock != self->encoder_clock)
788                                 {
789                                         gst_clock_set_master (self->encoder_clock, pipeline_clock);
790                                         GST_DEBUG_OBJECT (self, "slaved to pipeline_clock %" GST_PTR_FORMAT "", pipeline_clock);
791                                 }
792                                 else
793                                         GST_DEBUG_OBJECT (self, "encoder_clock is master clock");
794                         }
795                                 else
796                                         GST_WARNING_OBJECT (self, "no pipeline clock!");
797                         ret = ioctl(self->encoder->fd, AENC_START);
798                         if ( ret != 0 )
799                                 goto fail;
800                         self->descriptors_available = 0;
801                         CLEAR_COMMAND (self);
802                         GST_INFO_OBJECT (self, "started encoder!");
803                         g_mutex_unlock (&self->mutex);
804                         break;
805                 default:
806                         break;
807         }
808
809         if (GST_ELEMENT_CLASS (parent_class)->change_state)
810                 sret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
811
812         switch (transition) {
813                 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
814                         g_mutex_lock (&self->mutex);
815                         GST_DEBUG_OBJECT (self, "GST_STATE_CHANGE_PLAYING_TO_PAUSED self->descriptors_count=%i self->descriptors_available=%i", self->descriptors_count, self->descriptors_available);
816                         while (self->descriptors_count < self->descriptors_available)
817                         {
818                                 GST_LOG_OBJECT (self, "flushing self->descriptors_count=%i");
819                                 self->descriptors_count++;
820                         }
821                         if (self->descriptors_count)
822                                 write(self->encoder->fd, &self->descriptors_count, sizeof(self->descriptors_count));
823                         ret = ioctl(self->encoder->fd, AENC_STOP);
824                         if ( ret != 0 )
825                                 goto fail;
826 #ifdef PROVIDE_CLOCK
827                         gst_clock_set_master (self->encoder_clock, NULL);
828 #endif
829                         GST_INFO_OBJECT (self, "stopped encoder!");
830                         g_mutex_unlock (&self->mutex);
831                         break;
832                 case GST_STATE_CHANGE_PAUSED_TO_READY:
833                         GST_DEBUG_OBJECT (self,"GST_STATE_CHANGE_PAUSED_TO_READY");
834 #ifdef PROVIDE_CLOCK
835                         gst_element_post_message (element, gst_message_new_clock_lost (GST_OBJECT_CAST (element), self->encoder_clock));
836 #endif
837                         GST_DEBUG_OBJECT (self, "stopping readthread @%p...", self->readthread);
838                         SEND_COMMAND (self, CONTROL_STOP);
839                         g_thread_join (self->readthread);
840                         if (self->dreamvideosrc)
841                                 gst_object_unref(self->dreamvideosrc);
842                         self->dreamvideosrc = NULL;
843                         break;
844                 case GST_STATE_CHANGE_READY_TO_NULL:
845                         gst_dreamaudiosource_encoder_release (self);
846                         GST_DEBUG_OBJECT (self,"GST_STATE_CHANGE_READY_TO_NULL, close control sockets");
847                         break;
848                 default:
849                         break;
850         }
851
852         return sret;
853 fail:
854         GST_ERROR_OBJECT(self,"can't perform encoder ioctl!");
855         g_mutex_unlock (&self->mutex);
856         return GST_STATE_CHANGE_FAILURE;
857 }
858
859 static void
860 gst_dreamaudiosource_dispose (GObject * gobject)
861 {
862         GstDreamAudioSource *self = GST_DREAMAUDIOSOURCE (gobject);
863 #ifdef dump
864         close(self->dumpfd);
865 #endif
866         g_mutex_clear (&self->mutex);
867         g_cond_clear (&self->cond);
868         GST_DEBUG_OBJECT (self, "disposed");
869         G_OBJECT_CLASS (parent_class)->dispose (gobject);
870 }
871
872 #ifdef PROVIDE_CLOCK
873 static GstClock *gst_dreamaudiosource_provide_clock (GstElement * element)
874 {
875         GstDreamAudioSource *self = GST_DREAMAUDIOSOURCE (element);
876
877         if (!self->encoder || self->encoder->fd < 0)
878         {
879                 GST_DEBUG_OBJECT (self, "encoder device not started, can't provide clock!");
880                 return NULL;
881         }
882
883         return GST_CLOCK_CAST (gst_object_ref (self->encoder_clock));
884 }
885
886 #endif
887