audioparsers: enable accept-template flag
[platform/upstream/gst-plugins-good.git] / gst / audioparsers / gstdcaparse.c
1 /* GStreamer DCA parser
2  * Copyright (C) 2010 Tim-Philipp Müller <tim centricular net>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 /**
21  * SECTION:element-dcaparse
22  * @short_description: DCA (DTS Coherent Acoustics) parser
23  * @see_also: #GstAmrParse, #GstAACParse, #GstAc3Parse
24  *
25  * This is a DCA (DTS Coherent Acoustics) parser.
26  *
27  * <refsect2>
28  * <title>Example launch line</title>
29  * |[
30  * gst-launch-1.0 filesrc location=abc.dts ! dcaparse ! dtsdec ! audioresample ! audioconvert ! autoaudiosink
31  * ]|
32  * </refsect2>
33  */
34
35 /* TODO:
36  *  - should accept framed and unframed input (needs decodebin fixes first)
37  *  - seeking in raw .dts files doesn't seem to work, but duration estimate ok
38  *
39  *  - if frames have 'odd' durations, the frame durations (plus timestamps)
40  *    aren't adjusted up occasionally to make up for rounding error gaps.
41  *    (e.g. if 512 samples per frame @ 48kHz = 10.666666667 ms/frame)
42  */
43
44 #ifdef HAVE_CONFIG_H
45 #include "config.h"
46 #endif
47
48 #include <string.h>
49
50 #include "gstdcaparse.h"
51 #include <gst/base/base.h>
52 #include <gst/pbutils/pbutils.h>
53
54 GST_DEBUG_CATEGORY_STATIC (dca_parse_debug);
55 #define GST_CAT_DEFAULT dca_parse_debug
56
57 static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
58     GST_PAD_SRC,
59     GST_PAD_ALWAYS,
60     GST_STATIC_CAPS ("audio/x-dts,"
61         " framed = (boolean) true,"
62         " channels = (int) [ 1, 8 ],"
63         " rate = (int) [ 8000, 192000 ],"
64         " depth = (int) { 14, 16 },"
65         " endianness = (int) { LITTLE_ENDIAN, BIG_ENDIAN }, "
66         " block-size = (int) [ 1, MAX], " " frame-size = (int) [ 1, MAX]"));
67
68 static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
69     GST_PAD_SINK,
70     GST_PAD_ALWAYS,
71     GST_STATIC_CAPS ("audio/x-dts; " "audio/x-private1-dts"));
72
73 static void gst_dca_parse_finalize (GObject * object);
74
75 static gboolean gst_dca_parse_start (GstBaseParse * parse);
76 static gboolean gst_dca_parse_stop (GstBaseParse * parse);
77 static GstFlowReturn gst_dca_parse_handle_frame (GstBaseParse * parse,
78     GstBaseParseFrame * frame, gint * skipsize);
79 static GstFlowReturn gst_dca_parse_pre_push_frame (GstBaseParse * parse,
80     GstBaseParseFrame * frame);
81 static GstCaps *gst_dca_parse_get_sink_caps (GstBaseParse * parse,
82     GstCaps * filter);
83 static gboolean gst_dca_parse_set_sink_caps (GstBaseParse * parse,
84     GstCaps * caps);
85
86 #define gst_dca_parse_parent_class parent_class
87 G_DEFINE_TYPE (GstDcaParse, gst_dca_parse, GST_TYPE_BASE_PARSE);
88
89 static void
90 gst_dca_parse_class_init (GstDcaParseClass * klass)
91 {
92   GstBaseParseClass *parse_class = GST_BASE_PARSE_CLASS (klass);
93   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
94   GObjectClass *object_class = G_OBJECT_CLASS (klass);
95
96   GST_DEBUG_CATEGORY_INIT (dca_parse_debug, "dcaparse", 0,
97       "DCA audio stream parser");
98
99   object_class->finalize = gst_dca_parse_finalize;
100
101   parse_class->start = GST_DEBUG_FUNCPTR (gst_dca_parse_start);
102   parse_class->stop = GST_DEBUG_FUNCPTR (gst_dca_parse_stop);
103   parse_class->handle_frame = GST_DEBUG_FUNCPTR (gst_dca_parse_handle_frame);
104   parse_class->pre_push_frame =
105       GST_DEBUG_FUNCPTR (gst_dca_parse_pre_push_frame);
106   parse_class->get_sink_caps = GST_DEBUG_FUNCPTR (gst_dca_parse_get_sink_caps);
107   parse_class->set_sink_caps = GST_DEBUG_FUNCPTR (gst_dca_parse_set_sink_caps);
108
109   gst_element_class_add_pad_template (element_class,
110       gst_static_pad_template_get (&sink_template));
111   gst_element_class_add_pad_template (element_class,
112       gst_static_pad_template_get (&src_template));
113
114   gst_element_class_set_static_metadata (element_class,
115       "DTS Coherent Acoustics audio stream parser", "Codec/Parser/Audio",
116       "DCA parser", "Tim-Philipp Müller <tim centricular net>");
117 }
118
119 static void
120 gst_dca_parse_reset (GstDcaParse * dcaparse)
121 {
122   dcaparse->channels = -1;
123   dcaparse->rate = -1;
124   dcaparse->depth = -1;
125   dcaparse->endianness = -1;
126   dcaparse->block_size = -1;
127   dcaparse->frame_size = -1;
128   dcaparse->last_sync = 0;
129   dcaparse->sent_codec_tag = FALSE;
130 }
131
132 static void
133 gst_dca_parse_init (GstDcaParse * dcaparse)
134 {
135   gst_base_parse_set_min_frame_size (GST_BASE_PARSE (dcaparse),
136       DCA_MIN_FRAMESIZE);
137   gst_dca_parse_reset (dcaparse);
138   dcaparse->baseparse_chainfunc =
139       GST_BASE_PARSE_SINK_PAD (GST_BASE_PARSE (dcaparse))->chainfunc;
140
141   GST_PAD_SET_ACCEPT_INTERSECT (GST_BASE_PARSE_SINK_PAD (dcaparse));
142   GST_PAD_SET_ACCEPT_TEMPLATE (GST_BASE_PARSE_SINK_PAD (dcaparse));
143 }
144
145 static void
146 gst_dca_parse_finalize (GObject * object)
147 {
148   G_OBJECT_CLASS (parent_class)->finalize (object);
149 }
150
151 static gboolean
152 gst_dca_parse_start (GstBaseParse * parse)
153 {
154   GstDcaParse *dcaparse = GST_DCA_PARSE (parse);
155
156   GST_DEBUG_OBJECT (parse, "starting");
157
158   gst_dca_parse_reset (dcaparse);
159
160   return TRUE;
161 }
162
163 static gboolean
164 gst_dca_parse_stop (GstBaseParse * parse)
165 {
166   GST_DEBUG_OBJECT (parse, "stopping");
167
168   return TRUE;
169 }
170
171 static gboolean
172 gst_dca_parse_parse_header (GstDcaParse * dcaparse,
173     const GstByteReader * reader, guint * frame_size,
174     guint * sample_rate, guint * channels, guint * depth,
175     gint * endianness, guint * num_blocks, guint * samples_per_block,
176     gboolean * terminator)
177 {
178   static const int sample_rates[16] = { 0, 8000, 16000, 32000, 0, 0, 11025,
179     22050, 44100, 0, 0, 12000, 24000, 48000, 96000, 192000
180   };
181   static const guint8 channels_table[16] = { 1, 2, 2, 2, 2, 3, 3, 4, 4, 5,
182     6, 6, 6, 7, 8, 8
183   };
184   GstByteReader r = *reader;
185   guint16 hdr[8];
186   guint32 marker;
187   guint chans, lfe, i;
188
189   if (gst_byte_reader_get_remaining (&r) < (4 + sizeof (hdr)))
190     return FALSE;
191
192   marker = gst_byte_reader_peek_uint32_be_unchecked (&r);
193
194   /* raw big endian or 14-bit big endian */
195   if (marker == 0x7FFE8001 || marker == 0x1FFFE800) {
196     for (i = 0; i < G_N_ELEMENTS (hdr); ++i)
197       hdr[i] = gst_byte_reader_get_uint16_be_unchecked (&r);
198   } else
199     /* raw little endian or 14-bit little endian */
200   if (marker == 0xFE7F0180 || marker == 0xFF1F00E8) {
201     for (i = 0; i < G_N_ELEMENTS (hdr); ++i)
202       hdr[i] = gst_byte_reader_get_uint16_le_unchecked (&r);
203   } else {
204     return FALSE;
205   }
206
207   GST_LOG_OBJECT (dcaparse, "dts sync marker 0x%08x at offset %u", marker,
208       gst_byte_reader_get_pos (reader));
209
210   /* 14-bit mode */
211   if (marker == 0x1FFFE800 || marker == 0xFF1F00E8) {
212     if ((hdr[2] & 0xFFF0) != 0x07F0)
213       return FALSE;
214     /* discard top 2 bits (2 void), shift in 2 */
215     hdr[0] = (hdr[0] << 2) | ((hdr[1] >> 12) & 0x0003);
216     /* discard top 4 bits (2 void, 2 shifted into hdr[0]), shift in 4 etc. */
217     hdr[1] = (hdr[1] << 4) | ((hdr[2] >> 10) & 0x000F);
218     hdr[2] = (hdr[2] << 6) | ((hdr[3] >> 8) & 0x003F);
219     hdr[3] = (hdr[3] << 8) | ((hdr[4] >> 6) & 0x00FF);
220     hdr[4] = (hdr[4] << 10) | ((hdr[5] >> 4) & 0x03FF);
221     hdr[5] = (hdr[5] << 12) | ((hdr[6] >> 2) & 0x0FFF);
222     hdr[6] = (hdr[6] << 14) | ((hdr[7] >> 0) & 0x3FFF);
223     g_assert (hdr[0] == 0x7FFE && hdr[1] == 0x8001);
224   }
225
226   GST_LOG_OBJECT (dcaparse, "frame header: %04x%04x%04x%04x",
227       hdr[2], hdr[3], hdr[4], hdr[5]);
228
229   *terminator = (hdr[2] & 0x80) ? FALSE : TRUE;
230   *samples_per_block = ((hdr[2] >> 10) & 0x1f) + 1;
231   *num_blocks = ((hdr[2] >> 2) & 0x7F) + 1;
232   *frame_size = (((hdr[2] & 0x03) << 12) | (hdr[3] >> 4)) + 1;
233   chans = ((hdr[3] & 0x0F) << 2) | (hdr[4] >> 14);
234   *sample_rate = sample_rates[(hdr[4] >> 10) & 0x0F];
235   lfe = (hdr[5] >> 9) & 0x03;
236
237   GST_TRACE_OBJECT (dcaparse, "frame size %u, num_blocks %u, rate %u, "
238       "samples per block %u", *frame_size, *num_blocks, *sample_rate,
239       *samples_per_block);
240
241   if (*num_blocks < 6 || *frame_size < 96 || *sample_rate == 0)
242     return FALSE;
243
244   if (marker == 0x1FFFE800 || marker == 0xFF1F00E8)
245     *frame_size = (*frame_size * 16) / 14;      /* FIXME: round up? */
246
247   if (chans < G_N_ELEMENTS (channels_table))
248     *channels = channels_table[chans] + ((lfe) ? 1 : 0);
249   else
250     *channels = 0;
251
252   if (depth)
253     *depth = (marker == 0x1FFFE800 || marker == 0xFF1F00E8) ? 14 : 16;
254   if (endianness)
255     *endianness = (marker == 0xFE7F0180 || marker == 0xFF1F00E8) ?
256         G_LITTLE_ENDIAN : G_BIG_ENDIAN;
257
258   GST_TRACE_OBJECT (dcaparse, "frame size %u, channels %u, rate %u, "
259       "num_blocks %u, samples_per_block %u", *frame_size, *channels,
260       *sample_rate, *num_blocks, *samples_per_block);
261
262   return TRUE;
263 }
264
265 static gint
266 gst_dca_parse_find_sync (GstDcaParse * dcaparse, GstByteReader * reader,
267     gsize bufsize, guint32 * sync)
268 {
269   guint32 best_sync = 0;
270   guint best_offset = G_MAXUINT;
271   gint off;
272
273   /* FIXME: verify syncs via _parse_header() here already */
274
275   /* Raw little endian */
276   off = gst_byte_reader_masked_scan_uint32 (reader, 0xffffffff, 0xfe7f0180,
277       0, bufsize);
278   if (off >= 0 && off < best_offset) {
279     best_offset = off;
280     best_sync = 0xfe7f0180;
281   }
282
283   /* Raw big endian */
284   off = gst_byte_reader_masked_scan_uint32 (reader, 0xffffffff, 0x7ffe8001,
285       0, bufsize);
286   if (off >= 0 && off < best_offset) {
287     best_offset = off;
288     best_sync = 0x7ffe8001;
289   }
290
291   /* FIXME: check next 2 bytes as well for 14-bit formats (but then don't
292    * forget to adjust the *skipsize= in _check_valid_frame() */
293
294   /* 14-bit little endian  */
295   off = gst_byte_reader_masked_scan_uint32 (reader, 0xffffffff, 0xff1f00e8,
296       0, bufsize);
297   if (off >= 0 && off < best_offset) {
298     best_offset = off;
299     best_sync = 0xff1f00e8;
300   }
301
302   /* 14-bit big endian  */
303   off = gst_byte_reader_masked_scan_uint32 (reader, 0xffffffff, 0x1fffe800,
304       0, bufsize);
305   if (off >= 0 && off < best_offset) {
306     best_offset = off;
307     best_sync = 0x1fffe800;
308   }
309
310   if (best_offset == G_MAXUINT)
311     return -1;
312
313   *sync = best_sync;
314   return best_offset;
315 }
316
317 static GstFlowReturn
318 gst_dca_parse_handle_frame (GstBaseParse * parse,
319     GstBaseParseFrame * frame, gint * skipsize)
320 {
321   GstDcaParse *dcaparse = GST_DCA_PARSE (parse);
322   GstBuffer *buf = frame->buffer;
323   GstByteReader r;
324   gboolean parser_draining;
325   gboolean parser_in_sync;
326   gboolean terminator;
327   guint32 sync = 0;
328   guint size = 0, rate, chans, num_blocks, samples_per_block, depth;
329   gint block_size;
330   gint endianness;
331   gint off = -1;
332   GstMapInfo map;
333   GstFlowReturn ret = GST_FLOW_EOS;
334
335   gst_buffer_map (buf, &map, GST_MAP_READ);
336
337   if (G_UNLIKELY (map.size < 16)) {
338     *skipsize = 1;
339     goto cleanup;
340   }
341
342   parser_in_sync = !GST_BASE_PARSE_LOST_SYNC (parse);
343
344   gst_byte_reader_init (&r, map.data, map.size);
345
346   if (G_LIKELY (parser_in_sync && dcaparse->last_sync != 0)) {
347     off = gst_byte_reader_masked_scan_uint32 (&r, 0xffffffff,
348         dcaparse->last_sync, 0, map.size);
349   }
350
351   if (G_UNLIKELY (off < 0)) {
352     off = gst_dca_parse_find_sync (dcaparse, &r, map.size, &sync);
353   }
354
355   /* didn't find anything that looks like a sync word, skip */
356   if (off < 0) {
357     *skipsize = map.size - 3;
358     GST_DEBUG_OBJECT (dcaparse, "no sync, skipping %d bytes", *skipsize);
359     goto cleanup;
360   }
361
362   GST_LOG_OBJECT (parse, "possible sync %08x at buffer offset %d", sync, off);
363
364   /* possible frame header, but not at offset 0? skip bytes before sync */
365   if (off > 0) {
366     *skipsize = off;
367     goto cleanup;
368   }
369
370   /* make sure the values in the frame header look sane */
371   if (!gst_dca_parse_parse_header (dcaparse, &r, &size, &rate, &chans, &depth,
372           &endianness, &num_blocks, &samples_per_block, &terminator)) {
373     *skipsize = 4;
374     goto cleanup;
375   }
376
377   GST_LOG_OBJECT (parse, "got frame, sync %08x, size %u, rate %d, channels %d",
378       sync, size, rate, chans);
379
380   dcaparse->last_sync = sync;
381
382   parser_draining = GST_BASE_PARSE_DRAINING (parse);
383
384   if (!parser_in_sync && !parser_draining) {
385     /* check for second frame to be sure */
386     GST_DEBUG_OBJECT (dcaparse, "resyncing; checking next frame syncword");
387     if (map.size >= (size + 16)) {
388       guint s2, r2, c2, n2, s3;
389       gboolean t;
390
391       GST_MEMDUMP ("buf", map.data, size + 16);
392       gst_byte_reader_init (&r, map.data, map.size);
393       gst_byte_reader_skip_unchecked (&r, size);
394
395       if (!gst_dca_parse_parse_header (dcaparse, &r, &s2, &r2, &c2, NULL, NULL,
396               &n2, &s3, &t)) {
397         GST_DEBUG_OBJECT (dcaparse, "didn't find second syncword");
398         *skipsize = 4;
399         goto cleanup;
400       }
401
402       /* ok, got sync now, let's assume constant frame size */
403       gst_base_parse_set_min_frame_size (parse, size);
404     } else {
405       /* wait for some more data */
406       GST_LOG_OBJECT (dcaparse,
407           "next sync out of reach (%" G_GSIZE_FORMAT " < %u)", map.size,
408           size + 16);
409       goto cleanup;
410     }
411   }
412
413   /* found frame */
414   ret = GST_FLOW_OK;
415
416   /* metadata handling */
417   block_size = num_blocks * samples_per_block;
418
419   if (G_UNLIKELY (dcaparse->rate != rate || dcaparse->channels != chans
420           || dcaparse->depth != depth || dcaparse->endianness != endianness
421           || (!terminator && dcaparse->block_size != block_size)
422           || (size != dcaparse->frame_size))) {
423     GstCaps *caps;
424
425     caps = gst_caps_new_simple ("audio/x-dts",
426         "framed", G_TYPE_BOOLEAN, TRUE,
427         "rate", G_TYPE_INT, rate, "channels", G_TYPE_INT, chans,
428         "endianness", G_TYPE_INT, endianness, "depth", G_TYPE_INT, depth,
429         "block-size", G_TYPE_INT, block_size, "frame-size", G_TYPE_INT, size,
430         NULL);
431     gst_pad_set_caps (GST_BASE_PARSE_SRC_PAD (parse), caps);
432     gst_caps_unref (caps);
433
434     dcaparse->rate = rate;
435     dcaparse->channels = chans;
436     dcaparse->depth = depth;
437     dcaparse->endianness = endianness;
438     dcaparse->block_size = block_size;
439     dcaparse->frame_size = size;
440
441     gst_base_parse_set_frame_rate (parse, rate, block_size, 0, 0);
442   }
443
444 cleanup:
445   gst_buffer_unmap (buf, &map);
446
447   if (ret == GST_FLOW_OK && size <= map.size) {
448     ret = gst_base_parse_finish_frame (parse, frame, size);
449   } else {
450     ret = GST_FLOW_OK;
451   }
452
453   return ret;
454 }
455
456 /*
457  * MPEG-PS private1 streams add a 2 bytes "Audio Substream Headers" for each
458  * buffer (not each frame) with the offset of the next frame's start.
459  * These 2 bytes can be dropped safely as they do not include any timing
460  * information, only the offset to the start of the next frame.
461  * See gstac3parse.c for a more detailed description.
462  * */
463
464 static GstFlowReturn
465 gst_dca_parse_chain_priv (GstPad * pad, GstObject * parent, GstBuffer * buffer)
466 {
467   GstDcaParse *dcaparse = GST_DCA_PARSE (parent);
468   GstFlowReturn ret;
469   GstBuffer *newbuf;
470   gsize size;
471
472   size = gst_buffer_get_size (buffer);
473   if (size >= 2) {
474     newbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, 2, size - 2);
475     gst_buffer_unref (buffer);
476     ret = dcaparse->baseparse_chainfunc (pad, parent, newbuf);
477   } else {
478     gst_buffer_unref (buffer);
479     ret = GST_FLOW_OK;
480   }
481
482   return ret;
483 }
484
485 static void
486 remove_fields (GstCaps * caps)
487 {
488   guint i, n;
489
490   n = gst_caps_get_size (caps);
491   for (i = 0; i < n; i++) {
492     GstStructure *s = gst_caps_get_structure (caps, i);
493
494     gst_structure_remove_field (s, "framed");
495   }
496 }
497
498 static GstCaps *
499 gst_dca_parse_get_sink_caps (GstBaseParse * parse, GstCaps * filter)
500 {
501   GstCaps *peercaps, *templ;
502   GstCaps *res;
503
504   templ = gst_pad_get_pad_template_caps (GST_BASE_PARSE_SINK_PAD (parse));
505   if (filter) {
506     GstCaps *fcopy = gst_caps_copy (filter);
507     /* Remove the fields we convert */
508     remove_fields (fcopy);
509     peercaps = gst_pad_peer_query_caps (GST_BASE_PARSE_SRC_PAD (parse), fcopy);
510     gst_caps_unref (fcopy);
511   } else
512     peercaps = gst_pad_peer_query_caps (GST_BASE_PARSE_SRC_PAD (parse), NULL);
513
514   if (peercaps) {
515     /* Remove the framed field */
516     peercaps = gst_caps_make_writable (peercaps);
517     remove_fields (peercaps);
518
519     res = gst_caps_intersect_full (peercaps, templ, GST_CAPS_INTERSECT_FIRST);
520     gst_caps_unref (peercaps);
521     gst_caps_unref (templ);
522   } else {
523     res = templ;
524   }
525
526   if (filter) {
527     GstCaps *intersection;
528
529     intersection =
530         gst_caps_intersect_full (filter, res, GST_CAPS_INTERSECT_FIRST);
531     gst_caps_unref (res);
532     res = intersection;
533   }
534
535   return res;
536 }
537
538 static gboolean
539 gst_dca_parse_set_sink_caps (GstBaseParse * parse, GstCaps * caps)
540 {
541   GstStructure *s;
542   GstDcaParse *dcaparse = GST_DCA_PARSE (parse);
543
544   s = gst_caps_get_structure (caps, 0);
545   if (gst_structure_has_name (s, "audio/x-private1-dts")) {
546     gst_pad_set_chain_function (parse->sinkpad, gst_dca_parse_chain_priv);
547   } else {
548     gst_pad_set_chain_function (parse->sinkpad, dcaparse->baseparse_chainfunc);
549   }
550   return TRUE;
551 }
552
553 static GstFlowReturn
554 gst_dca_parse_pre_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
555 {
556   GstDcaParse *dcaparse = GST_DCA_PARSE (parse);
557
558   if (!dcaparse->sent_codec_tag) {
559     GstTagList *taglist;
560     GstCaps *caps;
561
562     taglist = gst_tag_list_new_empty ();
563
564     /* codec tag */
565     caps = gst_pad_get_current_caps (GST_BASE_PARSE_SRC_PAD (parse));
566     gst_pb_utils_add_codec_description_to_tag_list (taglist,
567         GST_TAG_AUDIO_CODEC, caps);
568     gst_caps_unref (caps);
569
570     gst_pad_push_event (GST_BASE_PARSE_SRC_PAD (dcaparse),
571         gst_event_new_tag (taglist));
572
573     /* also signals the end of first-frame processing */
574     dcaparse->sent_codec_tag = TRUE;
575   }
576
577   return GST_FLOW_OK;
578 }