audioparsers: use new base parse API to fix tag handling
[platform/upstream/gst-plugins-good.git] / gst / audioparsers / gstac3parse.c
1 /* GStreamer AC3 parser
2  * Copyright (C) 2009 Tim-Philipp Müller <tim centricular net>
3  * Copyright (C) 2009 Mark Nauwelaerts <mnauw users sf net>
4  * Copyright (C) 2009 Nokia Corporation. All rights reserved.
5  *   Contact: Stefan Kost <stefan.kost@nokia.com>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22 /**
23  * SECTION:element-ac3parse
24  * @short_description: AC3 parser
25  * @see_also: #GstAmrParse, #GstAACParse
26  *
27  * This is an AC3 parser.
28  *
29  * <refsect2>
30  * <title>Example launch line</title>
31  * |[
32  * gst-launch-1.0 filesrc location=abc.ac3 ! ac3parse ! a52dec ! audioresample ! audioconvert ! autoaudiosink
33  * ]|
34  * </refsect2>
35  */
36
37 /* TODO:
38  *  - audio/ac3 to audio/x-private1-ac3 is not implemented (done in the muxer)
39  *  - should accept framed and unframed input (needs decodebin fixes first)
40  */
41
42 #ifdef HAVE_CONFIG_H
43 #include "config.h"
44 #endif
45
46 #include <string.h>
47
48 #include "gstac3parse.h"
49 #include <gst/base/base.h>
50 #include <gst/pbutils/pbutils.h>
51
52 GST_DEBUG_CATEGORY_STATIC (ac3_parse_debug);
53 #define GST_CAT_DEFAULT ac3_parse_debug
54
55 static const struct
56 {
57   const guint bit_rate;         /* nominal bit rate */
58   const guint frame_size[3];    /* frame size for 32kHz, 44kHz, and 48kHz */
59 } frmsizcod_table[38] = {
60   {
61     32, {
62   64, 69, 96}}, {
63     32, {
64   64, 70, 96}}, {
65     40, {
66   80, 87, 120}}, {
67     40, {
68   80, 88, 120}}, {
69     48, {
70   96, 104, 144}}, {
71     48, {
72   96, 105, 144}}, {
73     56, {
74   112, 121, 168}}, {
75     56, {
76   112, 122, 168}}, {
77     64, {
78   128, 139, 192}}, {
79     64, {
80   128, 140, 192}}, {
81     80, {
82   160, 174, 240}}, {
83     80, {
84   160, 175, 240}}, {
85     96, {
86   192, 208, 288}}, {
87     96, {
88   192, 209, 288}}, {
89     112, {
90   224, 243, 336}}, {
91     112, {
92   224, 244, 336}}, {
93     128, {
94   256, 278, 384}}, {
95     128, {
96   256, 279, 384}}, {
97     160, {
98   320, 348, 480}}, {
99     160, {
100   320, 349, 480}}, {
101     192, {
102   384, 417, 576}}, {
103     192, {
104   384, 418, 576}}, {
105     224, {
106   448, 487, 672}}, {
107     224, {
108   448, 488, 672}}, {
109     256, {
110   512, 557, 768}}, {
111     256, {
112   512, 558, 768}}, {
113     320, {
114   640, 696, 960}}, {
115     320, {
116   640, 697, 960}}, {
117     384, {
118   768, 835, 1152}}, {
119     384, {
120   768, 836, 1152}}, {
121     448, {
122   896, 975, 1344}}, {
123     448, {
124   896, 976, 1344}}, {
125     512, {
126   1024, 1114, 1536}}, {
127     512, {
128   1024, 1115, 1536}}, {
129     576, {
130   1152, 1253, 1728}}, {
131     576, {
132   1152, 1254, 1728}}, {
133     640, {
134   1280, 1393, 1920}}, {
135     640, {
136   1280, 1394, 1920}}
137 };
138
139 static const guint fscod_rates[4] = { 48000, 44100, 32000, 0 };
140 static const guint acmod_chans[8] = { 2, 1, 2, 3, 3, 4, 4, 5 };
141 static const guint numblks[4] = { 1, 2, 3, 6 };
142
143 static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
144     GST_PAD_SRC,
145     GST_PAD_ALWAYS,
146     GST_STATIC_CAPS ("audio/x-ac3, framed = (boolean) true, "
147         " channels = (int) [ 1, 6 ], rate = (int) [ 8000, 48000 ], "
148         " alignment = (string) { iec61937, frame}; "
149         "audio/x-eac3, framed = (boolean) true, "
150         " channels = (int) [ 1, 6 ], rate = (int) [ 8000, 48000 ], "
151         " alignment = (string) { iec61937, frame}; "));
152
153 static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
154     GST_PAD_SINK,
155     GST_PAD_ALWAYS,
156     GST_STATIC_CAPS ("audio/x-ac3; " "audio/x-eac3; " "audio/ac3; "
157         "audio/x-private1-ac3"));
158
159 static void gst_ac3_parse_finalize (GObject * object);
160
161 static gboolean gst_ac3_parse_start (GstBaseParse * parse);
162 static gboolean gst_ac3_parse_stop (GstBaseParse * parse);
163 static GstFlowReturn gst_ac3_parse_handle_frame (GstBaseParse * parse,
164     GstBaseParseFrame * frame, gint * skipsize);
165 static GstFlowReturn gst_ac3_parse_pre_push_frame (GstBaseParse * parse,
166     GstBaseParseFrame * frame);
167 static gboolean gst_ac3_parse_src_event (GstBaseParse * parse,
168     GstEvent * event);
169 static GstCaps *gst_ac3_parse_get_sink_caps (GstBaseParse * parse,
170     GstCaps * filter);
171 static gboolean gst_ac3_parse_set_sink_caps (GstBaseParse * parse,
172     GstCaps * caps);
173
174 #define gst_ac3_parse_parent_class parent_class
175 G_DEFINE_TYPE (GstAc3Parse, gst_ac3_parse, GST_TYPE_BASE_PARSE);
176
177 static void
178 gst_ac3_parse_class_init (GstAc3ParseClass * klass)
179 {
180   GObjectClass *object_class = G_OBJECT_CLASS (klass);
181   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
182   GstBaseParseClass *parse_class = GST_BASE_PARSE_CLASS (klass);
183
184   GST_DEBUG_CATEGORY_INIT (ac3_parse_debug, "ac3parse", 0,
185       "AC3 audio stream parser");
186
187   object_class->finalize = gst_ac3_parse_finalize;
188
189   gst_element_class_add_pad_template (element_class,
190       gst_static_pad_template_get (&sink_template));
191   gst_element_class_add_pad_template (element_class,
192       gst_static_pad_template_get (&src_template));
193
194   gst_element_class_set_static_metadata (element_class,
195       "AC3 audio stream parser", "Codec/Parser/Converter/Audio",
196       "AC3 parser", "Tim-Philipp Müller <tim centricular net>");
197
198   parse_class->start = GST_DEBUG_FUNCPTR (gst_ac3_parse_start);
199   parse_class->stop = GST_DEBUG_FUNCPTR (gst_ac3_parse_stop);
200   parse_class->handle_frame = GST_DEBUG_FUNCPTR (gst_ac3_parse_handle_frame);
201   parse_class->pre_push_frame =
202       GST_DEBUG_FUNCPTR (gst_ac3_parse_pre_push_frame);
203   parse_class->src_event = GST_DEBUG_FUNCPTR (gst_ac3_parse_src_event);
204   parse_class->get_sink_caps = GST_DEBUG_FUNCPTR (gst_ac3_parse_get_sink_caps);
205   parse_class->set_sink_caps = GST_DEBUG_FUNCPTR (gst_ac3_parse_set_sink_caps);
206 }
207
208 static void
209 gst_ac3_parse_reset (GstAc3Parse * ac3parse)
210 {
211   ac3parse->channels = -1;
212   ac3parse->sample_rate = -1;
213   ac3parse->blocks = -1;
214   ac3parse->eac = FALSE;
215   ac3parse->sent_codec_tag = FALSE;
216   g_atomic_int_set (&ac3parse->align, GST_AC3_PARSE_ALIGN_NONE);
217 }
218
219 static void
220 gst_ac3_parse_init (GstAc3Parse * ac3parse)
221 {
222   gst_base_parse_set_min_frame_size (GST_BASE_PARSE (ac3parse), 8);
223   gst_ac3_parse_reset (ac3parse);
224   ac3parse->baseparse_chainfunc =
225       GST_BASE_PARSE_SINK_PAD (GST_BASE_PARSE (ac3parse))->chainfunc;
226   GST_PAD_SET_ACCEPT_INTERSECT (GST_BASE_PARSE_SINK_PAD (ac3parse));
227   GST_PAD_SET_ACCEPT_TEMPLATE (GST_BASE_PARSE_SINK_PAD (ac3parse));
228 }
229
230 static void
231 gst_ac3_parse_finalize (GObject * object)
232 {
233   G_OBJECT_CLASS (parent_class)->finalize (object);
234 }
235
236 static gboolean
237 gst_ac3_parse_start (GstBaseParse * parse)
238 {
239   GstAc3Parse *ac3parse = GST_AC3_PARSE (parse);
240
241   GST_DEBUG_OBJECT (parse, "starting");
242
243   gst_ac3_parse_reset (ac3parse);
244
245   return TRUE;
246 }
247
248 static gboolean
249 gst_ac3_parse_stop (GstBaseParse * parse)
250 {
251   GST_DEBUG_OBJECT (parse, "stopping");
252
253   return TRUE;
254 }
255
256 static void
257 gst_ac3_parse_set_alignment (GstAc3Parse * ac3parse, gboolean eac)
258 {
259   GstCaps *caps;
260   GstStructure *st;
261   const gchar *str = NULL;
262   int i;
263
264   if (G_LIKELY (!eac))
265     goto done;
266
267   caps = gst_pad_get_allowed_caps (GST_BASE_PARSE_SRC_PAD (ac3parse));
268
269   if (!caps)
270     goto done;
271
272   for (i = 0; i < gst_caps_get_size (caps); i++) {
273     st = gst_caps_get_structure (caps, i);
274
275     if (!g_str_equal (gst_structure_get_name (st), "audio/x-eac3"))
276       continue;
277
278     if ((str = gst_structure_get_string (st, "alignment"))) {
279       if (g_str_equal (str, "iec61937")) {
280         g_atomic_int_set (&ac3parse->align, GST_AC3_PARSE_ALIGN_IEC61937);
281         GST_DEBUG_OBJECT (ac3parse, "picked iec61937 alignment");
282       } else if (g_str_equal (str, "frame") == 0) {
283         g_atomic_int_set (&ac3parse->align, GST_AC3_PARSE_ALIGN_FRAME);
284         GST_DEBUG_OBJECT (ac3parse, "picked frame alignment");
285       } else {
286         g_atomic_int_set (&ac3parse->align, GST_AC3_PARSE_ALIGN_FRAME);
287         GST_WARNING_OBJECT (ac3parse, "unknown alignment: %s", str);
288       }
289       break;
290     }
291   }
292
293   if (caps)
294     gst_caps_unref (caps);
295
296 done:
297   /* default */
298   if (ac3parse->align == GST_AC3_PARSE_ALIGN_NONE) {
299     g_atomic_int_set (&ac3parse->align, GST_AC3_PARSE_ALIGN_FRAME);
300     GST_DEBUG_OBJECT (ac3parse, "picked syncframe alignment");
301   }
302 }
303
304 static gboolean
305 gst_ac3_parse_frame_header_ac3 (GstAc3Parse * ac3parse, GstBuffer * buf,
306     gint skip, guint * frame_size, guint * rate, guint * chans, guint * blks,
307     guint * sid)
308 {
309   GstBitReader bits;
310   GstMapInfo map;
311   guint8 fscod, frmsizcod, bsid, acmod, lfe_on, rate_scale;
312   gboolean ret = FALSE;
313
314   GST_LOG_OBJECT (ac3parse, "parsing ac3");
315
316   gst_buffer_map (buf, &map, GST_MAP_READ);
317   gst_bit_reader_init (&bits, map.data, map.size);
318   gst_bit_reader_skip_unchecked (&bits, skip * 8);
319
320   gst_bit_reader_skip_unchecked (&bits, 16 + 16);
321   fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);
322   frmsizcod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 6);
323
324   if (G_UNLIKELY (fscod == 3 || frmsizcod >= G_N_ELEMENTS (frmsizcod_table))) {
325     GST_DEBUG_OBJECT (ac3parse, "bad fscod=%d frmsizcod=%d", fscod, frmsizcod);
326     goto cleanup;
327   }
328
329   bsid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 5);
330   gst_bit_reader_skip_unchecked (&bits, 3);     /* bsmod */
331   acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);
332
333   /* spec not quite clear here: decoder should decode if less than 8,
334    * but seemingly only defines 6 and 8 cases */
335   /* Files with 9 and 10 happen, and seem to comply with the <= 8
336      format, so let them through. The spec says nothing about 9 and 10 */
337   if (bsid > 10) {
338     GST_DEBUG_OBJECT (ac3parse, "unexpected bsid=%d", bsid);
339     goto cleanup;
340   } else if (bsid != 8 && bsid != 6) {
341     GST_DEBUG_OBJECT (ac3parse, "undefined bsid=%d", bsid);
342   }
343
344   if ((acmod & 0x1) && (acmod != 0x1))  /* 3 front channels */
345     gst_bit_reader_skip_unchecked (&bits, 2);
346   if ((acmod & 0x4))            /* if a surround channel exists */
347     gst_bit_reader_skip_unchecked (&bits, 2);
348   if (acmod == 0x2)             /* if in 2/0 mode */
349     gst_bit_reader_skip_unchecked (&bits, 2);
350
351   lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1);
352
353   /* 6/8->0, 9->1, 10->2,
354      see http://matroska.org/technical/specs/codecid/index.html */
355   rate_scale = (CLAMP (bsid, 8, 10) - 8);
356
357   if (frame_size)
358     *frame_size = frmsizcod_table[frmsizcod].frame_size[fscod] * 2;
359   if (rate)
360     *rate = fscod_rates[fscod] >> rate_scale;
361   if (chans)
362     *chans = acmod_chans[acmod] + lfe_on;
363   if (blks)
364     *blks = 6;
365   if (sid)
366     *sid = 0;
367
368   ret = TRUE;
369
370 cleanup:
371   gst_buffer_unmap (buf, &map);
372
373   return ret;
374 }
375
376 static gboolean
377 gst_ac3_parse_frame_header_eac3 (GstAc3Parse * ac3parse, GstBuffer * buf,
378     gint skip, guint * frame_size, guint * rate, guint * chans, guint * blks,
379     guint * sid)
380 {
381   GstBitReader bits;
382   GstMapInfo map;
383   guint16 frmsiz, sample_rate, blocks;
384   guint8 strmtyp, fscod, fscod2, acmod, lfe_on, strmid, numblkscod;
385   gboolean ret = FALSE;
386
387   GST_LOG_OBJECT (ac3parse, "parsing e-ac3");
388
389   gst_buffer_map (buf, &map, GST_MAP_READ);
390   gst_bit_reader_init (&bits, map.data, map.size);
391   gst_bit_reader_skip_unchecked (&bits, skip * 8);
392
393   gst_bit_reader_skip_unchecked (&bits, 16);
394   strmtyp = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2); /* strmtyp     */
395   if (G_UNLIKELY (strmtyp == 3)) {
396     GST_DEBUG_OBJECT (ac3parse, "bad strmtyp %d", strmtyp);
397     goto cleanup;
398   }
399
400   strmid = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);  /* substreamid */
401   frmsiz = gst_bit_reader_get_bits_uint16_unchecked (&bits, 11);        /* frmsiz      */
402   fscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);   /* fscod       */
403   if (fscod == 3) {
404     fscod2 = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);        /* fscod2      */
405     if (G_UNLIKELY (fscod2 == 3)) {
406       GST_DEBUG_OBJECT (ac3parse, "invalid fscod2");
407       goto cleanup;
408     }
409     sample_rate = fscod_rates[fscod2] / 2;
410     blocks = 6;
411   } else {
412     numblkscod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 2);    /* numblkscod  */
413     sample_rate = fscod_rates[fscod];
414     blocks = numblks[numblkscod];
415   }
416
417   acmod = gst_bit_reader_get_bits_uint8_unchecked (&bits, 3);   /* acmod       */
418   lfe_on = gst_bit_reader_get_bits_uint8_unchecked (&bits, 1);  /* lfeon       */
419
420   gst_bit_reader_skip_unchecked (&bits, 5);     /* bsid        */
421
422   if (frame_size)
423     *frame_size = (frmsiz + 1) * 2;
424   if (rate)
425     *rate = sample_rate;
426   if (chans)
427     *chans = acmod_chans[acmod] + lfe_on;
428   if (blks)
429     *blks = blocks;
430   if (sid)
431     *sid = (strmtyp & 0x1) << 3 | strmid;
432
433   ret = TRUE;
434
435 cleanup:
436   gst_buffer_unmap (buf, &map);
437
438   return ret;
439 }
440
441 static gboolean
442 gst_ac3_parse_frame_header (GstAc3Parse * parse, GstBuffer * buf, gint skip,
443     guint * framesize, guint * rate, guint * chans, guint * blocks,
444     guint * sid, gboolean * eac)
445 {
446   GstBitReader bits;
447   guint16 sync;
448   guint8 bsid;
449   GstMapInfo map;
450   gboolean ret = FALSE;
451
452   gst_buffer_map (buf, &map, GST_MAP_READ);
453   gst_bit_reader_init (&bits, map.data, map.size);
454
455   GST_MEMDUMP_OBJECT (parse, "AC3 frame sync", map.data, MIN (map.size, 16));
456
457   gst_bit_reader_skip_unchecked (&bits, skip * 8);
458
459   sync = gst_bit_reader_get_bits_uint16_unchecked (&bits, 16);
460   gst_bit_reader_skip_unchecked (&bits, 16 + 8);
461   bsid = gst_bit_reader_peek_bits_uint8_unchecked (&bits, 5);
462
463   if (G_UNLIKELY (sync != 0x0b77))
464     goto cleanup;
465
466   GST_LOG_OBJECT (parse, "bsid = %d", bsid);
467
468   if (bsid <= 10) {
469     if (eac)
470       *eac = FALSE;
471     ret = gst_ac3_parse_frame_header_ac3 (parse, buf, skip, framesize, rate,
472         chans, blocks, sid);
473     goto cleanup;
474   } else if (bsid <= 16) {
475     if (eac)
476       *eac = TRUE;
477     ret = gst_ac3_parse_frame_header_eac3 (parse, buf, skip, framesize, rate,
478         chans, blocks, sid);
479     goto cleanup;
480   } else {
481     GST_DEBUG_OBJECT (parse, "unexpected bsid %d", bsid);
482     ret = FALSE;
483     goto cleanup;
484   }
485
486   GST_DEBUG_OBJECT (parse, "unexpected bsid %d", bsid);
487
488 cleanup:
489   gst_buffer_unmap (buf, &map);
490
491   return ret;
492 }
493
494 static GstFlowReturn
495 gst_ac3_parse_handle_frame (GstBaseParse * parse,
496     GstBaseParseFrame * frame, gint * skipsize)
497 {
498   GstAc3Parse *ac3parse = GST_AC3_PARSE (parse);
499   GstBuffer *buf = frame->buffer;
500   GstByteReader reader;
501   gint off;
502   gboolean lost_sync, draining, eac, more = FALSE;
503   guint frmsiz, blocks, sid;
504   guint rate, chans;
505   gboolean update_rate = FALSE;
506   gint framesize = 0;
507   gint have_blocks = 0;
508   GstMapInfo map;
509   gboolean ret = FALSE;
510   GstFlowReturn res = GST_FLOW_OK;
511
512   gst_buffer_map (buf, &map, GST_MAP_READ);
513
514   if (G_UNLIKELY (map.size < 8)) {
515     *skipsize = 1;
516     goto cleanup;
517   }
518
519   gst_byte_reader_init (&reader, map.data, map.size);
520   off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000, 0x0b770000,
521       0, map.size);
522
523   GST_LOG_OBJECT (parse, "possible sync at buffer offset %d", off);
524
525   /* didn't find anything that looks like a sync word, skip */
526   if (off < 0) {
527     *skipsize = map.size - 3;
528     goto cleanup;
529   }
530
531   /* possible frame header, but not at offset 0? skip bytes before sync */
532   if (off > 0) {
533     *skipsize = off;
534     goto cleanup;
535   }
536
537   /* make sure the values in the frame header look sane */
538   if (!gst_ac3_parse_frame_header (ac3parse, buf, 0, &frmsiz, &rate, &chans,
539           &blocks, &sid, &eac)) {
540     *skipsize = off + 2;
541     goto cleanup;
542   }
543
544   GST_LOG_OBJECT (parse, "size: %u, blocks: %u, rate: %u, chans: %u", frmsiz,
545       blocks, rate, chans);
546
547   framesize = frmsiz;
548
549   if (G_UNLIKELY (g_atomic_int_get (&ac3parse->align) ==
550           GST_AC3_PARSE_ALIGN_NONE))
551     gst_ac3_parse_set_alignment (ac3parse, eac);
552
553   GST_LOG_OBJECT (parse, "got frame");
554
555   lost_sync = GST_BASE_PARSE_LOST_SYNC (parse);
556   draining = GST_BASE_PARSE_DRAINING (parse);
557
558   if (g_atomic_int_get (&ac3parse->align) == GST_AC3_PARSE_ALIGN_IEC61937) {
559     /* We need 6 audio blocks from each substream, so we keep going forwards
560      * till we have it */
561
562     g_assert (blocks > 0);
563     GST_LOG_OBJECT (ac3parse, "Need %d frames before pushing", 6 / blocks);
564
565     if (sid != 0) {
566       /* We need the first substream to be the one with id 0 */
567       GST_LOG_OBJECT (ac3parse, "Skipping till we find sid 0");
568       *skipsize = off + 2;
569       goto cleanup;
570     }
571
572     framesize = 0;
573
574     /* Loop till we have 6 blocks per substream */
575     for (have_blocks = 0; !more && have_blocks < 6; have_blocks += blocks) {
576       /* Loop till we get one frame from each substream */
577       do {
578         framesize += frmsiz;
579
580         if (!gst_byte_reader_skip (&reader, frmsiz)
581             || map.size < (framesize + 6)) {
582           more = TRUE;
583           break;
584         }
585
586         if (!gst_ac3_parse_frame_header (ac3parse, buf, framesize, &frmsiz,
587                 NULL, NULL, NULL, &sid, &eac)) {
588           *skipsize = off + 2;
589           goto cleanup;
590         }
591       } while (sid);
592     }
593
594     /* We're now at the next frame, so no need to skip if resyncing */
595     frmsiz = 0;
596   }
597
598   if (lost_sync && !draining) {
599     guint16 word = 0;
600
601     GST_DEBUG_OBJECT (ac3parse, "resyncing; checking next frame syncword");
602
603     if (more || !gst_byte_reader_skip (&reader, frmsiz) ||
604         !gst_byte_reader_get_uint16_be (&reader, &word)) {
605       GST_DEBUG_OBJECT (ac3parse, "... but not sufficient data");
606       gst_base_parse_set_min_frame_size (parse, framesize + 8);
607       *skipsize = 0;
608       goto cleanup;
609     } else {
610       if (word != 0x0b77) {
611         GST_DEBUG_OBJECT (ac3parse, "0x%x not OK", word);
612         *skipsize = off + 2;
613         goto cleanup;
614       } else {
615         /* ok, got sync now, let's assume constant frame size */
616         gst_base_parse_set_min_frame_size (parse, framesize);
617       }
618     }
619   }
620
621   /* expect to have found a frame here */
622   g_assert (framesize);
623   ret = TRUE;
624
625   /* arrange for metadata setup */
626   if (G_UNLIKELY (sid)) {
627     /* dependent frame, no need to (ac)count for or consider further */
628     GST_LOG_OBJECT (parse, "sid: %d", sid);
629     frame->flags |= GST_BASE_PARSE_FRAME_FLAG_NO_FRAME;
630     /* TODO maybe also mark as DELTA_UNIT,
631      * if that does not surprise baseparse elsewhere */
632     /* occupies same time space as previous base frame */
633     if (G_LIKELY (GST_BUFFER_TIMESTAMP (buf) >= GST_BUFFER_DURATION (buf)))
634       GST_BUFFER_TIMESTAMP (buf) -= GST_BUFFER_DURATION (buf);
635     /* only shortcut if we already arranged for caps */
636     if (G_LIKELY (ac3parse->sample_rate > 0))
637       goto cleanup;
638   }
639
640   if (G_UNLIKELY (ac3parse->sample_rate != rate || ac3parse->channels != chans
641           || ac3parse->eac != eac)) {
642     GstCaps *caps = gst_caps_new_simple (eac ? "audio/x-eac3" : "audio/x-ac3",
643         "framed", G_TYPE_BOOLEAN, TRUE, "rate", G_TYPE_INT, rate,
644         "channels", G_TYPE_INT, chans, NULL);
645     gst_caps_set_simple (caps, "alignment", G_TYPE_STRING,
646         g_atomic_int_get (&ac3parse->align) == GST_AC3_PARSE_ALIGN_IEC61937 ?
647         "iec61937" : "frame", NULL);
648     gst_pad_set_caps (GST_BASE_PARSE_SRC_PAD (parse), caps);
649     gst_caps_unref (caps);
650
651     ac3parse->sample_rate = rate;
652     ac3parse->channels = chans;
653     ac3parse->eac = eac;
654
655     update_rate = TRUE;
656   }
657
658   if (G_UNLIKELY (ac3parse->blocks != blocks)) {
659     ac3parse->blocks = blocks;
660
661     update_rate = TRUE;
662   }
663
664   if (G_UNLIKELY (update_rate))
665     gst_base_parse_set_frame_rate (parse, rate, 256 * blocks, 2, 2);
666
667 cleanup:
668   gst_buffer_unmap (buf, &map);
669
670   if (ret && framesize <= map.size) {
671     res = gst_base_parse_finish_frame (parse, frame, framesize);
672   }
673
674   return res;
675 }
676
677
678 /*
679  * MPEG-PS private1 streams add a 2 bytes "Audio Substream Headers" for each
680  * buffer (not each frame) with the offset of the next frame's start.
681  *
682  * Buffer 1:
683  * -------------------------------------------
684  * |firstAccUnit|AC3SyncWord|xxxxxxxxxxxxxxxxx
685  * -------------------------------------------
686  * Buffer 2:
687  * -------------------------------------------
688  * |firstAccUnit|xxxxxx|AC3SyncWord|xxxxxxxxxx
689  * -------------------------------------------
690  *
691  * These 2 bytes can be dropped safely as they do not include any timing
692  * information, only the offset to the start of the next frame.
693  *
694  * From http://stnsoft.com/DVD/ass-hdr.html:
695  * "FirstAccUnit offset to frame which corresponds to PTS value offset 0 is the
696  * last byte of FirstAccUnit, ie add the offset of byte 2 to get the AU's offset
697  * The value 0000 indicates there is no first access unit"
698  * */
699
700 static GstFlowReturn
701 gst_ac3_parse_chain_priv (GstPad * pad, GstObject * parent, GstBuffer * buf)
702 {
703   GstAc3Parse *ac3parse = GST_AC3_PARSE (parent);
704   GstFlowReturn ret;
705   gsize size;
706   guint8 data[2];
707   gint offset;
708   gint len;
709   GstBuffer *subbuf;
710   gint first_access;
711
712   size = gst_buffer_get_size (buf);
713   if (size < 2)
714     goto not_enough_data;
715
716   gst_buffer_extract (buf, 0, data, 2);
717   first_access = (data[0] << 8) | data[1];
718
719   /* Skip the first_access header */
720   offset = 2;
721
722   if (first_access > 1) {
723     /* Length of data before first_access */
724     len = first_access - 1;
725
726     if (len <= 0 || offset + len > size)
727       goto bad_first_access_parameter;
728
729     subbuf = gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL, offset, len);
730     GST_BUFFER_DTS (subbuf) = GST_CLOCK_TIME_NONE;
731     GST_BUFFER_PTS (subbuf) = GST_CLOCK_TIME_NONE;
732     ret = ac3parse->baseparse_chainfunc (pad, parent, subbuf);
733     if (ret != GST_FLOW_OK) {
734       gst_buffer_unref (buf);
735       goto done;
736     }
737
738     offset += len;
739     len = size - offset;
740
741     if (len > 0) {
742       subbuf = gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL, offset, len);
743       GST_BUFFER_PTS (subbuf) = GST_BUFFER_PTS (buf);
744       GST_BUFFER_DTS (subbuf) = GST_BUFFER_DTS (buf);
745
746       ret = ac3parse->baseparse_chainfunc (pad, parent, subbuf);
747     }
748     gst_buffer_unref (buf);
749   } else {
750     /* first_access = 0 or 1, so if there's a timestamp it applies to the first byte */
751     subbuf =
752         gst_buffer_copy_region (buf, GST_BUFFER_COPY_ALL, offset,
753         size - offset);
754     GST_BUFFER_PTS (subbuf) = GST_BUFFER_PTS (buf);
755     GST_BUFFER_DTS (subbuf) = GST_BUFFER_DTS (buf);
756     gst_buffer_unref (buf);
757     ret = ac3parse->baseparse_chainfunc (pad, parent, subbuf);
758   }
759
760 done:
761   return ret;
762
763 /* ERRORS */
764 not_enough_data:
765   {
766     GST_ELEMENT_ERROR (GST_ELEMENT (ac3parse), STREAM, FORMAT, (NULL),
767         ("Insufficient data in buffer. Can't determine first_acess"));
768     gst_buffer_unref (buf);
769     return GST_FLOW_ERROR;
770   }
771 bad_first_access_parameter:
772   {
773     GST_ELEMENT_ERROR (GST_ELEMENT (ac3parse), STREAM, FORMAT, (NULL),
774         ("Bad first_access parameter (%d) in buffer", first_access));
775     gst_buffer_unref (buf);
776     return GST_FLOW_ERROR;
777   }
778 }
779
780 static GstFlowReturn
781 gst_ac3_parse_pre_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
782 {
783   GstAc3Parse *ac3parse = GST_AC3_PARSE (parse);
784
785   if (!ac3parse->sent_codec_tag) {
786     GstTagList *taglist;
787     GstCaps *caps;
788
789     taglist = gst_tag_list_new_empty ();
790
791     /* codec tag */
792     caps = gst_pad_get_current_caps (GST_BASE_PARSE_SRC_PAD (parse));
793     gst_pb_utils_add_codec_description_to_tag_list (taglist,
794         GST_TAG_AUDIO_CODEC, caps);
795     gst_caps_unref (caps);
796
797     gst_base_parse_merge_tags (parse, taglist, GST_TAG_MERGE_REPLACE);
798     gst_tag_list_unref (taglist);
799
800     /* also signals the end of first-frame processing */
801     ac3parse->sent_codec_tag = TRUE;
802   }
803
804   return GST_FLOW_OK;
805 }
806
807 static gboolean
808 gst_ac3_parse_src_event (GstBaseParse * parse, GstEvent * event)
809 {
810   GstAc3Parse *ac3parse = GST_AC3_PARSE (parse);
811
812   if (G_UNLIKELY (GST_EVENT_TYPE (event) == GST_EVENT_CUSTOM_UPSTREAM) &&
813       gst_event_has_name (event, "ac3parse-set-alignment")) {
814     const GstStructure *st = gst_event_get_structure (event);
815     const gchar *align = gst_structure_get_string (st, "alignment");
816
817     if (g_str_equal (align, "iec61937")) {
818       GST_DEBUG_OBJECT (ac3parse, "Switching to iec61937 alignment");
819       g_atomic_int_set (&ac3parse->align, GST_AC3_PARSE_ALIGN_IEC61937);
820     } else if (g_str_equal (align, "frame")) {
821       GST_DEBUG_OBJECT (ac3parse, "Switching to frame alignment");
822       g_atomic_int_set (&ac3parse->align, GST_AC3_PARSE_ALIGN_FRAME);
823     } else {
824       g_atomic_int_set (&ac3parse->align, GST_AC3_PARSE_ALIGN_FRAME);
825       GST_WARNING_OBJECT (ac3parse, "Got unknown alignment request (%s) "
826           "reverting to frame alignment.",
827           gst_structure_get_string (st, "alignment"));
828     }
829
830     gst_event_unref (event);
831     return TRUE;
832   }
833
834   return GST_BASE_PARSE_CLASS (parent_class)->src_event (parse, event);
835 }
836
837 static void
838 remove_fields (GstCaps * caps)
839 {
840   guint i, n;
841
842   n = gst_caps_get_size (caps);
843   for (i = 0; i < n; i++) {
844     GstStructure *s = gst_caps_get_structure (caps, i);
845
846     gst_structure_remove_field (s, "framed");
847     gst_structure_remove_field (s, "alignment");
848   }
849 }
850
851 static GstCaps *
852 extend_caps (GstCaps * caps, gboolean add_private)
853 {
854   guint i, n;
855   GstCaps *ncaps = gst_caps_new_empty ();
856
857   n = gst_caps_get_size (caps);
858   for (i = 0; i < n; i++) {
859     GstStructure *s = gst_caps_get_structure (caps, i);
860
861     if (add_private && !gst_structure_has_name (s, "audio/x-private1-ac3")) {
862       GstStructure *ns = gst_structure_copy (s);
863       gst_structure_set_name (ns, "audio/x-private1-ac3");
864       gst_caps_append_structure (ncaps, ns);
865     } else if (!add_private &&
866         gst_structure_has_name (s, "audio/x-private1-ac3")) {
867       GstStructure *ns = gst_structure_copy (s);
868       gst_structure_set_name (ns, "audio/x-ac3");
869       gst_caps_append_structure (ncaps, ns);
870       ns = gst_structure_copy (s);
871       gst_structure_set_name (ns, "audio/x-eac3");
872       gst_caps_append_structure (ncaps, ns);
873     } else if (!add_private) {
874       gst_caps_append_structure (ncaps, gst_structure_copy (s));
875     }
876   }
877
878   if (add_private) {
879     gst_caps_append (caps, ncaps);
880   } else {
881     gst_caps_unref (caps);
882     caps = ncaps;
883   }
884
885   return caps;
886 }
887
888 static GstCaps *
889 gst_ac3_parse_get_sink_caps (GstBaseParse * parse, GstCaps * filter)
890 {
891   GstCaps *peercaps, *templ;
892   GstCaps *res;
893
894   templ = gst_pad_get_pad_template_caps (GST_BASE_PARSE_SINK_PAD (parse));
895   if (filter) {
896     GstCaps *fcopy = gst_caps_copy (filter);
897     /* Remove the fields we convert */
898     remove_fields (fcopy);
899     /* we do not ask downstream to handle x-private1-ac3 */
900     fcopy = extend_caps (fcopy, FALSE);
901     peercaps = gst_pad_peer_query_caps (GST_BASE_PARSE_SRC_PAD (parse), fcopy);
902     gst_caps_unref (fcopy);
903   } else
904     peercaps = gst_pad_peer_query_caps (GST_BASE_PARSE_SRC_PAD (parse), NULL);
905
906   if (peercaps) {
907     /* Remove the framed and alignment field. We can convert
908      * between different alignments. */
909     peercaps = gst_caps_make_writable (peercaps);
910     remove_fields (peercaps);
911     /* also allow for x-private1-ac3 input */
912     peercaps = extend_caps (peercaps, TRUE);
913
914     res = gst_caps_intersect_full (peercaps, templ, GST_CAPS_INTERSECT_FIRST);
915     gst_caps_unref (peercaps);
916     gst_caps_unref (templ);
917   } else {
918     res = templ;
919   }
920
921   if (filter) {
922     GstCaps *intersection;
923
924     intersection =
925         gst_caps_intersect_full (filter, res, GST_CAPS_INTERSECT_FIRST);
926     gst_caps_unref (res);
927     res = intersection;
928   }
929
930   return res;
931 }
932
933 static gboolean
934 gst_ac3_parse_set_sink_caps (GstBaseParse * parse, GstCaps * caps)
935 {
936   GstStructure *s;
937   GstAc3Parse *ac3parse = GST_AC3_PARSE (parse);
938
939   s = gst_caps_get_structure (caps, 0);
940   if (gst_structure_has_name (s, "audio/x-private1-ac3")) {
941     gst_pad_set_chain_function (parse->sinkpad, gst_ac3_parse_chain_priv);
942   } else {
943     gst_pad_set_chain_function (parse->sinkpad, ac3parse->baseparse_chainfunc);
944   }
945   return TRUE;
946 }