dcaparse: add support for "audio/x-private1-dts"
[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/gstbytereader.h>
52 #include <gst/base/gstbitreader.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 GstCaps *gst_dca_parse_get_sink_caps (GstBaseParse * parse,
80     GstCaps * filter);
81 static gboolean gst_dca_parse_set_sink_caps (GstBaseParse * parse,
82     GstCaps * caps);
83
84 #define gst_dca_parse_parent_class parent_class
85 G_DEFINE_TYPE (GstDcaParse, gst_dca_parse, GST_TYPE_BASE_PARSE);
86
87 static void
88 gst_dca_parse_class_init (GstDcaParseClass * klass)
89 {
90   GstBaseParseClass *parse_class = GST_BASE_PARSE_CLASS (klass);
91   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
92   GObjectClass *object_class = G_OBJECT_CLASS (klass);
93
94   GST_DEBUG_CATEGORY_INIT (dca_parse_debug, "dcaparse", 0,
95       "DCA audio stream parser");
96
97   object_class->finalize = gst_dca_parse_finalize;
98
99   parse_class->start = GST_DEBUG_FUNCPTR (gst_dca_parse_start);
100   parse_class->stop = GST_DEBUG_FUNCPTR (gst_dca_parse_stop);
101   parse_class->handle_frame = GST_DEBUG_FUNCPTR (gst_dca_parse_handle_frame);
102   parse_class->get_sink_caps = GST_DEBUG_FUNCPTR (gst_dca_parse_get_sink_caps);
103   parse_class->set_sink_caps = GST_DEBUG_FUNCPTR (gst_dca_parse_set_sink_caps);
104
105   gst_element_class_add_pad_template (element_class,
106       gst_static_pad_template_get (&sink_template));
107   gst_element_class_add_pad_template (element_class,
108       gst_static_pad_template_get (&src_template));
109
110   gst_element_class_set_static_metadata (element_class,
111       "DTS Coherent Acoustics audio stream parser", "Codec/Parser/Audio",
112       "DCA parser", "Tim-Philipp Müller <tim centricular net>");
113 }
114
115 static void
116 gst_dca_parse_reset (GstDcaParse * dcaparse)
117 {
118   dcaparse->channels = -1;
119   dcaparse->rate = -1;
120   dcaparse->depth = -1;
121   dcaparse->endianness = -1;
122   dcaparse->block_size = -1;
123   dcaparse->frame_size = -1;
124   dcaparse->last_sync = 0;
125 }
126
127 static void
128 gst_dca_parse_init (GstDcaParse * dcaparse)
129 {
130   gst_base_parse_set_min_frame_size (GST_BASE_PARSE (dcaparse),
131       DCA_MIN_FRAMESIZE);
132   gst_dca_parse_reset (dcaparse);
133   dcaparse->baseparse_chainfunc =
134       GST_BASE_PARSE_SINK_PAD (GST_BASE_PARSE (dcaparse))->chainfunc;
135 }
136
137 static void
138 gst_dca_parse_finalize (GObject * object)
139 {
140   G_OBJECT_CLASS (parent_class)->finalize (object);
141 }
142
143 static gboolean
144 gst_dca_parse_start (GstBaseParse * parse)
145 {
146   GstDcaParse *dcaparse = GST_DCA_PARSE (parse);
147
148   GST_DEBUG_OBJECT (parse, "starting");
149
150   gst_dca_parse_reset (dcaparse);
151
152   return TRUE;
153 }
154
155 static gboolean
156 gst_dca_parse_stop (GstBaseParse * parse)
157 {
158   GST_DEBUG_OBJECT (parse, "stopping");
159
160   return TRUE;
161 }
162
163 static gboolean
164 gst_dca_parse_parse_header (GstDcaParse * dcaparse,
165     const GstByteReader * reader, guint * frame_size,
166     guint * sample_rate, guint * channels, guint * depth,
167     gint * endianness, guint * num_blocks, guint * samples_per_block,
168     gboolean * terminator)
169 {
170   static const int sample_rates[16] = { 0, 8000, 16000, 32000, 0, 0, 11025,
171     22050, 44100, 0, 0, 12000, 24000, 48000, 96000, 192000
172   };
173   static const guint8 channels_table[16] = { 1, 2, 2, 2, 2, 3, 3, 4, 4, 5,
174     6, 6, 6, 7, 8, 8
175   };
176   GstByteReader r = *reader;
177   guint16 hdr[8];
178   guint32 marker;
179   guint chans, lfe, i;
180
181   if (gst_byte_reader_get_remaining (&r) < (4 + sizeof (hdr)))
182     return FALSE;
183
184   marker = gst_byte_reader_peek_uint32_be_unchecked (&r);
185
186   /* raw big endian or 14-bit big endian */
187   if (marker == 0x7FFE8001 || marker == 0x1FFFE800) {
188     for (i = 0; i < G_N_ELEMENTS (hdr); ++i)
189       hdr[i] = gst_byte_reader_get_uint16_be_unchecked (&r);
190   } else
191     /* raw little endian or 14-bit little endian */
192   if (marker == 0xFE7F0180 || marker == 0xFF1F00E8) {
193     for (i = 0; i < G_N_ELEMENTS (hdr); ++i)
194       hdr[i] = gst_byte_reader_get_uint16_le_unchecked (&r);
195   } else {
196     return FALSE;
197   }
198
199   GST_LOG_OBJECT (dcaparse, "dts sync marker 0x%08x at offset %u", marker,
200       gst_byte_reader_get_pos (reader));
201
202   /* 14-bit mode */
203   if (marker == 0x1FFFE800 || marker == 0xFF1F00E8) {
204     if ((hdr[2] & 0xFFF0) != 0x07F0)
205       return FALSE;
206     /* discard top 2 bits (2 void), shift in 2 */
207     hdr[0] = (hdr[0] << 2) | ((hdr[1] >> 12) & 0x0003);
208     /* discard top 4 bits (2 void, 2 shifted into hdr[0]), shift in 4 etc. */
209     hdr[1] = (hdr[1] << 4) | ((hdr[2] >> 10) & 0x000F);
210     hdr[2] = (hdr[2] << 6) | ((hdr[3] >> 8) & 0x003F);
211     hdr[3] = (hdr[3] << 8) | ((hdr[4] >> 6) & 0x00FF);
212     hdr[4] = (hdr[4] << 10) | ((hdr[5] >> 4) & 0x03FF);
213     hdr[5] = (hdr[5] << 12) | ((hdr[6] >> 2) & 0x0FFF);
214     hdr[6] = (hdr[6] << 14) | ((hdr[7] >> 0) & 0x3FFF);
215     g_assert (hdr[0] == 0x7FFE && hdr[1] == 0x8001);
216   }
217
218   GST_LOG_OBJECT (dcaparse, "frame header: %04x%04x%04x%04x",
219       hdr[2], hdr[3], hdr[4], hdr[5]);
220
221   *terminator = (hdr[2] & 0x80) ? FALSE : TRUE;
222   *samples_per_block = ((hdr[2] >> 10) & 0x1f) + 1;
223   *num_blocks = ((hdr[2] >> 2) & 0x7F) + 1;
224   *frame_size = (((hdr[2] & 0x03) << 12) | (hdr[3] >> 4)) + 1;
225   chans = ((hdr[3] & 0x0F) << 2) | (hdr[4] >> 14);
226   *sample_rate = sample_rates[(hdr[4] >> 10) & 0x0F];
227   lfe = (hdr[5] >> 9) & 0x03;
228
229   GST_TRACE_OBJECT (dcaparse, "frame size %u, num_blocks %u, rate %u, "
230       "samples per block %u", *frame_size, *num_blocks, *sample_rate,
231       *samples_per_block);
232
233   if (*num_blocks < 6 || *frame_size < 96 || *sample_rate == 0)
234     return FALSE;
235
236   if (marker == 0x1FFFE800 || marker == 0xFF1F00E8)
237     *frame_size = (*frame_size * 16) / 14;      /* FIXME: round up? */
238
239   if (chans < G_N_ELEMENTS (channels_table))
240     *channels = channels_table[chans] + ((lfe) ? 1 : 0);
241   else
242     *channels = 0;
243
244   if (depth)
245     *depth = (marker == 0x1FFFE800 || marker == 0xFF1F00E8) ? 14 : 16;
246   if (endianness)
247     *endianness = (marker == 0xFE7F0180 || marker == 0xFF1F00E8) ?
248         G_LITTLE_ENDIAN : G_BIG_ENDIAN;
249
250   GST_TRACE_OBJECT (dcaparse, "frame size %u, channels %u, rate %u, "
251       "num_blocks %u, samples_per_block %u", *frame_size, *channels,
252       *sample_rate, *num_blocks, *samples_per_block);
253
254   return TRUE;
255 }
256
257 static gint
258 gst_dca_parse_find_sync (GstDcaParse * dcaparse, GstByteReader * reader,
259     gsize bufsize, guint32 * sync)
260 {
261   guint32 best_sync = 0;
262   guint best_offset = G_MAXUINT;
263   gint off;
264
265   /* FIXME: verify syncs via _parse_header() here already */
266
267   /* Raw little endian */
268   off = gst_byte_reader_masked_scan_uint32 (reader, 0xffffffff, 0xfe7f0180,
269       0, bufsize);
270   if (off >= 0 && off < best_offset) {
271     best_offset = off;
272     best_sync = 0xfe7f0180;
273   }
274
275   /* Raw big endian */
276   off = gst_byte_reader_masked_scan_uint32 (reader, 0xffffffff, 0x7ffe8001,
277       0, bufsize);
278   if (off >= 0 && off < best_offset) {
279     best_offset = off;
280     best_sync = 0x7ffe8001;
281   }
282
283   /* FIXME: check next 2 bytes as well for 14-bit formats (but then don't
284    * forget to adjust the *skipsize= in _check_valid_frame() */
285
286   /* 14-bit little endian  */
287   off = gst_byte_reader_masked_scan_uint32 (reader, 0xffffffff, 0xff1f00e8,
288       0, bufsize);
289   if (off >= 0 && off < best_offset) {
290     best_offset = off;
291     best_sync = 0xff1f00e8;
292   }
293
294   /* 14-bit big endian  */
295   off = gst_byte_reader_masked_scan_uint32 (reader, 0xffffffff, 0x1fffe800,
296       0, bufsize);
297   if (off >= 0 && off < best_offset) {
298     best_offset = off;
299     best_sync = 0x1fffe800;
300   }
301
302   if (best_offset == G_MAXUINT)
303     return -1;
304
305   *sync = best_sync;
306   return best_offset;
307 }
308
309 static GstFlowReturn
310 gst_dca_parse_handle_frame (GstBaseParse * parse,
311     GstBaseParseFrame * frame, gint * skipsize)
312 {
313   GstDcaParse *dcaparse = GST_DCA_PARSE (parse);
314   GstBuffer *buf = frame->buffer;
315   GstByteReader r;
316   gboolean parser_draining;
317   gboolean parser_in_sync;
318   gboolean terminator;
319   guint32 sync = 0;
320   guint size, rate, chans, num_blocks, samples_per_block, depth;
321   gint block_size;
322   gint endianness;
323   gint off = -1;
324   GstMapInfo map;
325   GstFlowReturn ret = GST_FLOW_EOS;
326
327   gst_buffer_map (buf, &map, GST_MAP_READ);
328
329   if (G_UNLIKELY (map.size < 16)) {
330     *skipsize = 1;
331     goto cleanup;
332   }
333
334   parser_in_sync = !GST_BASE_PARSE_LOST_SYNC (parse);
335
336   gst_byte_reader_init (&r, map.data, map.size);
337
338   if (G_LIKELY (parser_in_sync && dcaparse->last_sync != 0)) {
339     off = gst_byte_reader_masked_scan_uint32 (&r, 0xffffffff,
340         dcaparse->last_sync, 0, map.size);
341   }
342
343   if (G_UNLIKELY (off < 0)) {
344     off = gst_dca_parse_find_sync (dcaparse, &r, map.size, &sync);
345   }
346
347   /* didn't find anything that looks like a sync word, skip */
348   if (off < 0) {
349     *skipsize = map.size - 3;
350     GST_DEBUG_OBJECT (dcaparse, "no sync, skipping %d bytes", *skipsize);
351     goto cleanup;
352   }
353
354   GST_LOG_OBJECT (parse, "possible sync %08x at buffer offset %d", sync, off);
355
356   /* possible frame header, but not at offset 0? skip bytes before sync */
357   if (off > 0) {
358     *skipsize = off;
359     goto cleanup;
360   }
361
362   /* make sure the values in the frame header look sane */
363   if (!gst_dca_parse_parse_header (dcaparse, &r, &size, &rate, &chans, &depth,
364           &endianness, &num_blocks, &samples_per_block, &terminator)) {
365     *skipsize = 4;
366     goto cleanup;
367   }
368
369   GST_LOG_OBJECT (parse, "got frame, sync %08x, size %u, rate %d, channels %d",
370       sync, size, rate, chans);
371
372   dcaparse->last_sync = sync;
373
374   parser_draining = GST_BASE_PARSE_DRAINING (parse);
375
376   if (!parser_in_sync && !parser_draining) {
377     /* check for second frame to be sure */
378     GST_DEBUG_OBJECT (dcaparse, "resyncing; checking next frame syncword");
379     if (map.size >= (size + 16)) {
380       guint s2, r2, c2, n2, s3;
381       gboolean t;
382
383       GST_MEMDUMP ("buf", map.data, size + 16);
384       gst_byte_reader_init (&r, map.data, map.size);
385       gst_byte_reader_skip_unchecked (&r, size);
386
387       if (!gst_dca_parse_parse_header (dcaparse, &r, &s2, &r2, &c2, NULL, NULL,
388               &n2, &s3, &t)) {
389         GST_DEBUG_OBJECT (dcaparse, "didn't find second syncword");
390         *skipsize = 4;
391         goto cleanup;
392       }
393
394       /* ok, got sync now, let's assume constant frame size */
395       gst_base_parse_set_min_frame_size (parse, size);
396     } else {
397       /* wait for some more data */
398       GST_LOG_OBJECT (dcaparse,
399           "next sync out of reach (%" G_GSIZE_FORMAT " < %u)", map.size,
400           size + 16);
401       goto cleanup;
402     }
403   }
404
405   /* found frame */
406   ret = GST_FLOW_OK;
407
408   /* metadata handling */
409   block_size = num_blocks * samples_per_block;
410
411   if (G_UNLIKELY (dcaparse->rate != rate || dcaparse->channels != chans
412           || dcaparse->depth != depth || dcaparse->endianness != endianness
413           || (!terminator && dcaparse->block_size != block_size)
414           || (size != dcaparse->frame_size))) {
415     GstCaps *caps;
416
417     caps = gst_caps_new_simple ("audio/x-dts",
418         "framed", G_TYPE_BOOLEAN, TRUE,
419         "rate", G_TYPE_INT, rate, "channels", G_TYPE_INT, chans,
420         "endianness", G_TYPE_INT, endianness, "depth", G_TYPE_INT, depth,
421         "block-size", G_TYPE_INT, block_size, "frame-size", G_TYPE_INT, size,
422         NULL);
423     gst_pad_set_caps (GST_BASE_PARSE_SRC_PAD (parse), caps);
424     gst_caps_unref (caps);
425
426     dcaparse->rate = rate;
427     dcaparse->channels = chans;
428     dcaparse->depth = depth;
429     dcaparse->endianness = endianness;
430     dcaparse->block_size = block_size;
431     dcaparse->frame_size = size;
432
433     gst_base_parse_set_frame_rate (parse, rate, block_size, 0, 0);
434   }
435
436 cleanup:
437   gst_buffer_unmap (buf, &map);
438
439   if (ret == GST_FLOW_OK && size <= map.size) {
440     ret = gst_base_parse_finish_frame (parse, frame, size);
441   } else {
442     ret = GST_FLOW_OK;
443   }
444
445   return ret;
446 }
447
448 /*
449  * MPEG-PS private1 streams add a 2 bytes "Audio Substream Headers" for each
450  * buffer (not each frame) with the offset of the next frame's start.
451  * These 2 bytes can be dropped safely as they do not include any timing
452  * information, only the offset to the start of the next frame.
453  * See gstac3parse.c for a more detailed description.
454  * */
455
456 static GstFlowReturn
457 gst_dca_parse_chain_priv (GstPad * pad, GstObject *parent, GstBuffer * buffer)
458 {
459   GstBuffer *newbuf;
460   GstFlowReturn ret;
461   GstDcaParse *dcaparse = GST_DCA_PARSE (parent);
462
463   newbuf = gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL,
464       2, gst_buffer_get_size (buffer) - 2);
465   ret = dcaparse->baseparse_chainfunc (pad, parent, newbuf);
466   gst_buffer_unref (buffer);
467   return ret;
468 }
469
470 static GstCaps *
471 gst_dca_parse_get_sink_caps (GstBaseParse * parse, GstCaps * filter)
472 {
473   GstCaps *peercaps, *templ;
474   GstCaps *res;
475
476   templ = gst_pad_get_pad_template_caps (GST_BASE_PARSE_SINK_PAD (parse));
477   peercaps = gst_pad_peer_query_caps (GST_BASE_PARSE_SRC_PAD (parse), filter);
478
479   if (peercaps) {
480     guint i, n;
481
482     /* Remove the framed field */
483     peercaps = gst_caps_make_writable (peercaps);
484     n = gst_caps_get_size (peercaps);
485     for (i = 0; i < n; i++) {
486       GstStructure *s = gst_caps_get_structure (peercaps, i);
487
488       gst_structure_remove_field (s, "framed");
489     }
490
491     res = gst_caps_intersect_full (peercaps, templ, GST_CAPS_INTERSECT_FIRST);
492     gst_caps_unref (peercaps);
493     res = gst_caps_make_writable (res);
494
495     /* Append the template caps because we still want to accept
496      * caps without any fields in the case upstream does not
497      * know anything.
498      */
499     gst_caps_append (res, templ);
500   } else {
501     res = templ;
502   }
503
504   if (filter) {
505     GstCaps *intersection;
506
507     intersection =
508         gst_caps_intersect_full (filter, res, GST_CAPS_INTERSECT_FIRST);
509     gst_caps_unref (res);
510     res = intersection;
511   }
512
513   return res;
514 }
515
516 static gboolean
517 gst_dca_parse_set_sink_caps (GstBaseParse * parse, GstCaps * caps)
518 {
519   GstStructure *s;
520   GstDcaParse *dcaparse = GST_DCA_PARSE (parse);
521
522   s = gst_caps_get_structure (caps, 0);
523   if (gst_structure_has_name (s, "audio/x-private1-dts")) {
524     gst_pad_set_chain_function (parse->sinkpad, gst_dca_parse_chain_priv);
525   } else {
526     gst_pad_set_chain_function (parse->sinkpad, dcaparse->baseparse_chainfunc);
527   }
528   return TRUE;
529 }