aacparse: fix object_type parsing off-by-one in ADTS frame
[platform/upstream/gst-plugins-good.git] / gst / audioparsers / gstaacparse.c
1 /* GStreamer AAC parser plugin
2  * Copyright (C) 2008 Nokia Corporation. All rights reserved.
3  *
4  * Contact: Stefan Kost <stefan.kost@nokia.com>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21
22 /**
23  * SECTION:element-aacparse
24  * @short_description: AAC parser
25  * @see_also: #GstAmrParse
26  *
27  * This is an AAC parser which handles both ADIF and ADTS stream formats.
28  *
29  * As ADIF format is not framed, it is not seekable and stream duration cannot
30  * be determined either. However, ADTS format AAC clips can be seeked, and parser
31  * can also estimate playback position and clip duration.
32  *
33  * <refsect2>
34  * <title>Example launch line</title>
35  * |[
36  * gst-launch-1.0 filesrc location=abc.aac ! aacparse ! faad ! audioresample ! audioconvert ! alsasink
37  * ]|
38  * </refsect2>
39  */
40
41 #ifdef HAVE_CONFIG_H
42 #include "config.h"
43 #endif
44
45 #include <string.h>
46
47 #include <gst/base/gstbitreader.h>
48 #include "gstaacparse.h"
49
50
51 static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
52     GST_PAD_SRC,
53     GST_PAD_ALWAYS,
54     GST_STATIC_CAPS ("audio/mpeg, "
55         "framed = (boolean) true, " "mpegversion = (int) { 2, 4 }, "
56         "stream-format = (string) { raw, adts, adif, loas };"));
57
58 static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
59     GST_PAD_SINK,
60     GST_PAD_ALWAYS,
61     GST_STATIC_CAPS ("audio/mpeg, mpegversion = (int) { 2, 4 };"));
62
63 GST_DEBUG_CATEGORY_STATIC (aacparse_debug);
64 #define GST_CAT_DEFAULT aacparse_debug
65
66
67 #define ADIF_MAX_SIZE 40        /* Should be enough */
68 #define ADTS_MAX_SIZE 10        /* Should be enough */
69 #define LOAS_MAX_SIZE 3         /* Should be enough */
70
71
72 #define AAC_FRAME_DURATION(parse) (GST_SECOND/parse->frames_per_sec)
73
74 static const gint loas_sample_rate_table[32] = {
75   96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
76   16000, 12000, 11025, 8000, 7350, 0, 0, 0
77 };
78
79 static const gint loas_channels_table[32] = {
80   0, 1, 2, 3, 4, 5, 6, 8,
81   0, 0, 0, 0, 0, 0, 0, 0
82 };
83
84 static gboolean gst_aac_parse_start (GstBaseParse * parse);
85 static gboolean gst_aac_parse_stop (GstBaseParse * parse);
86
87 static gboolean gst_aac_parse_sink_setcaps (GstBaseParse * parse,
88     GstCaps * caps);
89 static GstCaps *gst_aac_parse_sink_getcaps (GstBaseParse * parse,
90     GstCaps * filter);
91
92 static GstFlowReturn gst_aac_parse_handle_frame (GstBaseParse * parse,
93     GstBaseParseFrame * frame, gint * skipsize);
94
95 G_DEFINE_TYPE (GstAacParse, gst_aac_parse, GST_TYPE_BASE_PARSE);
96
97 static inline gint
98 gst_aac_parse_get_sample_rate_from_index (guint sr_idx)
99 {
100   static const guint aac_sample_rates[] = { 96000, 88200, 64000, 48000, 44100,
101     32000, 24000, 22050, 16000, 12000, 11025, 8000
102   };
103
104   if (sr_idx < G_N_ELEMENTS (aac_sample_rates))
105     return aac_sample_rates[sr_idx];
106   GST_WARNING ("Invalid sample rate index %u", sr_idx);
107   return 0;
108 }
109
110 /**
111  * gst_aac_parse_class_init:
112  * @klass: #GstAacParseClass.
113  *
114  */
115 static void
116 gst_aac_parse_class_init (GstAacParseClass * klass)
117 {
118   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
119   GstBaseParseClass *parse_class = GST_BASE_PARSE_CLASS (klass);
120
121   GST_DEBUG_CATEGORY_INIT (aacparse_debug, "aacparse", 0,
122       "AAC audio stream parser");
123
124   gst_element_class_add_pad_template (element_class,
125       gst_static_pad_template_get (&sink_template));
126   gst_element_class_add_pad_template (element_class,
127       gst_static_pad_template_get (&src_template));
128
129   gst_element_class_set_static_metadata (element_class,
130       "AAC audio stream parser", "Codec/Parser/Audio",
131       "Advanced Audio Coding parser", "Stefan Kost <stefan.kost@nokia.com>");
132
133   parse_class->start = GST_DEBUG_FUNCPTR (gst_aac_parse_start);
134   parse_class->stop = GST_DEBUG_FUNCPTR (gst_aac_parse_stop);
135   parse_class->set_sink_caps = GST_DEBUG_FUNCPTR (gst_aac_parse_sink_setcaps);
136   parse_class->get_sink_caps = GST_DEBUG_FUNCPTR (gst_aac_parse_sink_getcaps);
137   parse_class->handle_frame = GST_DEBUG_FUNCPTR (gst_aac_parse_handle_frame);
138 }
139
140
141 /**
142  * gst_aac_parse_init:
143  * @aacparse: #GstAacParse.
144  * @klass: #GstAacParseClass.
145  *
146  */
147 static void
148 gst_aac_parse_init (GstAacParse * aacparse)
149 {
150   GST_DEBUG ("initialized");
151 }
152
153
154 /**
155  * gst_aac_parse_set_src_caps:
156  * @aacparse: #GstAacParse.
157  * @sink_caps: (proposed) caps of sink pad
158  *
159  * Set source pad caps according to current knowledge about the
160  * audio stream.
161  *
162  * Returns: TRUE if caps were successfully set.
163  */
164 static gboolean
165 gst_aac_parse_set_src_caps (GstAacParse * aacparse, GstCaps * sink_caps)
166 {
167   GstStructure *s;
168   GstCaps *src_caps = NULL;
169   gboolean res = FALSE;
170   const gchar *stream_format;
171
172   GST_DEBUG_OBJECT (aacparse, "sink caps: %" GST_PTR_FORMAT, sink_caps);
173   if (sink_caps)
174     src_caps = gst_caps_copy (sink_caps);
175   else
176     src_caps = gst_caps_new_empty_simple ("audio/mpeg");
177
178   gst_caps_set_simple (src_caps, "framed", G_TYPE_BOOLEAN, TRUE,
179       "mpegversion", G_TYPE_INT, aacparse->mpegversion, NULL);
180
181   switch (aacparse->header_type) {
182     case DSPAAC_HEADER_NONE:
183       stream_format = "raw";
184       break;
185     case DSPAAC_HEADER_ADTS:
186       stream_format = "adts";
187       break;
188     case DSPAAC_HEADER_ADIF:
189       stream_format = "adif";
190       break;
191     case DSPAAC_HEADER_LOAS:
192       stream_format = "loas";
193       break;
194     default:
195       stream_format = NULL;
196   }
197
198   s = gst_caps_get_structure (src_caps, 0);
199   if (aacparse->sample_rate > 0)
200     gst_structure_set (s, "rate", G_TYPE_INT, aacparse->sample_rate, NULL);
201   if (aacparse->channels > 0)
202     gst_structure_set (s, "channels", G_TYPE_INT, aacparse->channels, NULL);
203   if (stream_format)
204     gst_structure_set (s, "stream-format", G_TYPE_STRING, stream_format, NULL);
205
206   GST_DEBUG_OBJECT (aacparse, "setting src caps: %" GST_PTR_FORMAT, src_caps);
207
208   res = gst_pad_set_caps (GST_BASE_PARSE (aacparse)->srcpad, src_caps);
209   gst_caps_unref (src_caps);
210   return res;
211 }
212
213
214 /**
215  * gst_aac_parse_sink_setcaps:
216  * @sinkpad: GstPad
217  * @caps: GstCaps
218  *
219  * Implementation of "set_sink_caps" vmethod in #GstBaseParse class.
220  *
221  * Returns: TRUE on success.
222  */
223 static gboolean
224 gst_aac_parse_sink_setcaps (GstBaseParse * parse, GstCaps * caps)
225 {
226   GstAacParse *aacparse;
227   GstStructure *structure;
228   gchar *caps_str;
229   const GValue *value;
230
231   aacparse = GST_AAC_PARSE (parse);
232   structure = gst_caps_get_structure (caps, 0);
233   caps_str = gst_caps_to_string (caps);
234
235   GST_DEBUG_OBJECT (aacparse, "setcaps: %s", caps_str);
236   g_free (caps_str);
237
238   /* This is needed at least in case of RTP
239    * Parses the codec_data information to get ObjectType,
240    * number of channels and samplerate */
241   value = gst_structure_get_value (structure, "codec_data");
242   if (value) {
243     GstBuffer *buf = gst_value_get_buffer (value);
244
245     if (buf) {
246       GstMapInfo map;
247       guint sr_idx;
248
249       gst_buffer_map (buf, &map, GST_MAP_READ);
250
251       sr_idx = ((map.data[0] & 0x07) << 1) | ((map.data[1] & 0x80) >> 7);
252       aacparse->object_type = (map.data[0] & 0xf8) >> 3;
253       aacparse->sample_rate = gst_aac_parse_get_sample_rate_from_index (sr_idx);
254       aacparse->channels = (map.data[1] & 0x78) >> 3;
255       aacparse->header_type = DSPAAC_HEADER_NONE;
256       aacparse->mpegversion = 4;
257       aacparse->frame_samples = (map.data[1] & 4) ? 960 : 1024;
258       gst_buffer_unmap (buf, &map);
259
260       GST_DEBUG ("codec_data: object_type=%d, sample_rate=%d, channels=%d, "
261           "samples=%d", aacparse->object_type, aacparse->sample_rate,
262           aacparse->channels, aacparse->frame_samples);
263
264       /* arrange for metadata and get out of the way */
265       gst_aac_parse_set_src_caps (aacparse, caps);
266       gst_base_parse_set_passthrough (parse, TRUE);
267     } else
268       return FALSE;
269
270     /* caps info overrides */
271     gst_structure_get_int (structure, "rate", &aacparse->sample_rate);
272     gst_structure_get_int (structure, "channels", &aacparse->channels);
273   } else {
274     aacparse->sample_rate = 0;
275     aacparse->channels = 0;
276     aacparse->header_type = DSPAAC_HEADER_NOT_PARSED;
277     gst_base_parse_set_passthrough (parse, FALSE);
278   }
279
280   return TRUE;
281 }
282
283
284 /**
285  * gst_aac_parse_adts_get_frame_len:
286  * @data: block of data containing an ADTS header.
287  *
288  * This function calculates ADTS frame length from the given header.
289  *
290  * Returns: size of the ADTS frame.
291  */
292 static inline guint
293 gst_aac_parse_adts_get_frame_len (const guint8 * data)
294 {
295   return ((data[3] & 0x03) << 11) | (data[4] << 3) | ((data[5] & 0xe0) >> 5);
296 }
297
298
299 /**
300  * gst_aac_parse_check_adts_frame:
301  * @aacparse: #GstAacParse.
302  * @data: Data to be checked.
303  * @avail: Amount of data passed.
304  * @framesize: If valid ADTS frame was found, this will be set to tell the
305  *             found frame size in bytes.
306  * @needed_data: If frame was not found, this may be set to tell how much
307  *               more data is needed in the next round to detect the frame
308  *               reliably. This may happen when a frame header candidate
309  *               is found but it cannot be guaranteed to be the header without
310  *               peeking the following data.
311  *
312  * Check if the given data contains contains ADTS frame. The algorithm
313  * will examine ADTS frame header and calculate the frame size. Also, another
314  * consecutive ADTS frame header need to be present after the found frame.
315  * Otherwise the data is not considered as a valid ADTS frame. However, this
316  * "extra check" is omitted when EOS has been received. In this case it is
317  * enough when data[0] contains a valid ADTS header.
318  *
319  * This function may set the #needed_data to indicate that a possible frame
320  * candidate has been found, but more data (#needed_data bytes) is needed to
321  * be absolutely sure. When this situation occurs, FALSE will be returned.
322  *
323  * When a valid frame is detected, this function will use
324  * gst_base_parse_set_min_frame_size() function from #GstBaseParse class
325  * to set the needed bytes for next frame.This way next data chunk is already
326  * of correct size.
327  *
328  * Returns: TRUE if the given data contains a valid ADTS header.
329  */
330 static gboolean
331 gst_aac_parse_check_adts_frame (GstAacParse * aacparse,
332     const guint8 * data, const guint avail, gboolean drain,
333     guint * framesize, guint * needed_data)
334 {
335   *needed_data = 0;
336
337   if (G_UNLIKELY (avail < 2))
338     return FALSE;
339
340   if ((data[0] == 0xff) && ((data[1] & 0xf6) == 0xf0)) {
341     *framesize = gst_aac_parse_adts_get_frame_len (data);
342
343     /* In EOS mode this is enough. No need to examine the data further.
344        We also relax the check when we have sync, on the assumption that
345        if we're not looking at random data, we have a much higher chance
346        to get the correct sync, and this avoids losing two frames when
347        a single bit corruption happens. */
348     if (drain || !GST_BASE_PARSE_LOST_SYNC (aacparse)) {
349       return TRUE;
350     }
351
352     if (*framesize + ADTS_MAX_SIZE > avail) {
353       /* We have found a possible frame header candidate, but can't be
354          sure since we don't have enough data to check the next frame */
355       GST_DEBUG ("NEED MORE DATA: we need %d, available %d",
356           *framesize + ADTS_MAX_SIZE, avail);
357       *needed_data = *framesize + ADTS_MAX_SIZE;
358       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
359           *framesize + ADTS_MAX_SIZE);
360       return FALSE;
361     }
362
363     if ((data[*framesize] == 0xff) && ((data[*framesize + 1] & 0xf6) == 0xf0)) {
364       guint nextlen = gst_aac_parse_adts_get_frame_len (data + (*framesize));
365
366       GST_LOG ("ADTS frame found, len: %d bytes", *framesize);
367       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
368           nextlen + ADTS_MAX_SIZE);
369       return TRUE;
370     }
371   }
372   return FALSE;
373 }
374
375 static gboolean
376 gst_aac_parse_latm_get_value (GstAacParse * aacparse, GstBitReader * br,
377     guint32 * value)
378 {
379   guint8 bytes, i, byte;
380
381   *value = 0;
382   if (!gst_bit_reader_get_bits_uint8 (br, &bytes, 2))
383     return FALSE;
384   for (i = 0; i < bytes; ++i) {
385     *value <<= 8;
386     if (!gst_bit_reader_get_bits_uint8 (br, &byte, 8))
387       return FALSE;
388     *value += byte;
389   }
390   return TRUE;
391 }
392
393 static gboolean
394 gst_aac_parse_get_audio_object_type (GstAacParse * aacparse, GstBitReader * br,
395     guint8 * audio_object_type)
396 {
397   if (!gst_bit_reader_get_bits_uint8 (br, audio_object_type, 5))
398     return FALSE;
399   if (*audio_object_type == 31) {
400     if (!gst_bit_reader_get_bits_uint8 (br, audio_object_type, 6))
401       return FALSE;
402     *audio_object_type += 32;
403   }
404   GST_LOG_OBJECT (aacparse, "audio object type %u", *audio_object_type);
405   return TRUE;
406 }
407
408 static gboolean
409 gst_aac_parse_get_audio_sample_rate (GstAacParse * aacparse, GstBitReader * br,
410     gint * sample_rate)
411 {
412   guint8 sampling_frequency_index;
413   if (!gst_bit_reader_get_bits_uint8 (br, &sampling_frequency_index, 4))
414     return FALSE;
415   GST_LOG_OBJECT (aacparse, "sampling_frequency_index: %u",
416       sampling_frequency_index);
417   if (sampling_frequency_index == 0xf) {
418     guint32 sampling_rate;
419     if (!gst_bit_reader_get_bits_uint32 (br, &sampling_rate, 24))
420       return FALSE;
421     *sample_rate = sampling_rate;
422   } else {
423     *sample_rate = loas_sample_rate_table[sampling_frequency_index];
424     if (!*sample_rate)
425       return FALSE;
426   }
427   return TRUE;
428 }
429
430 /* See table 1.13 in ISO/IEC 14496-3 */
431 static gboolean
432 gst_aac_parse_read_loas_audio_specific_config (GstAacParse * aacparse,
433     GstBitReader * br, gint * sample_rate, gint * channels, guint32 * bits)
434 {
435   guint8 audio_object_type, channel_configuration;
436
437   if (!gst_aac_parse_get_audio_object_type (aacparse, br, &audio_object_type))
438     return FALSE;
439
440   if (!gst_aac_parse_get_audio_sample_rate (aacparse, br, sample_rate))
441     return FALSE;
442
443   if (!gst_bit_reader_get_bits_uint8 (br, &channel_configuration, 4))
444     return FALSE;
445   GST_LOG_OBJECT (aacparse, "channel_configuration: %d", channel_configuration);
446   *channels = loas_channels_table[channel_configuration];
447   if (!*channels)
448     return FALSE;
449
450   if (audio_object_type == 5) {
451     GST_LOG_OBJECT (aacparse,
452         "Audio object type 5, so rereading sampling rate...");
453     if (!gst_aac_parse_get_audio_sample_rate (aacparse, br, sample_rate))
454       return FALSE;
455   }
456
457   GST_INFO_OBJECT (aacparse, "Found LOAS config: %d Hz, %d channels",
458       *sample_rate, *channels);
459
460   /* There's LOTS of stuff next, but we ignore it for now as we have
461      what we want (sample rate and number of channels */
462   GST_DEBUG_OBJECT (aacparse,
463       "Need more code to parse humongous LOAS data, currently ignored");
464   if (bits)
465     *bits = 0;
466   return TRUE;
467 }
468
469
470 static gboolean
471 gst_aac_parse_read_loas_config (GstAacParse * aacparse, const guint8 * data,
472     guint avail, gint * sample_rate, gint * channels, gint * version)
473 {
474   GstBitReader br;
475   guint8 u8, v, vA;
476
477   /* No version in the bitstream, but the spec has LOAS in the MPEG-4 section */
478   if (version)
479     *version = 4;
480
481   gst_bit_reader_init (&br, data, avail);
482
483   /* skip sync word (11 bits) and size (13 bits) */
484   if (!gst_bit_reader_skip (&br, 11 + 13))
485     return FALSE;
486
487   /* First bit is "use last config" */
488   if (!gst_bit_reader_get_bits_uint8 (&br, &u8, 1))
489     return FALSE;
490   if (u8) {
491     GST_DEBUG_OBJECT (aacparse, "Frame uses previous config");
492     if (!aacparse->sample_rate || !aacparse->channels) {
493       GST_WARNING_OBJECT (aacparse, "No previous config to use");
494     }
495     *sample_rate = aacparse->sample_rate;
496     *channels = aacparse->channels;
497     return TRUE;
498   }
499
500   GST_DEBUG_OBJECT (aacparse, "Frame contains new config");
501
502   if (!gst_bit_reader_get_bits_uint8 (&br, &v, 1))
503     return FALSE;
504   if (v) {
505     if (!gst_bit_reader_get_bits_uint8 (&br, &vA, 1))
506       return FALSE;
507   } else
508     vA = 0;
509
510   GST_LOG_OBJECT (aacparse, "v %d, vA %d", v, vA);
511   if (vA == 0) {
512     guint8 same_time, subframes, num_program, prog;
513     if (v == 1) {
514       guint32 value;
515       if (!gst_aac_parse_latm_get_value (aacparse, &br, &value))
516         return FALSE;
517     }
518     if (!gst_bit_reader_get_bits_uint8 (&br, &same_time, 1))
519       return FALSE;
520     if (!gst_bit_reader_get_bits_uint8 (&br, &subframes, 6))
521       return FALSE;
522     if (!gst_bit_reader_get_bits_uint8 (&br, &num_program, 4))
523       return FALSE;
524     GST_LOG_OBJECT (aacparse, "same_time %d, subframes %d, num_program %d",
525         same_time, subframes, num_program);
526
527     for (prog = 0; prog <= num_program; ++prog) {
528       guint8 num_layer, layer;
529       if (!gst_bit_reader_get_bits_uint8 (&br, &num_layer, 3))
530         return FALSE;
531       GST_LOG_OBJECT (aacparse, "Program %d: %d layers", prog, num_layer);
532
533       for (layer = 0; layer <= num_layer; ++layer) {
534         guint8 use_same_config;
535         if (prog == 0 && layer == 0) {
536           use_same_config = 0;
537         } else {
538           if (!gst_bit_reader_get_bits_uint8 (&br, &use_same_config, 1))
539             return FALSE;
540         }
541         if (!use_same_config) {
542           if (v == 0) {
543             if (!gst_aac_parse_read_loas_audio_specific_config (aacparse, &br,
544                     sample_rate, channels, NULL))
545               return FALSE;
546           } else {
547             guint32 bits, asc_len;
548             if (!gst_aac_parse_latm_get_value (aacparse, &br, &asc_len))
549               return FALSE;
550             if (!gst_aac_parse_read_loas_audio_specific_config (aacparse, &br,
551                     sample_rate, channels, &bits))
552               return FALSE;
553             asc_len -= bits;
554             if (!gst_bit_reader_skip (&br, asc_len))
555               return FALSE;
556           }
557         }
558       }
559     }
560     GST_LOG_OBJECT (aacparse, "More data ignored");
561   } else {
562     GST_WARNING_OBJECT (aacparse, "Spec says \"TBD\"...");
563   }
564   return TRUE;
565 }
566
567 /**
568  * gst_aac_parse_loas_get_frame_len:
569  * @data: block of data containing a LOAS header.
570  *
571  * This function calculates LOAS frame length from the given header.
572  *
573  * Returns: size of the LOAS frame.
574  */
575 static inline guint
576 gst_aac_parse_loas_get_frame_len (const guint8 * data)
577 {
578   return (((data[1] & 0x1f) << 8) | data[2]) + 3;
579 }
580
581
582 /**
583  * gst_aac_parse_check_loas_frame:
584  * @aacparse: #GstAacParse.
585  * @data: Data to be checked.
586  * @avail: Amount of data passed.
587  * @framesize: If valid LOAS frame was found, this will be set to tell the
588  *             found frame size in bytes.
589  * @needed_data: If frame was not found, this may be set to tell how much
590  *               more data is needed in the next round to detect the frame
591  *               reliably. This may happen when a frame header candidate
592  *               is found but it cannot be guaranteed to be the header without
593  *               peeking the following data.
594  *
595  * Check if the given data contains contains LOAS frame. The algorithm
596  * will examine LOAS frame header and calculate the frame size. Also, another
597  * consecutive LOAS frame header need to be present after the found frame.
598  * Otherwise the data is not considered as a valid LOAS frame. However, this
599  * "extra check" is omitted when EOS has been received. In this case it is
600  * enough when data[0] contains a valid LOAS header.
601  *
602  * This function may set the #needed_data to indicate that a possible frame
603  * candidate has been found, but more data (#needed_data bytes) is needed to
604  * be absolutely sure. When this situation occurs, FALSE will be returned.
605  *
606  * When a valid frame is detected, this function will use
607  * gst_base_parse_set_min_frame_size() function from #GstBaseParse class
608  * to set the needed bytes for next frame.This way next data chunk is already
609  * of correct size.
610  *
611  * LOAS can have three different formats, if I read the spec correctly. Only
612  * one of them is supported here, as the two samples I have use this one.
613  *
614  * Returns: TRUE if the given data contains a valid LOAS header.
615  */
616 static gboolean
617 gst_aac_parse_check_loas_frame (GstAacParse * aacparse,
618     const guint8 * data, const guint avail, gboolean drain,
619     guint * framesize, guint * needed_data)
620 {
621   *needed_data = 0;
622
623   /* 3 byte header */
624   if (G_UNLIKELY (avail < 3))
625     return FALSE;
626
627   if ((data[0] == 0x56) && ((data[1] & 0xe0) == 0xe0)) {
628     *framesize = gst_aac_parse_loas_get_frame_len (data);
629     GST_DEBUG_OBJECT (aacparse, "Found %u byte LOAS frame", *framesize);
630
631     /* In EOS mode this is enough. No need to examine the data further.
632        We also relax the check when we have sync, on the assumption that
633        if we're not looking at random data, we have a much higher chance
634        to get the correct sync, and this avoids losing two frames when
635        a single bit corruption happens. */
636     if (drain || !GST_BASE_PARSE_LOST_SYNC (aacparse)) {
637       return TRUE;
638     }
639
640     if (*framesize + LOAS_MAX_SIZE > avail) {
641       /* We have found a possible frame header candidate, but can't be
642          sure since we don't have enough data to check the next frame */
643       GST_DEBUG ("NEED MORE DATA: we need %d, available %d",
644           *framesize + LOAS_MAX_SIZE, avail);
645       *needed_data = *framesize + LOAS_MAX_SIZE;
646       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
647           *framesize + LOAS_MAX_SIZE);
648       return FALSE;
649     }
650
651     if ((data[*framesize] == 0x56) && ((data[*framesize + 1] & 0xe0) == 0xe0)) {
652       guint nextlen = gst_aac_parse_loas_get_frame_len (data + (*framesize));
653
654       GST_LOG ("LOAS frame found, len: %d bytes", *framesize);
655       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
656           nextlen + LOAS_MAX_SIZE);
657       return TRUE;
658     }
659   }
660   return FALSE;
661 }
662
663 /* caller ensure sufficient data */
664 static inline void
665 gst_aac_parse_parse_adts_header (GstAacParse * aacparse, const guint8 * data,
666     gint * rate, gint * channels, gint * object, gint * version)
667 {
668
669   if (rate) {
670     gint sr_idx = (data[2] & 0x3c) >> 2;
671
672     *rate = gst_aac_parse_get_sample_rate_from_index (sr_idx);
673   }
674   if (channels)
675     *channels = ((data[2] & 0x01) << 2) | ((data[3] & 0xc0) >> 6);
676
677   if (version)
678     *version = (data[1] & 0x08) ? 2 : 4;
679   if (object)
680     *object = ((data[2] & 0xc0) >> 6) + 1;
681 }
682
683 /**
684  * gst_aac_parse_detect_stream:
685  * @aacparse: #GstAacParse.
686  * @data: A block of data that needs to be examined for stream characteristics.
687  * @avail: Size of the given datablock.
688  * @framesize: If valid stream was found, this will be set to tell the
689  *             first frame size in bytes.
690  * @skipsize: If valid stream was found, this will be set to tell the first
691  *            audio frame position within the given data.
692  *
693  * Examines the given piece of data and try to detect the format of it. It
694  * checks for "ADIF" header (in the beginning of the clip) and ADTS frame
695  * header. If the stream is detected, TRUE will be returned and #framesize
696  * is set to indicate the found frame size. Additionally, #skipsize might
697  * be set to indicate the number of bytes that need to be skipped, a.k.a. the
698  * position of the frame inside given data chunk.
699  *
700  * Returns: TRUE on success.
701  */
702 static gboolean
703 gst_aac_parse_detect_stream (GstAacParse * aacparse,
704     const guint8 * data, const guint avail, gboolean drain,
705     guint * framesize, gint * skipsize)
706 {
707   gboolean found = FALSE;
708   guint need_data_adts = 0, need_data_loas;
709   guint i = 0;
710
711   GST_DEBUG_OBJECT (aacparse, "Parsing header data");
712
713   /* FIXME: No need to check for ADIF if we are not in the beginning of the
714      stream */
715
716   /* Can we even parse the header? */
717   if (avail < MAX (ADTS_MAX_SIZE, LOAS_MAX_SIZE)) {
718     GST_DEBUG_OBJECT (aacparse, "Not enough data to check");
719     return FALSE;
720   }
721
722   for (i = 0; i < avail - 4; i++) {
723     if (((data[i] == 0xff) && ((data[i + 1] & 0xf6) == 0xf0)) ||
724         ((data[0] == 0x56) && ((data[1] & 0xe0) == 0xe0)) ||
725         strncmp ((char *) data + i, "ADIF", 4) == 0) {
726       GST_DEBUG_OBJECT (aacparse, "Found signature at offset %u", i);
727       found = TRUE;
728
729       if (i) {
730         /* Trick: tell the parent class that we didn't find the frame yet,
731            but make it skip 'i' amount of bytes. Next time we arrive
732            here we have full frame in the beginning of the data. */
733         *skipsize = i;
734         return FALSE;
735       }
736       break;
737     }
738   }
739   if (!found) {
740     if (i)
741       *skipsize = i;
742     return FALSE;
743   }
744
745   if (gst_aac_parse_check_adts_frame (aacparse, data, avail, drain,
746           framesize, &need_data_adts)) {
747     gint rate, channels;
748
749     GST_INFO ("ADTS ID: %d, framesize: %d", (data[1] & 0x08) >> 3, *framesize);
750
751     gst_aac_parse_parse_adts_header (aacparse, data, &rate, &channels,
752         &aacparse->object_type, &aacparse->mpegversion);
753
754     if (!channels || !framesize) {
755       GST_DEBUG_OBJECT (aacparse, "impossible ADTS configuration");
756       return FALSE;
757     }
758
759     aacparse->header_type = DSPAAC_HEADER_ADTS;
760     gst_base_parse_set_frame_rate (GST_BASE_PARSE (aacparse), rate,
761         aacparse->frame_samples, 2, 2);
762
763     GST_DEBUG ("ADTS: samplerate %d, channels %d, objtype %d, version %d",
764         rate, channels, aacparse->object_type, aacparse->mpegversion);
765
766     gst_base_parse_set_syncable (GST_BASE_PARSE (aacparse), TRUE);
767
768     return TRUE;
769   }
770
771   if (gst_aac_parse_check_loas_frame (aacparse, data, avail, drain,
772           framesize, &need_data_loas)) {
773     gint rate, channels;
774
775     GST_INFO ("LOAS, framesize: %d", *framesize);
776
777     aacparse->header_type = DSPAAC_HEADER_LOAS;
778
779     if (!gst_aac_parse_read_loas_config (aacparse, data, avail, &rate,
780             &channels, &aacparse->mpegversion)) {
781       GST_WARNING_OBJECT (aacparse, "Error reading LOAS config");
782       return FALSE;
783     }
784
785     if (rate && channels) {
786       gst_base_parse_set_frame_rate (GST_BASE_PARSE (aacparse), rate,
787           aacparse->frame_samples, 2, 2);
788
789       GST_DEBUG ("LOAS: samplerate %d, channels %d, objtype %d, version %d",
790           rate, channels, aacparse->object_type, aacparse->mpegversion);
791       aacparse->sample_rate = rate;
792       aacparse->channels = channels;
793     }
794
795     gst_base_parse_set_syncable (GST_BASE_PARSE (aacparse), TRUE);
796
797     return TRUE;
798   }
799
800   if (need_data_adts || need_data_loas) {
801     /* This tells the parent class not to skip any data */
802     *skipsize = 0;
803     return FALSE;
804   }
805
806   if (avail < ADIF_MAX_SIZE)
807     return FALSE;
808
809   if (memcmp (data + i, "ADIF", 4) == 0) {
810     const guint8 *adif;
811     int skip_size = 0;
812     int bitstream_type;
813     int sr_idx;
814     GstCaps *sinkcaps;
815
816     aacparse->header_type = DSPAAC_HEADER_ADIF;
817     aacparse->mpegversion = 4;
818
819     /* Skip the "ADIF" bytes */
820     adif = data + i + 4;
821
822     /* copyright string */
823     if (adif[0] & 0x80)
824       skip_size += 9;           /* skip 9 bytes */
825
826     bitstream_type = adif[0 + skip_size] & 0x10;
827     aacparse->bitrate =
828         ((unsigned int) (adif[0 + skip_size] & 0x0f) << 19) |
829         ((unsigned int) adif[1 + skip_size] << 11) |
830         ((unsigned int) adif[2 + skip_size] << 3) |
831         ((unsigned int) adif[3 + skip_size] & 0xe0);
832
833     /* CBR */
834     if (bitstream_type == 0) {
835 #if 0
836       /* Buffer fullness parsing. Currently not needed... */
837       guint num_elems = 0;
838       guint fullness = 0;
839
840       num_elems = (adif[3 + skip_size] & 0x1e);
841       GST_INFO ("ADIF num_config_elems: %d", num_elems);
842
843       fullness = ((unsigned int) (adif[3 + skip_size] & 0x01) << 19) |
844           ((unsigned int) adif[4 + skip_size] << 11) |
845           ((unsigned int) adif[5 + skip_size] << 3) |
846           ((unsigned int) (adif[6 + skip_size] & 0xe0) >> 5);
847
848       GST_INFO ("ADIF buffer fullness: %d", fullness);
849 #endif
850       aacparse->object_type = ((adif[6 + skip_size] & 0x01) << 1) |
851           ((adif[7 + skip_size] & 0x80) >> 7);
852       sr_idx = (adif[7 + skip_size] & 0x78) >> 3;
853     }
854     /* VBR */
855     else {
856       aacparse->object_type = (adif[4 + skip_size] & 0x18) >> 3;
857       sr_idx = ((adif[4 + skip_size] & 0x07) << 1) |
858           ((adif[5 + skip_size] & 0x80) >> 7);
859     }
860
861     /* FIXME: This gives totally wrong results. Duration calculation cannot
862        be based on this */
863     aacparse->sample_rate = gst_aac_parse_get_sample_rate_from_index (sr_idx);
864
865     /* baseparse is not given any fps,
866      * so it will give up on timestamps, seeking, etc */
867
868     /* FIXME: Can we assume this? */
869     aacparse->channels = 2;
870
871     GST_INFO ("ADIF: br=%d, samplerate=%d, objtype=%d",
872         aacparse->bitrate, aacparse->sample_rate, aacparse->object_type);
873
874     gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse), 512);
875
876     /* arrange for metadata and get out of the way */
877     sinkcaps = gst_pad_get_current_caps (GST_BASE_PARSE_SINK_PAD (aacparse));
878     gst_aac_parse_set_src_caps (aacparse, sinkcaps);
879     if (sinkcaps)
880       gst_caps_unref (sinkcaps);
881
882     /* not syncable, not easily seekable (unless we push data from start */
883     gst_base_parse_set_syncable (GST_BASE_PARSE_CAST (aacparse), FALSE);
884     gst_base_parse_set_passthrough (GST_BASE_PARSE_CAST (aacparse), TRUE);
885     gst_base_parse_set_average_bitrate (GST_BASE_PARSE_CAST (aacparse), 0);
886
887     *framesize = avail;
888     return TRUE;
889   }
890
891   /* This should never happen */
892   return FALSE;
893 }
894
895
896 /**
897  * gst_aac_parse_check_valid_frame:
898  * @parse: #GstBaseParse.
899  * @frame: #GstBaseParseFrame.
900  * @skipsize: How much data parent class should skip in order to find the
901  *            frame header.
902  *
903  * Implementation of "handle_frame" vmethod in #GstBaseParse class.
904  *
905  * Also determines frame overhead.
906  * ADTS streams have a 7 byte header in each frame. MP4 and ADIF streams don't have
907  * a per-frame header. LOAS has 3 bytes.
908  *
909  * We're making a couple of simplifying assumptions:
910  *
911  * 1. We count Program Configuration Elements rather than searching for them
912  *    in the streams to discount them - the overhead is negligible.
913  *
914  * 2. We ignore CRC. This has a worst-case impact of (num_raw_blocks + 1)*16
915  *    bits, which should still not be significant enough to warrant the
916  *    additional parsing through the headers
917  *
918  * Returns: a #GstFlowReturn.
919  */
920 static GstFlowReturn
921 gst_aac_parse_handle_frame (GstBaseParse * parse,
922     GstBaseParseFrame * frame, gint * skipsize)
923 {
924   GstMapInfo map;
925   GstAacParse *aacparse;
926   gboolean ret = FALSE;
927   gboolean lost_sync;
928   GstBuffer *buffer;
929   guint framesize;
930   gint rate, channels;
931
932   aacparse = GST_AAC_PARSE (parse);
933   buffer = frame->buffer;
934
935   gst_buffer_map (buffer, &map, GST_MAP_READ);
936
937   *skipsize = -1;
938   lost_sync = GST_BASE_PARSE_LOST_SYNC (parse);
939
940   if (aacparse->header_type == DSPAAC_HEADER_ADIF ||
941       aacparse->header_type == DSPAAC_HEADER_NONE) {
942     /* There is nothing to parse */
943     framesize = map.size;
944     ret = TRUE;
945
946   } else if (aacparse->header_type == DSPAAC_HEADER_NOT_PARSED || lost_sync) {
947
948     ret = gst_aac_parse_detect_stream (aacparse, map.data, map.size,
949         GST_BASE_PARSE_DRAINING (parse), &framesize, skipsize);
950
951   } else if (aacparse->header_type == DSPAAC_HEADER_ADTS) {
952     guint needed_data = 1024;
953
954     ret = gst_aac_parse_check_adts_frame (aacparse, map.data, map.size,
955         GST_BASE_PARSE_DRAINING (parse), &framesize, &needed_data);
956
957     if (!ret) {
958       GST_DEBUG ("buffer didn't contain valid frame");
959       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
960           needed_data);
961     }
962
963   } else if (aacparse->header_type == DSPAAC_HEADER_LOAS) {
964     guint needed_data = 1024;
965
966     ret = gst_aac_parse_check_loas_frame (aacparse, map.data,
967         map.size, GST_BASE_PARSE_DRAINING (parse), &framesize, &needed_data);
968
969     if (!ret) {
970       GST_DEBUG ("buffer didn't contain valid frame");
971       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
972           needed_data);
973     }
974
975   } else {
976     GST_DEBUG ("buffer didn't contain valid frame");
977     gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
978         ADTS_MAX_SIZE);
979   }
980
981   if (G_UNLIKELY (!ret))
982     goto exit;
983
984   if (aacparse->header_type == DSPAAC_HEADER_ADTS) {
985     /* see above */
986     frame->overhead = 7;
987
988     gst_aac_parse_parse_adts_header (aacparse, map.data,
989         &rate, &channels, NULL, NULL);
990
991     GST_LOG_OBJECT (aacparse, "rate: %d, chans: %d", rate, channels);
992
993     if (G_UNLIKELY (rate != aacparse->sample_rate
994             || channels != aacparse->channels)) {
995       aacparse->sample_rate = rate;
996       aacparse->channels = channels;
997
998       if (!gst_aac_parse_set_src_caps (aacparse, NULL)) {
999         /* If linking fails, we need to return appropriate error */
1000         ret = GST_FLOW_NOT_LINKED;
1001       }
1002
1003       gst_base_parse_set_frame_rate (GST_BASE_PARSE (aacparse),
1004           aacparse->sample_rate, aacparse->frame_samples, 2, 2);
1005     }
1006   } else if (aacparse->header_type == DSPAAC_HEADER_LOAS) {
1007     gboolean setcaps = FALSE;
1008
1009     /* see above */
1010     frame->overhead = 3;
1011
1012     if (!gst_aac_parse_read_loas_config (aacparse, map.data, map.size, &rate,
1013             &channels, NULL)) {
1014       GST_WARNING_OBJECT (aacparse, "Error reading LOAS config");
1015     } else if (G_UNLIKELY (rate != aacparse->sample_rate
1016             || channels != aacparse->channels)) {
1017       aacparse->sample_rate = rate;
1018       aacparse->channels = channels;
1019       setcaps = TRUE;
1020       GST_INFO_OBJECT (aacparse, "New LOAS config: %d Hz, %d channels", rate,
1021           channels);
1022     }
1023
1024     /* We want to set caps both at start, and when rate/channels change.
1025        Since only some LOAS frames have that info, we may receive frames
1026        before knowing about rate/channels. */
1027     if (setcaps
1028         || !gst_pad_has_current_caps (GST_BASE_PARSE_SRC_PAD (aacparse))) {
1029       if (!gst_aac_parse_set_src_caps (aacparse, NULL)) {
1030         /* If linking fails, we need to return appropriate error */
1031         ret = GST_FLOW_NOT_LINKED;
1032       }
1033
1034       gst_base_parse_set_frame_rate (GST_BASE_PARSE (aacparse),
1035           aacparse->sample_rate, aacparse->frame_samples, 2, 2);
1036     }
1037   }
1038
1039 exit:
1040   gst_buffer_unmap (buffer, &map);
1041
1042   if (ret) {
1043     /* found, skip if needed */
1044     if (*skipsize > 0)
1045       return GST_FLOW_OK;
1046     *skipsize = 0;
1047   } else {
1048     if (*skipsize < 0)
1049       *skipsize = 1;
1050   }
1051
1052   if (ret && framesize <= map.size) {
1053     return gst_base_parse_finish_frame (parse, frame, framesize);
1054   }
1055
1056   return GST_FLOW_OK;
1057 }
1058
1059
1060 /**
1061  * gst_aac_parse_start:
1062  * @parse: #GstBaseParse.
1063  *
1064  * Implementation of "start" vmethod in #GstBaseParse class.
1065  *
1066  * Returns: TRUE if startup succeeded.
1067  */
1068 static gboolean
1069 gst_aac_parse_start (GstBaseParse * parse)
1070 {
1071   GstAacParse *aacparse;
1072
1073   aacparse = GST_AAC_PARSE (parse);
1074   GST_DEBUG ("start");
1075   aacparse->frame_samples = 1024;
1076   gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse), ADTS_MAX_SIZE);
1077   return TRUE;
1078 }
1079
1080
1081 /**
1082  * gst_aac_parse_stop:
1083  * @parse: #GstBaseParse.
1084  *
1085  * Implementation of "stop" vmethod in #GstBaseParse class.
1086  *
1087  * Returns: TRUE is stopping succeeded.
1088  */
1089 static gboolean
1090 gst_aac_parse_stop (GstBaseParse * parse)
1091 {
1092   GST_DEBUG ("stop");
1093   return TRUE;
1094 }
1095
1096 static GstCaps *
1097 gst_aac_parse_sink_getcaps (GstBaseParse * parse, GstCaps * filter)
1098 {
1099   GstCaps *peercaps, *templ;
1100   GstCaps *res;
1101
1102   templ = gst_pad_get_pad_template_caps (GST_BASE_PARSE_SINK_PAD (parse));
1103   peercaps = gst_pad_peer_query_caps (GST_BASE_PARSE_SRC_PAD (parse), filter);
1104   if (peercaps) {
1105     guint i, n;
1106
1107     /* Remove the framed field */
1108     peercaps = gst_caps_make_writable (peercaps);
1109     n = gst_caps_get_size (peercaps);
1110     for (i = 0; i < n; i++) {
1111       GstStructure *s = gst_caps_get_structure (peercaps, i);
1112
1113       gst_structure_remove_field (s, "framed");
1114     }
1115
1116     res = gst_caps_intersect_full (peercaps, templ, GST_CAPS_INTERSECT_FIRST);
1117     gst_caps_unref (peercaps);
1118     res = gst_caps_make_writable (res);
1119
1120     /* Append the template caps because we still want to accept
1121      * caps without any fields in the case upstream does not
1122      * know anything.
1123      */
1124     gst_caps_append (res, templ);
1125   } else {
1126     res = templ;
1127   }
1128
1129   if (filter) {
1130     GstCaps *intersection;
1131
1132     intersection =
1133         gst_caps_intersect_full (filter, res, GST_CAPS_INTERSECT_FIRST);
1134     gst_caps_unref (res);
1135     res = intersection;
1136   }
1137
1138   return res;
1139 }