improve state change logic, move cdb init from start to init func
[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 Multimedia 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 enum
30 {
31         SIGNAL_GET_BASE_PTS,
32         LAST_SIGNAL
33 };
34 enum
35 {
36         ARG_0,
37         ARG_BITRATE,
38 };
39
40 static guint gst_dreamaudiosource_signals[LAST_SIGNAL] = { 0 };
41
42 #define DEFAULT_BITRATE 128
43
44 static GstStaticPadTemplate srctemplate =
45     GST_STATIC_PAD_TEMPLATE ("src",
46         GST_PAD_SRC,
47         GST_PAD_ALWAYS,
48         GST_STATIC_CAPS ("audio/mpeg, "
49         "mpegversion = 4,"
50         "stream-format = (string) adts")
51     );
52
53 #define gst_dreamaudiosource_parent_class parent_class
54 G_DEFINE_TYPE (GstDreamAudioSource, gst_dreamaudiosource, GST_TYPE_PUSH_SRC);
55
56 static GstCaps *gst_dreamaudiosource_getcaps (GstBaseSrc * psrc, GstCaps * filter);
57 static gboolean gst_dreamaudiosource_start (GstBaseSrc * bsrc);
58 static gboolean gst_dreamaudiosource_stop (GstBaseSrc * bsrc);
59 static void gst_dreamaudiosource_finalize (GObject * gobject);
60 static GstFlowReturn gst_dreamaudiosource_create (GstPushSrc * psrc, GstBuffer ** outbuf);
61
62 static void gst_dreamaudiosource_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec);
63 static void gst_dreamaudiosource_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec);
64
65 static GstStateChangeReturn gst_dreamaudiosource_change_state (GstElement * element, GstStateChange transition);
66 static gint64 gst_dreamaudiosource_get_base_pts (GstDreamAudioSource *self);
67
68 static void
69 gst_dreamaudiosource_class_init (GstDreamAudioSourceClass * klass)
70 {
71         GObjectClass *gobject_class;
72         GstElementClass *gstelement_class;
73         GstBaseSrcClass *gstbasesrc_class;
74         GstPushSrcClass *gstpush_src_class;
75
76         gobject_class = (GObjectClass *) klass;
77         gstelement_class = (GstElementClass *) klass;
78         gstbasesrc_class = (GstBaseSrcClass *) klass;
79         gstpush_src_class = (GstPushSrcClass *) klass;
80
81         gobject_class->set_property = gst_dreamaudiosource_set_property;
82         gobject_class->get_property = gst_dreamaudiosource_get_property;
83         gobject_class->finalize = gst_dreamaudiosource_finalize;
84
85         gst_element_class_add_pad_template (gstelement_class,
86                                             gst_static_pad_template_get (&srctemplate));
87
88         gst_element_class_set_static_metadata (gstelement_class,
89             "Dream Audio source", "Source/Audio",
90             "Provide an audio elementary stream from Dreambox encoder device",
91             "Andreas Frisch <fraxinas@opendreambox.org>");
92
93         gstelement_class->change_state = gst_dreamaudiosource_change_state;
94
95         gstbasesrc_class->get_caps = gst_dreamaudiosource_getcaps;
96         gstbasesrc_class->start = gst_dreamaudiosource_start;
97         gstbasesrc_class->stop = gst_dreamaudiosource_stop;
98
99         gstpush_src_class->create = gst_dreamaudiosource_create;
100
101         g_object_class_install_property (G_OBJECT_CLASS (klass), ARG_BITRATE,
102           g_param_spec_int ("bitrate", "Bitrate (kb/s)",
103             "Bitrate in kbit/sec", 16, 320, DEFAULT_BITRATE,
104             G_PARAM_CONSTRUCT | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
105         
106         gst_dreamaudiosource_signals[SIGNAL_GET_BASE_PTS] =
107                 g_signal_new ("get-base-pts",
108                 G_TYPE_FROM_CLASS (klass),
109                 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
110                 G_STRUCT_OFFSET (GstDreamAudioSourceClass, get_base_pts),
111                 NULL, NULL, gst_dreamsource_marshal_INT64__VOID, G_TYPE_INT64, 0);
112
113         klass->get_base_pts = gst_dreamaudiosource_get_base_pts;
114
115 }
116
117 static gint64
118 gst_dreamaudiosource_get_base_pts (GstDreamAudioSource *self)
119 {
120         GST_DEBUG_OBJECT (self, "gst_dreamaudiosource_get_base_pts " GST_TIME_FORMAT"", GST_TIME_ARGS (self->base_pts) );
121         return self->base_pts;
122 }
123
124 static void gst_dreamaudiosource_set_bitrate (GstDreamAudioSource * self, uint32_t bitrate)
125 {
126         if (!self->encoder || !self->encoder->fd)
127                 return;
128         uint32_t abr = bitrate*1000;
129         int ret = ioctl(self->encoder->fd, AENC_SET_BITRATE, &abr);
130         if (ret != 0)
131         {
132                 GST_WARNING_OBJECT (self, "can't set audio bitrate to %i bytes/s!", abr);
133                 return;
134         }
135         GST_INFO_OBJECT (self, "set audio bitrate to %i kBytes/s", bitrate);
136         self->audio_info.bitrate = abr;
137 }
138
139 gboolean
140 gst_dreamaudiosource_plugin_init (GstPlugin *plugin)
141 {
142         GST_DEBUG_CATEGORY_INIT (dreamaudiosource_debug, "dreamaudiosource", 0, "dreamaudiosource");
143         return gst_element_register (plugin, "dreamaudiosource", GST_RANK_PRIMARY, GST_TYPE_DREAMAUDIOSOURCE);
144 }
145
146 static void
147 gst_dreamaudiosource_init (GstDreamAudioSource * self)
148 {
149         self->encoder = NULL;
150         self->descriptors_available = 0;
151         g_mutex_init (&self->mutex);
152         
153         gst_base_src_set_format (GST_BASE_SRC (self), GST_FORMAT_TIME);
154         gst_base_src_set_live (GST_BASE_SRC (self), TRUE);
155
156         self->encoder = malloc(sizeof(EncoderInfo));
157
158         if(!self->encoder) {
159                 GST_ERROR_OBJECT(self,"out of space");
160                 return;
161         }
162
163         char fn_buf[32];
164         sprintf(fn_buf, "/dev/aenc%d", 0);
165         self->encoder->fd = open(fn_buf, O_RDWR | O_SYNC);
166         if(self->encoder->fd <= 0) {
167                 GST_ERROR_OBJECT(self,"cannot open device %s (%s)", fn_buf, strerror(errno));
168                 free(self->encoder);
169                 self->encoder = NULL;
170                 return;
171         }
172
173         self->encoder->buffer = malloc(ABUFSIZE);
174         if(!self->encoder->buffer) {
175                 GST_ERROR_OBJECT(self,"cannot alloc buffer");
176                 return;
177         }
178
179         self->encoder->cdb = (unsigned char *)mmap(0, AMMAPSIZE, PROT_READ, MAP_PRIVATE, self->encoder->fd, 0);
180         if(!self->encoder->cdb || self->encoder->cdb== MAP_FAILED) {
181                 GST_ERROR_OBJECT(self,"cannot mmap cdb: %s (%d)", strerror(errno));
182                 return;
183         }
184
185 #ifdef dump
186         self->dumpfd = open("/media/hdd/movie/dreamaudiosource.dump", O_WRONLY | O_CREAT | O_TRUNC);
187         GST_DEBUG_OBJECT (self, "dumpfd = %i (%s)", self->dumpfd, (self->dumpfd > 0) ? "OK" : strerror(errno));
188 #endif
189
190         gst_dreamaudiosource_set_bitrate(self, DEFAULT_BITRATE);
191 }
192
193 static void
194 gst_dreamaudiosource_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec)
195 {
196         GstDreamAudioSource *self = GST_DREAMAUDIOSOURCE (object);
197         
198         switch (prop_id) {
199                 case ARG_BITRATE:
200                         gst_dreamaudiosource_set_bitrate(self, g_value_get_int (value));
201                         break;
202                 default:
203                         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
204                         break;
205         }
206 }
207
208 static void
209 gst_dreamaudiosource_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec)
210 {
211         GstDreamAudioSource *self = GST_DREAMAUDIOSOURCE (object);
212         
213         switch (prop_id) {
214                 case ARG_BITRATE:
215                         g_value_set_int (value, self->audio_info.bitrate/1000);
216                         break;
217                 default:
218                         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
219                         break;
220         }
221 }
222
223 static GstCaps *
224 gst_dreamaudiosource_getcaps (GstBaseSrc * bsrc, GstCaps * filter)
225 {
226         GstDreamAudioSource *self = GST_DREAMAUDIOSOURCE (bsrc);
227         GstPadTemplate *pad_template;
228         GstCaps *caps;
229
230         pad_template = gst_element_class_get_pad_template (GST_ELEMENT_GET_CLASS(self), "src");
231         g_return_val_if_fail (pad_template != NULL, NULL);
232
233         if (self->encoder == NULL) {
234                 GST_DEBUG_OBJECT (self, "encoder not opened -> use template caps");
235                 caps = gst_pad_template_get_caps (pad_template);
236         }
237         else
238         {
239                 caps = gst_caps_make_writable(gst_pad_template_get_caps (pad_template));
240         }
241
242         GST_INFO_OBJECT (self, "return caps %" GST_PTR_FORMAT, caps);
243         return caps;
244 }
245
246 static void
247 gst_dreamaudiosource_free_buffer (GstDreamAudioSource * self)
248 {
249         GST_LOG_OBJECT (self, "gst_dreamaudiosource_free_buffer");
250 }
251
252 static GstFlowReturn
253 gst_dreamaudiosource_create (GstPushSrc * psrc, GstBuffer ** outbuf)
254 {
255         GstDreamAudioSource *self = GST_DREAMAUDIOSOURCE (psrc);
256         EncoderInfo *enc = self->encoder;
257         static int dumpoffset;
258
259         GST_LOG_OBJECT (self, "new buffer requested");
260
261         if (!enc) {
262                 GST_WARNING_OBJECT (self, "encoder device not opened!");
263                 return GST_FLOW_ERROR;
264         }
265
266         
267         while (1)
268         {
269                 *outbuf = NULL;
270                 
271                 if (self->descriptors_available == 0)
272                 {
273                         self->descriptors_count = 0;
274                         int rlen = read(enc->fd, enc->buffer, ABUFSIZE);
275                         if (rlen <= 0 || rlen % ABDSIZE ) {
276                                 if ( errno == 512 )
277                                         return GST_FLOW_FLUSHING;
278                                 GST_WARNING_OBJECT (self, "read error %s", strerror(errno));
279                                 return GST_FLOW_ERROR;
280                         }
281                         self->descriptors_available = rlen / ABDSIZE;
282                         GST_LOG_OBJECT (self, "encoder buffer was empty, %d descriptors available", self->descriptors_available);
283                 }
284
285                 while (self->descriptors_count < self->descriptors_available) {
286                         off_t offset = self->descriptors_count * ABDSIZE;
287                         AudioBufferDescriptor *desc = (AudioBufferDescriptor*)(&enc->buffer[offset]);
288
289                         uint32_t f = desc->stCommon.uiFlags;
290
291                         GST_LOG_OBJECT (self, "descriptors_count=%d, descriptors_available=%u\tuiOffset=%u, uiLength=%"G_GSIZE_FORMAT"", self->descriptors_count, self->descriptors_available, desc->stCommon.uiOffset, desc->stCommon.uiLength);
292
293                         if (f & CDB_FLAG_METADATA) { 
294                                 GST_LOG_OBJECT (self, "CDB_FLAG_METADATA... skip outdated packet");
295                                 self->descriptors_count = self->descriptors_available;
296                                 continue;
297                         }
298                         
299                         *outbuf = gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY, enc->cdb, AMMAPSIZE, desc->stCommon.uiOffset, desc->stCommon.uiLength, self, (GDestroyNotify)gst_dreamaudiosource_free_buffer);
300                         
301                         if (f & CDB_FLAG_PTS_VALID)
302                         {
303                                 if (G_UNLIKELY (self->base_pts == GST_CLOCK_TIME_NONE))
304                                 {
305                                         if (self->dreamvideosrc)
306                                         {
307                                                 g_mutex_lock (&self->mutex);
308                                                 guint64 videosource_base_pts;
309                                                 g_signal_emit_by_name(self->dreamvideosrc, "get-base-pts", &videosource_base_pts);
310                                                 if (videosource_base_pts != GST_CLOCK_TIME_NONE)
311                                                 {
312                                                         GST_DEBUG_OBJECT (self, "use DREAMVIDEOSOURCE's base_pts=%" GST_TIME_FORMAT "", GST_TIME_ARGS (videosource_base_pts) );
313                                                         self->base_pts = videosource_base_pts;
314                                                 }
315                                                 g_mutex_unlock (&self->mutex);
316                                         }
317                                         else
318                                         {
319                                                 self->base_pts = MPEGTIME_TO_GSTTIME(desc->stCommon.uiPTS);
320                                                 GST_DEBUG_OBJECT (self, "use mpeg stream pts as base_pts=%" GST_TIME_FORMAT"", GST_TIME_ARGS (self->base_pts) );
321                                         }
322                                 }
323                                 GstClockTime buffer_time = MPEGTIME_TO_GSTTIME(desc->stCommon.uiPTS);
324                                 if (self->base_pts != GST_CLOCK_TIME_NONE && buffer_time > self->base_pts )
325                                 {
326                                         buffer_time -= self->base_pts;
327                                         GST_BUFFER_PTS(*outbuf) = buffer_time;
328                                         GST_BUFFER_DTS(*outbuf) = buffer_time;
329                                 }
330                                 
331                         }
332                         
333 #ifdef dump
334                         int wret = write(self->dumpfd, (unsigned char*)(enc->cdb + desc->stCommon.uiOffset), desc->stCommon.uiLength);
335                         dumpoffset += wret;
336                         GST_LOG_OBJECT (self, "read %"G_GSIZE_FORMAT" dumped %i total 0x%08X", desc->stCommon.uiLength, wret, dumpoffset );
337 #endif
338                         self->descriptors_count++;
339
340                         break;
341                 }
342
343                 if (self->descriptors_count == self->descriptors_available) {
344                         GST_LOG_OBJECT (self, "self->descriptors_count == self->descriptors_available -> release %i consumed descriptors", self->descriptors_count);
345                         /* release consumed descs */
346                         if (write(enc->fd, &self->descriptors_count, 4) != 4) {
347                                 GST_WARNING_OBJECT (self, "release consumed descs write error!");
348                                 return GST_FLOW_ERROR;
349                         }
350                         self->descriptors_available = 0;
351                 }
352
353                 if (*outbuf)
354                 {
355                         GST_DEBUG_OBJECT (self, "pushing %" GST_PTR_FORMAT "", *outbuf );
356                         return GST_FLOW_OK;
357                 }
358         }
359
360         return GST_FLOW_ERROR;
361 }
362
363 static GstStateChangeReturn gst_dreamaudiosource_change_state (GstElement * element, GstStateChange transition)
364 {
365         g_return_val_if_fail (element, GST_STATE_CHANGE_FAILURE);
366         GstDreamAudioSource *self = GST_DREAMAUDIOSOURCE (element);
367         int ret;
368
369         switch (transition) {
370                 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
371                         GST_LOG_OBJECT (self, "GST_STATE_CHANGE_PAUSED_TO_PLAYING");
372                         self->base_pts = GST_CLOCK_TIME_NONE;
373                         ret = ioctl(self->encoder->fd, AENC_START);
374                         if ( ret != 0 )
375                         {
376                                 GST_ERROR_OBJECT(self,"can't start encoder ioctl!");
377                                 return GST_STATE_CHANGE_FAILURE;
378                         }
379                         GST_INFO_OBJECT (self, "started encoder!");
380                         break;
381                 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
382                         GST_LOG_OBJECT (self, "GST_STATE_CHANGE_PLAYING_TO_PAUSED");
383                         ret = ioctl(self->encoder->fd, AENC_STOP);
384                         if ( ret != 0 )
385                         {
386                                 GST_ERROR_OBJECT(self,"can't stop encoder ioctl!");
387                                 return GST_STATE_CHANGE_FAILURE;
388                         }
389                         GST_INFO_OBJECT (self, "stopped encoder!");
390                         break;
391                 default:
392                         break;
393         }
394
395         if (GST_ELEMENT_CLASS (parent_class)->change_state)
396                 return GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
397
398         return GST_STATE_CHANGE_SUCCESS;
399 }
400
401 static gboolean
402 gst_dreamaudiosource_start (GstBaseSrc * bsrc)
403 {
404         GstDreamAudioSource *self = GST_DREAMAUDIOSOURCE (bsrc);
405         self->dreamvideosrc = gst_bin_get_by_name_recurse_up(GST_BIN(GST_ELEMENT_PARENT(self)), "dreamvideosource0");
406         self->base_pts = GST_CLOCK_TIME_NONE;
407         GST_DEBUG_OBJECT (self, "started. reference to dreamvideosource=%" GST_PTR_FORMAT"", self->dreamvideosrc);
408         return TRUE;
409 }
410
411 static gboolean
412 gst_dreamaudiosource_stop (GstBaseSrc * bsrc)
413 {
414         GstDreamAudioSource *self = GST_DREAMAUDIOSOURCE (bsrc);
415         GST_DEBUG_OBJECT (self, "closed");
416         return TRUE;
417 }
418
419 static void
420 gst_dreamaudiosource_finalize (GObject * gobject)
421 {
422         GstDreamAudioSource *self = GST_DREAMAUDIOSOURCE (gobject);
423         if (self->encoder) {
424                 if (self->encoder->buffer)
425                         free(self->encoder->buffer);
426                 if (self->encoder->cdb) 
427                         munmap(self->encoder->cdb, AMMAPSIZE);
428                 free(self->encoder);
429         }
430 #ifdef dump
431         close(self->dumpfd);
432 #endif
433         g_mutex_clear (&self->mutex);
434         GST_DEBUG_OBJECT (self, "finalized");
435         G_OBJECT_CLASS (parent_class)->finalize (gobject);
436 }