Revert "aacparse: relax the detection of ADTS"
[platform/upstream/gstreamer.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 <gst/pbutils/pbutils.h>
49 #include "gstaacparse.h"
50
51
52 static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
53     GST_PAD_SRC,
54     GST_PAD_ALWAYS,
55     GST_STATIC_CAPS ("audio/mpeg, "
56         "framed = (boolean) true, " "mpegversion = (int) { 2, 4 }, "
57         "stream-format = (string) { raw, adts, adif, loas };"));
58
59 static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
60     GST_PAD_SINK,
61     GST_PAD_ALWAYS,
62     GST_STATIC_CAPS ("audio/mpeg, mpegversion = (int) { 2, 4 };"));
63
64 GST_DEBUG_CATEGORY_STATIC (aacparse_debug);
65 #define GST_CAT_DEFAULT aacparse_debug
66
67
68 #define ADIF_MAX_SIZE 40        /* Should be enough */
69 #define ADTS_MAX_SIZE 10        /* Should be enough */
70 #define LOAS_MAX_SIZE 3         /* Should be enough */
71
72 #define ADTS_HEADERS_LENGTH 7UL /* Total byte-length of fixed and variable
73                                    headers prepended during raw to ADTS
74                                    conversion */
75
76 #define AAC_FRAME_DURATION(parse) (GST_SECOND/parse->frames_per_sec)
77
78 static const gint loas_sample_rate_table[32] = {
79   96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
80   16000, 12000, 11025, 8000, 7350, 0, 0, 0
81 };
82
83 static const gint loas_channels_table[32] = {
84   0, 1, 2, 3, 4, 5, 6, 8,
85   0, 0, 0, 0, 0, 0, 0, 0
86 };
87
88 static gboolean gst_aac_parse_start (GstBaseParse * parse);
89 static gboolean gst_aac_parse_stop (GstBaseParse * parse);
90
91 static gboolean gst_aac_parse_sink_setcaps (GstBaseParse * parse,
92     GstCaps * caps);
93 static GstCaps *gst_aac_parse_sink_getcaps (GstBaseParse * parse,
94     GstCaps * filter);
95
96 static GstFlowReturn gst_aac_parse_handle_frame (GstBaseParse * parse,
97     GstBaseParseFrame * frame, gint * skipsize);
98 static GstFlowReturn gst_aac_parse_pre_push_frame (GstBaseParse * parse,
99     GstBaseParseFrame * frame);
100
101 G_DEFINE_TYPE (GstAacParse, gst_aac_parse, GST_TYPE_BASE_PARSE);
102
103 /**
104  * gst_aac_parse_class_init:
105  * @klass: #GstAacParseClass.
106  *
107  */
108 static void
109 gst_aac_parse_class_init (GstAacParseClass * klass)
110 {
111   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
112   GstBaseParseClass *parse_class = GST_BASE_PARSE_CLASS (klass);
113
114   GST_DEBUG_CATEGORY_INIT (aacparse_debug, "aacparse", 0,
115       "AAC audio stream parser");
116
117   gst_element_class_add_pad_template (element_class,
118       gst_static_pad_template_get (&sink_template));
119   gst_element_class_add_pad_template (element_class,
120       gst_static_pad_template_get (&src_template));
121
122   gst_element_class_set_static_metadata (element_class,
123       "AAC audio stream parser", "Codec/Parser/Audio",
124       "Advanced Audio Coding parser", "Stefan Kost <stefan.kost@nokia.com>");
125
126   parse_class->start = GST_DEBUG_FUNCPTR (gst_aac_parse_start);
127   parse_class->stop = GST_DEBUG_FUNCPTR (gst_aac_parse_stop);
128   parse_class->set_sink_caps = GST_DEBUG_FUNCPTR (gst_aac_parse_sink_setcaps);
129   parse_class->get_sink_caps = GST_DEBUG_FUNCPTR (gst_aac_parse_sink_getcaps);
130   parse_class->handle_frame = GST_DEBUG_FUNCPTR (gst_aac_parse_handle_frame);
131   parse_class->pre_push_frame =
132       GST_DEBUG_FUNCPTR (gst_aac_parse_pre_push_frame);
133 }
134
135
136 /**
137  * gst_aac_parse_init:
138  * @aacparse: #GstAacParse.
139  * @klass: #GstAacParseClass.
140  *
141  */
142 static void
143 gst_aac_parse_init (GstAacParse * aacparse)
144 {
145   GST_DEBUG ("initialized");
146   GST_PAD_SET_ACCEPT_INTERSECT (GST_BASE_PARSE_SINK_PAD (aacparse));
147 }
148
149
150 /**
151  * gst_aac_parse_set_src_caps:
152  * @aacparse: #GstAacParse.
153  * @sink_caps: (proposed) caps of sink pad
154  *
155  * Set source pad caps according to current knowledge about the
156  * audio stream.
157  *
158  * Returns: TRUE if caps were successfully set.
159  */
160 static gboolean
161 gst_aac_parse_set_src_caps (GstAacParse * aacparse, GstCaps * sink_caps)
162 {
163   GstStructure *s;
164   GstCaps *src_caps = NULL, *allowed;
165   gboolean res = FALSE;
166   const gchar *stream_format;
167   GstBuffer *codec_data;
168   guint16 codec_data_data;
169
170   GST_DEBUG_OBJECT (aacparse, "sink caps: %" GST_PTR_FORMAT, sink_caps);
171   if (sink_caps)
172     src_caps = gst_caps_copy (sink_caps);
173   else
174     src_caps = gst_caps_new_empty_simple ("audio/mpeg");
175
176   gst_caps_set_simple (src_caps, "framed", G_TYPE_BOOLEAN, TRUE,
177       "mpegversion", G_TYPE_INT, aacparse->mpegversion, NULL);
178
179   aacparse->output_header_type = aacparse->header_type;
180   switch (aacparse->header_type) {
181     case DSPAAC_HEADER_NONE:
182       stream_format = "raw";
183       break;
184     case DSPAAC_HEADER_ADTS:
185       stream_format = "adts";
186       break;
187     case DSPAAC_HEADER_ADIF:
188       stream_format = "adif";
189       break;
190     case DSPAAC_HEADER_LOAS:
191       stream_format = "loas";
192       break;
193     default:
194       stream_format = NULL;
195   }
196
197   s = gst_caps_get_structure (src_caps, 0);
198   if (aacparse->sample_rate > 0)
199     gst_structure_set (s, "rate", G_TYPE_INT, aacparse->sample_rate, NULL);
200   if (aacparse->channels > 0)
201     gst_structure_set (s, "channels", G_TYPE_INT, aacparse->channels, NULL);
202   if (stream_format)
203     gst_structure_set (s, "stream-format", G_TYPE_STRING, stream_format, NULL);
204
205   allowed = gst_pad_get_allowed_caps (GST_BASE_PARSE (aacparse)->srcpad);
206   if (!gst_caps_can_intersect (src_caps, allowed)) {
207     GST_DEBUG_OBJECT (GST_BASE_PARSE (aacparse)->srcpad,
208         "Caps can not intersect");
209     if (aacparse->header_type == DSPAAC_HEADER_ADTS) {
210       GST_DEBUG_OBJECT (GST_BASE_PARSE (aacparse)->srcpad,
211           "Input is ADTS, trying raw");
212       gst_caps_set_simple (src_caps, "stream-format", G_TYPE_STRING, "raw",
213           NULL);
214       if (gst_caps_can_intersect (src_caps, allowed)) {
215         GstMapInfo map;
216         int idx;
217
218         idx =
219             gst_codec_utils_aac_get_index_from_sample_rate
220             (aacparse->sample_rate);
221         if (idx < 0)
222           goto not_a_known_rate;
223
224         GST_DEBUG_OBJECT (GST_BASE_PARSE (aacparse)->srcpad,
225             "Caps can intersect, we will drop the ADTS layer");
226         aacparse->output_header_type = DSPAAC_HEADER_NONE;
227
228         /* The codec_data data is according to AudioSpecificConfig,
229            ISO/IEC 14496-3, 1.6.2.1 */
230         codec_data = gst_buffer_new_and_alloc (2);
231         gst_buffer_map (codec_data, &map, GST_MAP_WRITE);
232         codec_data_data =
233             (aacparse->object_type << 11) |
234             (idx << 7) | (aacparse->channels << 3);
235         GST_WRITE_UINT16_BE (map.data, codec_data_data);
236         gst_buffer_unmap (codec_data, &map);
237         gst_caps_set_simple (src_caps, "codec_data", GST_TYPE_BUFFER,
238             codec_data, NULL);
239       }
240     } else if (aacparse->header_type == DSPAAC_HEADER_NONE) {
241       GST_DEBUG_OBJECT (GST_BASE_PARSE (aacparse)->srcpad,
242           "Input is raw, trying ADTS");
243       gst_caps_set_simple (src_caps, "stream-format", G_TYPE_STRING, "adts",
244           NULL);
245       if (gst_caps_can_intersect (src_caps, allowed)) {
246         GST_DEBUG_OBJECT (GST_BASE_PARSE (aacparse)->srcpad,
247             "Caps can intersect, we will prepend ADTS headers");
248         aacparse->output_header_type = DSPAAC_HEADER_ADTS;
249       }
250     }
251   }
252   gst_caps_unref (allowed);
253
254   GST_DEBUG_OBJECT (aacparse, "setting src caps: %" GST_PTR_FORMAT, src_caps);
255
256   res = gst_pad_set_caps (GST_BASE_PARSE (aacparse)->srcpad, src_caps);
257   gst_caps_unref (src_caps);
258   return res;
259
260 not_a_known_rate:
261   gst_caps_unref (allowed);
262   gst_caps_unref (src_caps);
263   return FALSE;
264 }
265
266
267 /**
268  * gst_aac_parse_sink_setcaps:
269  * @sinkpad: GstPad
270  * @caps: GstCaps
271  *
272  * Implementation of "set_sink_caps" vmethod in #GstBaseParse class.
273  *
274  * Returns: TRUE on success.
275  */
276 static gboolean
277 gst_aac_parse_sink_setcaps (GstBaseParse * parse, GstCaps * caps)
278 {
279   GstAacParse *aacparse;
280   GstStructure *structure;
281   gchar *caps_str;
282   const GValue *value;
283
284   aacparse = GST_AAC_PARSE (parse);
285   structure = gst_caps_get_structure (caps, 0);
286   caps_str = gst_caps_to_string (caps);
287
288   GST_DEBUG_OBJECT (aacparse, "setcaps: %s", caps_str);
289   g_free (caps_str);
290
291   /* This is needed at least in case of RTP
292    * Parses the codec_data information to get ObjectType,
293    * number of channels and samplerate */
294   value = gst_structure_get_value (structure, "codec_data");
295   if (value) {
296     GstBuffer *buf = gst_value_get_buffer (value);
297
298     if (buf) {
299       GstMapInfo map;
300       guint sr_idx;
301
302       gst_buffer_map (buf, &map, GST_MAP_READ);
303
304       sr_idx = ((map.data[0] & 0x07) << 1) | ((map.data[1] & 0x80) >> 7);
305       aacparse->object_type = (map.data[0] & 0xf8) >> 3;
306       aacparse->sample_rate =
307           gst_codec_utils_aac_get_sample_rate_from_index (sr_idx);
308       aacparse->channels = (map.data[1] & 0x78) >> 3;
309       aacparse->header_type = DSPAAC_HEADER_NONE;
310       aacparse->mpegversion = 4;
311       aacparse->frame_samples = (map.data[1] & 4) ? 960 : 1024;
312       gst_buffer_unmap (buf, &map);
313
314       GST_DEBUG ("codec_data: object_type=%d, sample_rate=%d, channels=%d, "
315           "samples=%d", aacparse->object_type, aacparse->sample_rate,
316           aacparse->channels, aacparse->frame_samples);
317
318       /* arrange for metadata and get out of the way */
319       gst_aac_parse_set_src_caps (aacparse, caps);
320       if (aacparse->header_type == aacparse->output_header_type)
321         gst_base_parse_set_passthrough (parse, TRUE);
322     } else
323       return FALSE;
324
325     /* caps info overrides */
326     gst_structure_get_int (structure, "rate", &aacparse->sample_rate);
327     gst_structure_get_int (structure, "channels", &aacparse->channels);
328   } else {
329     aacparse->sample_rate = 0;
330     aacparse->channels = 0;
331     aacparse->header_type = DSPAAC_HEADER_NOT_PARSED;
332     gst_base_parse_set_passthrough (parse, FALSE);
333   }
334
335   return TRUE;
336 }
337
338
339 /**
340  * gst_aac_parse_adts_get_frame_len:
341  * @data: block of data containing an ADTS header.
342  *
343  * This function calculates ADTS frame length from the given header.
344  *
345  * Returns: size of the ADTS frame.
346  */
347 static inline guint
348 gst_aac_parse_adts_get_frame_len (const guint8 * data)
349 {
350   return ((data[3] & 0x03) << 11) | (data[4] << 3) | ((data[5] & 0xe0) >> 5);
351 }
352
353
354 /**
355  * gst_aac_parse_check_adts_frame:
356  * @aacparse: #GstAacParse.
357  * @data: Data to be checked.
358  * @avail: Amount of data passed.
359  * @framesize: If valid ADTS frame was found, this will be set to tell the
360  *             found frame size in bytes.
361  * @needed_data: If frame was not found, this may be set to tell how much
362  *               more data is needed in the next round to detect the frame
363  *               reliably. This may happen when a frame header candidate
364  *               is found but it cannot be guaranteed to be the header without
365  *               peeking the following data.
366  *
367  * Check if the given data contains contains ADTS frame. The algorithm
368  * will examine ADTS frame header and calculate the frame size. Also, another
369  * consecutive ADTS frame header need to be present after the found frame.
370  * Otherwise the data is not considered as a valid ADTS frame. However, this
371  * "extra check" is omitted when EOS has been received. In this case it is
372  * enough when data[0] contains a valid ADTS header.
373  *
374  * This function may set the #needed_data to indicate that a possible frame
375  * candidate has been found, but more data (#needed_data bytes) is needed to
376  * be absolutely sure. When this situation occurs, FALSE will be returned.
377  *
378  * When a valid frame is detected, this function will use
379  * gst_base_parse_set_min_frame_size() function from #GstBaseParse class
380  * to set the needed bytes for next frame.This way next data chunk is already
381  * of correct size.
382  *
383  * Returns: TRUE if the given data contains a valid ADTS header.
384  */
385 static gboolean
386 gst_aac_parse_check_adts_frame (GstAacParse * aacparse,
387     const guint8 * data, const guint avail, gboolean drain,
388     guint * framesize, guint * needed_data)
389 {
390   *needed_data = 0;
391
392   if (G_UNLIKELY (avail < 2))
393     return FALSE;
394
395   if ((data[0] == 0xff) && ((data[1] & 0xf6) == 0xf0)) {
396     *framesize = gst_aac_parse_adts_get_frame_len (data);
397
398     /* In EOS mode this is enough. No need to examine the data further.
399        We also relax the check when we have sync, on the assumption that
400        if we're not looking at random data, we have a much higher chance
401        to get the correct sync, and this avoids losing two frames when
402        a single bit corruption happens. */
403     if (drain || !GST_BASE_PARSE_LOST_SYNC (aacparse)) {
404       return TRUE;
405     }
406
407     if (*framesize + ADTS_MAX_SIZE > avail) {
408       /* We have found a possible frame header candidate, but can't be
409          sure since we don't have enough data to check the next frame */
410       GST_DEBUG ("NEED MORE DATA: we need %d, available %d",
411           *framesize + ADTS_MAX_SIZE, avail);
412       *needed_data = *framesize + ADTS_MAX_SIZE;
413       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
414           *framesize + ADTS_MAX_SIZE);
415       return FALSE;
416     }
417
418     if ((data[*framesize] == 0xff) && ((data[*framesize + 1] & 0xf6) == 0xf0)) {
419       guint nextlen = gst_aac_parse_adts_get_frame_len (data + (*framesize));
420
421       GST_LOG ("ADTS frame found, len: %d bytes", *framesize);
422       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
423           nextlen + ADTS_MAX_SIZE);
424       return TRUE;
425     }
426   }
427   return FALSE;
428 }
429
430 static gboolean
431 gst_aac_parse_latm_get_value (GstAacParse * aacparse, GstBitReader * br,
432     guint32 * value)
433 {
434   guint8 bytes, i, byte;
435
436   *value = 0;
437   if (!gst_bit_reader_get_bits_uint8 (br, &bytes, 2))
438     return FALSE;
439   for (i = 0; i < bytes; ++i) {
440     *value <<= 8;
441     if (!gst_bit_reader_get_bits_uint8 (br, &byte, 8))
442       return FALSE;
443     *value += byte;
444   }
445   return TRUE;
446 }
447
448 static gboolean
449 gst_aac_parse_get_audio_object_type (GstAacParse * aacparse, GstBitReader * br,
450     guint8 * audio_object_type)
451 {
452   if (!gst_bit_reader_get_bits_uint8 (br, audio_object_type, 5))
453     return FALSE;
454   if (*audio_object_type == 31) {
455     if (!gst_bit_reader_get_bits_uint8 (br, audio_object_type, 6))
456       return FALSE;
457     *audio_object_type += 32;
458   }
459   GST_LOG_OBJECT (aacparse, "audio object type %u", *audio_object_type);
460   return TRUE;
461 }
462
463 static gboolean
464 gst_aac_parse_get_audio_sample_rate (GstAacParse * aacparse, GstBitReader * br,
465     gint * sample_rate)
466 {
467   guint8 sampling_frequency_index;
468   if (!gst_bit_reader_get_bits_uint8 (br, &sampling_frequency_index, 4))
469     return FALSE;
470   GST_LOG_OBJECT (aacparse, "sampling_frequency_index: %u",
471       sampling_frequency_index);
472   if (sampling_frequency_index == 0xf) {
473     guint32 sampling_rate;
474     if (!gst_bit_reader_get_bits_uint32 (br, &sampling_rate, 24))
475       return FALSE;
476     *sample_rate = sampling_rate;
477   } else {
478     *sample_rate = loas_sample_rate_table[sampling_frequency_index];
479     if (!*sample_rate)
480       return FALSE;
481   }
482   return TRUE;
483 }
484
485 /* See table 1.13 in ISO/IEC 14496-3 */
486 static gboolean
487 gst_aac_parse_read_loas_audio_specific_config (GstAacParse * aacparse,
488     GstBitReader * br, gint * sample_rate, gint * channels, guint32 * bits)
489 {
490   guint8 audio_object_type, channel_configuration;
491
492   if (!gst_aac_parse_get_audio_object_type (aacparse, br, &audio_object_type))
493     return FALSE;
494
495   if (!gst_aac_parse_get_audio_sample_rate (aacparse, br, sample_rate))
496     return FALSE;
497
498   if (!gst_bit_reader_get_bits_uint8 (br, &channel_configuration, 4))
499     return FALSE;
500   GST_LOG_OBJECT (aacparse, "channel_configuration: %d", channel_configuration);
501   *channels = loas_channels_table[channel_configuration];
502   if (!*channels)
503     return FALSE;
504
505   if (audio_object_type == 5) {
506     GST_LOG_OBJECT (aacparse,
507         "Audio object type 5, so rereading sampling rate...");
508     if (!gst_aac_parse_get_audio_sample_rate (aacparse, br, sample_rate))
509       return FALSE;
510   }
511
512   GST_INFO_OBJECT (aacparse, "Found LOAS config: %d Hz, %d channels",
513       *sample_rate, *channels);
514
515   /* There's LOTS of stuff next, but we ignore it for now as we have
516      what we want (sample rate and number of channels */
517   GST_DEBUG_OBJECT (aacparse,
518       "Need more code to parse humongous LOAS data, currently ignored");
519   if (bits)
520     *bits = 0;
521   return TRUE;
522 }
523
524
525 static gboolean
526 gst_aac_parse_read_loas_config (GstAacParse * aacparse, const guint8 * data,
527     guint avail, gint * sample_rate, gint * channels, gint * version)
528 {
529   GstBitReader br;
530   guint8 u8, v, vA;
531
532   /* No version in the bitstream, but the spec has LOAS in the MPEG-4 section */
533   if (version)
534     *version = 4;
535
536   gst_bit_reader_init (&br, data, avail);
537
538   /* skip sync word (11 bits) and size (13 bits) */
539   if (!gst_bit_reader_skip (&br, 11 + 13))
540     return FALSE;
541
542   /* First bit is "use last config" */
543   if (!gst_bit_reader_get_bits_uint8 (&br, &u8, 1))
544     return FALSE;
545   if (u8) {
546     GST_DEBUG_OBJECT (aacparse, "Frame uses previous config");
547     if (!aacparse->sample_rate || !aacparse->channels) {
548       GST_WARNING_OBJECT (aacparse, "No previous config to use");
549     }
550     *sample_rate = aacparse->sample_rate;
551     *channels = aacparse->channels;
552     return TRUE;
553   }
554
555   GST_DEBUG_OBJECT (aacparse, "Frame contains new config");
556
557   if (!gst_bit_reader_get_bits_uint8 (&br, &v, 1))
558     return FALSE;
559   if (v) {
560     if (!gst_bit_reader_get_bits_uint8 (&br, &vA, 1))
561       return FALSE;
562   } else
563     vA = 0;
564
565   GST_LOG_OBJECT (aacparse, "v %d, vA %d", v, vA);
566   if (vA == 0) {
567     guint8 same_time, subframes, num_program, prog;
568     if (v == 1) {
569       guint32 value;
570       if (!gst_aac_parse_latm_get_value (aacparse, &br, &value))
571         return FALSE;
572     }
573     if (!gst_bit_reader_get_bits_uint8 (&br, &same_time, 1))
574       return FALSE;
575     if (!gst_bit_reader_get_bits_uint8 (&br, &subframes, 6))
576       return FALSE;
577     if (!gst_bit_reader_get_bits_uint8 (&br, &num_program, 4))
578       return FALSE;
579     GST_LOG_OBJECT (aacparse, "same_time %d, subframes %d, num_program %d",
580         same_time, subframes, num_program);
581
582     for (prog = 0; prog <= num_program; ++prog) {
583       guint8 num_layer, layer;
584       if (!gst_bit_reader_get_bits_uint8 (&br, &num_layer, 3))
585         return FALSE;
586       GST_LOG_OBJECT (aacparse, "Program %d: %d layers", prog, num_layer);
587
588       for (layer = 0; layer <= num_layer; ++layer) {
589         guint8 use_same_config;
590         if (prog == 0 && layer == 0) {
591           use_same_config = 0;
592         } else {
593           if (!gst_bit_reader_get_bits_uint8 (&br, &use_same_config, 1))
594             return FALSE;
595         }
596         if (!use_same_config) {
597           if (v == 0) {
598             if (!gst_aac_parse_read_loas_audio_specific_config (aacparse, &br,
599                     sample_rate, channels, NULL))
600               return FALSE;
601           } else {
602             guint32 bits, asc_len;
603             if (!gst_aac_parse_latm_get_value (aacparse, &br, &asc_len))
604               return FALSE;
605             if (!gst_aac_parse_read_loas_audio_specific_config (aacparse, &br,
606                     sample_rate, channels, &bits))
607               return FALSE;
608             asc_len -= bits;
609             if (!gst_bit_reader_skip (&br, asc_len))
610               return FALSE;
611           }
612         }
613       }
614     }
615     GST_LOG_OBJECT (aacparse, "More data ignored");
616   } else {
617     GST_WARNING_OBJECT (aacparse, "Spec says \"TBD\"...");
618   }
619   return TRUE;
620 }
621
622 /**
623  * gst_aac_parse_loas_get_frame_len:
624  * @data: block of data containing a LOAS header.
625  *
626  * This function calculates LOAS frame length from the given header.
627  *
628  * Returns: size of the LOAS frame.
629  */
630 static inline guint
631 gst_aac_parse_loas_get_frame_len (const guint8 * data)
632 {
633   return (((data[1] & 0x1f) << 8) | data[2]) + 3;
634 }
635
636
637 /**
638  * gst_aac_parse_check_loas_frame:
639  * @aacparse: #GstAacParse.
640  * @data: Data to be checked.
641  * @avail: Amount of data passed.
642  * @framesize: If valid LOAS frame was found, this will be set to tell the
643  *             found frame size in bytes.
644  * @needed_data: If frame was not found, this may be set to tell how much
645  *               more data is needed in the next round to detect the frame
646  *               reliably. This may happen when a frame header candidate
647  *               is found but it cannot be guaranteed to be the header without
648  *               peeking the following data.
649  *
650  * Check if the given data contains contains LOAS frame. The algorithm
651  * will examine LOAS frame header and calculate the frame size. Also, another
652  * consecutive LOAS frame header need to be present after the found frame.
653  * Otherwise the data is not considered as a valid LOAS frame. However, this
654  * "extra check" is omitted when EOS has been received. In this case it is
655  * enough when data[0] contains a valid LOAS header.
656  *
657  * This function may set the #needed_data to indicate that a possible frame
658  * candidate has been found, but more data (#needed_data bytes) is needed to
659  * be absolutely sure. When this situation occurs, FALSE will be returned.
660  *
661  * When a valid frame is detected, this function will use
662  * gst_base_parse_set_min_frame_size() function from #GstBaseParse class
663  * to set the needed bytes for next frame.This way next data chunk is already
664  * of correct size.
665  *
666  * LOAS can have three different formats, if I read the spec correctly. Only
667  * one of them is supported here, as the two samples I have use this one.
668  *
669  * Returns: TRUE if the given data contains a valid LOAS header.
670  */
671 static gboolean
672 gst_aac_parse_check_loas_frame (GstAacParse * aacparse,
673     const guint8 * data, const guint avail, gboolean drain,
674     guint * framesize, guint * needed_data)
675 {
676   *needed_data = 0;
677
678   /* 3 byte header */
679   if (G_UNLIKELY (avail < 3))
680     return FALSE;
681
682   if ((data[0] == 0x56) && ((data[1] & 0xe0) == 0xe0)) {
683     *framesize = gst_aac_parse_loas_get_frame_len (data);
684     GST_DEBUG_OBJECT (aacparse, "Found %u byte LOAS frame", *framesize);
685
686     /* In EOS mode this is enough. No need to examine the data further.
687        We also relax the check when we have sync, on the assumption that
688        if we're not looking at random data, we have a much higher chance
689        to get the correct sync, and this avoids losing two frames when
690        a single bit corruption happens. */
691     if (drain || !GST_BASE_PARSE_LOST_SYNC (aacparse)) {
692       return TRUE;
693     }
694
695     if (*framesize + LOAS_MAX_SIZE > avail) {
696       /* We have found a possible frame header candidate, but can't be
697          sure since we don't have enough data to check the next frame */
698       GST_DEBUG ("NEED MORE DATA: we need %d, available %d",
699           *framesize + LOAS_MAX_SIZE, avail);
700       *needed_data = *framesize + LOAS_MAX_SIZE;
701       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
702           *framesize + LOAS_MAX_SIZE);
703       return FALSE;
704     }
705
706     if ((data[*framesize] == 0x56) && ((data[*framesize + 1] & 0xe0) == 0xe0)) {
707       guint nextlen = gst_aac_parse_loas_get_frame_len (data + (*framesize));
708
709       GST_LOG ("LOAS frame found, len: %d bytes", *framesize);
710       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
711           nextlen + LOAS_MAX_SIZE);
712       return TRUE;
713     }
714   }
715   return FALSE;
716 }
717
718 /* caller ensure sufficient data */
719 static inline void
720 gst_aac_parse_parse_adts_header (GstAacParse * aacparse, const guint8 * data,
721     gint * rate, gint * channels, gint * object, gint * version)
722 {
723
724   if (rate) {
725     gint sr_idx = (data[2] & 0x3c) >> 2;
726
727     *rate = gst_codec_utils_aac_get_sample_rate_from_index (sr_idx);
728   }
729   if (channels)
730     *channels = ((data[2] & 0x01) << 2) | ((data[3] & 0xc0) >> 6);
731
732   if (version)
733     *version = (data[1] & 0x08) ? 2 : 4;
734   if (object)
735     *object = ((data[2] & 0xc0) >> 6) + 1;
736 }
737
738 /**
739  * gst_aac_parse_detect_stream:
740  * @aacparse: #GstAacParse.
741  * @data: A block of data that needs to be examined for stream characteristics.
742  * @avail: Size of the given datablock.
743  * @framesize: If valid stream was found, this will be set to tell the
744  *             first frame size in bytes.
745  * @skipsize: If valid stream was found, this will be set to tell the first
746  *            audio frame position within the given data.
747  *
748  * Examines the given piece of data and try to detect the format of it. It
749  * checks for "ADIF" header (in the beginning of the clip) and ADTS frame
750  * header. If the stream is detected, TRUE will be returned and #framesize
751  * is set to indicate the found frame size. Additionally, #skipsize might
752  * be set to indicate the number of bytes that need to be skipped, a.k.a. the
753  * position of the frame inside given data chunk.
754  *
755  * Returns: TRUE on success.
756  */
757 static gboolean
758 gst_aac_parse_detect_stream (GstAacParse * aacparse,
759     const guint8 * data, const guint avail, gboolean drain,
760     guint * framesize, gint * skipsize)
761 {
762   gboolean found = FALSE;
763   guint need_data_adts = 0, need_data_loas;
764   guint i = 0;
765
766   GST_DEBUG_OBJECT (aacparse, "Parsing header data");
767
768   /* FIXME: No need to check for ADIF if we are not in the beginning of the
769      stream */
770
771   /* Can we even parse the header? */
772   if (avail < MAX (ADTS_MAX_SIZE, LOAS_MAX_SIZE)) {
773     GST_DEBUG_OBJECT (aacparse, "Not enough data to check");
774     return FALSE;
775   }
776
777   for (i = 0; i < avail - 4; i++) {
778     if (((data[i] == 0xff) && ((data[i + 1] & 0xf6) == 0xf0)) ||
779         ((data[0] == 0x56) && ((data[1] & 0xe0) == 0xe0)) ||
780         strncmp ((char *) data + i, "ADIF", 4) == 0) {
781       GST_DEBUG_OBJECT (aacparse, "Found signature at offset %u", i);
782       found = TRUE;
783
784       if (i) {
785         /* Trick: tell the parent class that we didn't find the frame yet,
786            but make it skip 'i' amount of bytes. Next time we arrive
787            here we have full frame in the beginning of the data. */
788         *skipsize = i;
789         return FALSE;
790       }
791       break;
792     }
793   }
794   if (!found) {
795     if (i)
796       *skipsize = i;
797     return FALSE;
798   }
799
800   if (gst_aac_parse_check_adts_frame (aacparse, data, avail, drain,
801           framesize, &need_data_adts)) {
802     gint rate, channels;
803
804     GST_INFO ("ADTS ID: %d, framesize: %d", (data[1] & 0x08) >> 3, *framesize);
805
806     gst_aac_parse_parse_adts_header (aacparse, data, &rate, &channels,
807         &aacparse->object_type, &aacparse->mpegversion);
808
809     if (!channels || !framesize) {
810       GST_DEBUG_OBJECT (aacparse, "impossible ADTS configuration");
811       return FALSE;
812     }
813
814     aacparse->header_type = DSPAAC_HEADER_ADTS;
815     gst_base_parse_set_frame_rate (GST_BASE_PARSE (aacparse), rate,
816         aacparse->frame_samples, 2, 2);
817
818     GST_DEBUG ("ADTS: samplerate %d, channels %d, objtype %d, version %d",
819         rate, channels, aacparse->object_type, aacparse->mpegversion);
820
821     gst_base_parse_set_syncable (GST_BASE_PARSE (aacparse), TRUE);
822
823     return TRUE;
824   }
825
826   if (gst_aac_parse_check_loas_frame (aacparse, data, avail, drain,
827           framesize, &need_data_loas)) {
828     gint rate, channels;
829
830     GST_INFO ("LOAS, framesize: %d", *framesize);
831
832     aacparse->header_type = DSPAAC_HEADER_LOAS;
833
834     if (!gst_aac_parse_read_loas_config (aacparse, data, avail, &rate,
835             &channels, &aacparse->mpegversion)) {
836       GST_WARNING_OBJECT (aacparse, "Error reading LOAS config");
837       return FALSE;
838     }
839
840     if (rate && channels) {
841       gst_base_parse_set_frame_rate (GST_BASE_PARSE (aacparse), rate,
842           aacparse->frame_samples, 2, 2);
843
844       GST_DEBUG ("LOAS: samplerate %d, channels %d, objtype %d, version %d",
845           rate, channels, aacparse->object_type, aacparse->mpegversion);
846       aacparse->sample_rate = rate;
847       aacparse->channels = channels;
848     }
849
850     gst_base_parse_set_syncable (GST_BASE_PARSE (aacparse), TRUE);
851
852     return TRUE;
853   }
854
855   if (need_data_adts || need_data_loas) {
856     /* This tells the parent class not to skip any data */
857     *skipsize = 0;
858     return FALSE;
859   }
860
861   if (avail < ADIF_MAX_SIZE)
862     return FALSE;
863
864   if (memcmp (data + i, "ADIF", 4) == 0) {
865     const guint8 *adif;
866     int skip_size = 0;
867     int bitstream_type;
868     int sr_idx;
869     GstCaps *sinkcaps;
870
871     aacparse->header_type = DSPAAC_HEADER_ADIF;
872     aacparse->mpegversion = 4;
873
874     /* Skip the "ADIF" bytes */
875     adif = data + i + 4;
876
877     /* copyright string */
878     if (adif[0] & 0x80)
879       skip_size += 9;           /* skip 9 bytes */
880
881     bitstream_type = adif[0 + skip_size] & 0x10;
882     aacparse->bitrate =
883         ((unsigned int) (adif[0 + skip_size] & 0x0f) << 19) |
884         ((unsigned int) adif[1 + skip_size] << 11) |
885         ((unsigned int) adif[2 + skip_size] << 3) |
886         ((unsigned int) adif[3 + skip_size] & 0xe0);
887
888     /* CBR */
889     if (bitstream_type == 0) {
890 #if 0
891       /* Buffer fullness parsing. Currently not needed... */
892       guint num_elems = 0;
893       guint fullness = 0;
894
895       num_elems = (adif[3 + skip_size] & 0x1e);
896       GST_INFO ("ADIF num_config_elems: %d", num_elems);
897
898       fullness = ((unsigned int) (adif[3 + skip_size] & 0x01) << 19) |
899           ((unsigned int) adif[4 + skip_size] << 11) |
900           ((unsigned int) adif[5 + skip_size] << 3) |
901           ((unsigned int) (adif[6 + skip_size] & 0xe0) >> 5);
902
903       GST_INFO ("ADIF buffer fullness: %d", fullness);
904 #endif
905       aacparse->object_type = ((adif[6 + skip_size] & 0x01) << 1) |
906           ((adif[7 + skip_size] & 0x80) >> 7);
907       sr_idx = (adif[7 + skip_size] & 0x78) >> 3;
908     }
909     /* VBR */
910     else {
911       aacparse->object_type = (adif[4 + skip_size] & 0x18) >> 3;
912       sr_idx = ((adif[4 + skip_size] & 0x07) << 1) |
913           ((adif[5 + skip_size] & 0x80) >> 7);
914     }
915
916     /* FIXME: This gives totally wrong results. Duration calculation cannot
917        be based on this */
918     aacparse->sample_rate =
919         gst_codec_utils_aac_get_sample_rate_from_index (sr_idx);
920
921     /* baseparse is not given any fps,
922      * so it will give up on timestamps, seeking, etc */
923
924     /* FIXME: Can we assume this? */
925     aacparse->channels = 2;
926
927     GST_INFO ("ADIF: br=%d, samplerate=%d, objtype=%d",
928         aacparse->bitrate, aacparse->sample_rate, aacparse->object_type);
929
930     gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse), 512);
931
932     /* arrange for metadata and get out of the way */
933     sinkcaps = gst_pad_get_current_caps (GST_BASE_PARSE_SINK_PAD (aacparse));
934     gst_aac_parse_set_src_caps (aacparse, sinkcaps);
935     if (sinkcaps)
936       gst_caps_unref (sinkcaps);
937
938     /* not syncable, not easily seekable (unless we push data from start */
939     gst_base_parse_set_syncable (GST_BASE_PARSE_CAST (aacparse), FALSE);
940     gst_base_parse_set_passthrough (GST_BASE_PARSE_CAST (aacparse), TRUE);
941     gst_base_parse_set_average_bitrate (GST_BASE_PARSE_CAST (aacparse), 0);
942
943     *framesize = avail;
944     return TRUE;
945   }
946
947   /* This should never happen */
948   return FALSE;
949 }
950
951 /**
952  * gst_aac_parse_get_audio_profile_object_type
953  * @aacparse: #GstAacParse.
954  *
955  * Gets the MPEG-2 profile or the MPEG-4 object type value corresponding to the
956  * mpegversion and profile of @aacparse's src pad caps, according to the
957  * values defined by table 1.A.11 in ISO/IEC 14496-3.
958  *
959  * Returns: the profile or object type value corresponding to @aacparse's src
960  * pad caps, if such a value exists; otherwise G_MAXUINT8.
961  */
962 static guint8
963 gst_aac_parse_get_audio_profile_object_type (GstAacParse * aacparse)
964 {
965   GstCaps *srccaps;
966   GstStructure *srcstruct;
967   const gchar *profile;
968   guint8 ret;
969
970   srccaps = gst_pad_get_current_caps (GST_BASE_PARSE_SRC_PAD (aacparse));
971   srcstruct = gst_caps_get_structure (srccaps, 0);
972   profile = gst_structure_get_string (srcstruct, "profile");
973   if (G_UNLIKELY (profile == NULL)) {
974     gst_caps_unref (srccaps);
975     return G_MAXUINT8;
976   }
977
978   if (g_strcmp0 (profile, "main") == 0) {
979     ret = (guint8) 0U;
980   } else if (g_strcmp0 (profile, "lc") == 0) {
981     ret = (guint8) 1U;
982   } else if (g_strcmp0 (profile, "ssr") == 0) {
983     ret = (guint8) 2U;
984   } else if (g_strcmp0 (profile, "ltp") == 0) {
985     if (G_LIKELY (aacparse->mpegversion == 4))
986       ret = (guint8) 3U;
987     else
988       ret = G_MAXUINT8;         /* LTP Object Type allowed only for MPEG-4 */
989   } else {
990     ret = G_MAXUINT8;
991   }
992
993   gst_caps_unref (srccaps);
994   return ret;
995 }
996
997 /**
998  * gst_aac_parse_get_audio_channel_configuration
999  * @num_channels: number of audio channels.
1000  *
1001  * Gets the Channel Configuration value, as defined by table 1.19 in ISO/IEC
1002  * 14496-3, for a given number of audio channels.
1003  *
1004  * Returns: the Channel Configuration value corresponding to @num_channels, if
1005  * such a value exists; otherwise G_MAXUINT8.
1006  */
1007 static guint8
1008 gst_aac_parse_get_audio_channel_configuration (gint num_channels)
1009 {
1010   if (num_channels >= 1 && num_channels <= 6)   /* Mono up to & including 5.1 */
1011     return (guint8) num_channels;
1012   else if (num_channels == 8)   /* 7.1 */
1013     return (guint8) 7U;
1014   else
1015     return G_MAXUINT8;
1016 }
1017
1018 /**
1019  * gst_aac_parse_get_audio_sampling_frequency_index:
1020  * @sample_rate: audio sampling rate.
1021  *
1022  * Gets the Sampling Frequency Index value, as defined by table 1.18 in ISO/IEC
1023  * 14496-3, for a given sampling rate.
1024  *
1025  * Returns: the Sampling Frequency Index value corresponding to @sample_rate,
1026  * if such a value exists; otherwise G_MAXUINT8.
1027  */
1028 static guint8
1029 gst_aac_parse_get_audio_sampling_frequency_index (gint sample_rate)
1030 {
1031   switch (sample_rate) {
1032     case 96000:
1033       return 0x0U;
1034     case 88200:
1035       return 0x1U;
1036     case 64000:
1037       return 0x2U;
1038     case 48000:
1039       return 0x3U;
1040     case 44100:
1041       return 0x4U;
1042     case 32000:
1043       return 0x5U;
1044     case 24000:
1045       return 0x6U;
1046     case 22050:
1047       return 0x7U;
1048     case 16000:
1049       return 0x8U;
1050     case 12000:
1051       return 0x9U;
1052     case 11025:
1053       return 0xAU;
1054     case 8000:
1055       return 0xBU;
1056     case 7350:
1057       return 0xCU;
1058     default:
1059       return G_MAXUINT8;
1060   }
1061 }
1062
1063 /**
1064  * gst_aac_parse_prepend_adts_headers:
1065  * @aacparse: #GstAacParse.
1066  * @frame: raw AAC frame to which ADTS headers shall be prepended.
1067  *
1068  * Prepends ADTS headers to a raw AAC audio frame.
1069  *
1070  * Returns: TRUE if ADTS headers were successfully prepended; FALSE otherwise.
1071  */
1072 static gboolean
1073 gst_aac_parse_prepend_adts_headers (GstAacParse * aacparse,
1074     GstBaseParseFrame * frame)
1075 {
1076   GstMemory *mem;
1077   guint8 *adts_headers;
1078   gsize buf_size;
1079   gsize frame_size;
1080   guint8 id, profile, channel_configuration, sampling_frequency_index;
1081
1082   id = (aacparse->mpegversion == 4) ? 0x0U : 0x1U;
1083   profile = gst_aac_parse_get_audio_profile_object_type (aacparse);
1084   if (profile == G_MAXUINT8) {
1085     GST_ERROR_OBJECT (aacparse, "Unsupported audio profile or object type");
1086     return FALSE;
1087   }
1088   channel_configuration =
1089       gst_aac_parse_get_audio_channel_configuration (aacparse->channels);
1090   if (channel_configuration == G_MAXUINT8) {
1091     GST_ERROR_OBJECT (aacparse, "Unsupported number of channels");
1092     return FALSE;
1093   }
1094   sampling_frequency_index =
1095       gst_aac_parse_get_audio_sampling_frequency_index (aacparse->sample_rate);
1096   if (sampling_frequency_index == G_MAXUINT8) {
1097     GST_ERROR_OBJECT (aacparse, "Unsupported sampling frequency");
1098     return FALSE;
1099   }
1100
1101   frame->out_buffer = gst_buffer_copy (frame->buffer);
1102   buf_size = gst_buffer_get_size (frame->out_buffer);
1103   frame_size = buf_size + ADTS_HEADERS_LENGTH;
1104
1105   if (G_UNLIKELY (frame_size >= 0x4000)) {
1106     GST_ERROR_OBJECT (aacparse, "Frame size is too big for ADTS");
1107     return FALSE;
1108   }
1109
1110   adts_headers = (guint8 *) g_malloc0 (ADTS_HEADERS_LENGTH);
1111
1112   /* Note: no error correction bits are added to the resulting ADTS frames */
1113   adts_headers[0] = 0xFFU;
1114   adts_headers[1] = 0xF0U | (id << 3) | 0x1U;
1115   adts_headers[2] = (profile << 6) | (sampling_frequency_index << 2) | 0x2U |
1116       (channel_configuration & 0x4U);
1117   adts_headers[3] = ((channel_configuration & 0x3U) << 6) | 0x30U |
1118       (guint8) (frame_size >> 11);
1119   adts_headers[4] = (guint8) ((frame_size >> 3) & 0x00FF);
1120   adts_headers[5] = (guint8) (((frame_size & 0x0007) << 5) + 0x1FU);
1121   adts_headers[6] = 0xFCU;
1122
1123   mem = gst_memory_new_wrapped (0, adts_headers, ADTS_HEADERS_LENGTH, 0,
1124       ADTS_HEADERS_LENGTH, NULL, NULL);
1125   gst_buffer_prepend_memory (frame->out_buffer, mem);
1126
1127   return TRUE;
1128 }
1129
1130 /**
1131  * gst_aac_parse_check_valid_frame:
1132  * @parse: #GstBaseParse.
1133  * @frame: #GstBaseParseFrame.
1134  * @skipsize: How much data parent class should skip in order to find the
1135  *            frame header.
1136  *
1137  * Implementation of "handle_frame" vmethod in #GstBaseParse class.
1138  *
1139  * Also determines frame overhead.
1140  * ADTS streams have a 7 byte header in each frame. MP4 and ADIF streams don't have
1141  * a per-frame header. LOAS has 3 bytes.
1142  *
1143  * We're making a couple of simplifying assumptions:
1144  *
1145  * 1. We count Program Configuration Elements rather than searching for them
1146  *    in the streams to discount them - the overhead is negligible.
1147  *
1148  * 2. We ignore CRC. This has a worst-case impact of (num_raw_blocks + 1)*16
1149  *    bits, which should still not be significant enough to warrant the
1150  *    additional parsing through the headers
1151  *
1152  * Returns: a #GstFlowReturn.
1153  */
1154 static GstFlowReturn
1155 gst_aac_parse_handle_frame (GstBaseParse * parse,
1156     GstBaseParseFrame * frame, gint * skipsize)
1157 {
1158   GstMapInfo map;
1159   GstAacParse *aacparse;
1160   gboolean ret = FALSE;
1161   gboolean lost_sync;
1162   GstBuffer *buffer;
1163   guint framesize;
1164   gint rate, channels;
1165
1166   aacparse = GST_AAC_PARSE (parse);
1167   buffer = frame->buffer;
1168
1169   gst_buffer_map (buffer, &map, GST_MAP_READ);
1170
1171   *skipsize = -1;
1172   lost_sync = GST_BASE_PARSE_LOST_SYNC (parse);
1173
1174   if (aacparse->header_type == DSPAAC_HEADER_ADIF ||
1175       aacparse->header_type == DSPAAC_HEADER_NONE) {
1176     /* There is nothing to parse */
1177     framesize = map.size;
1178     ret = TRUE;
1179
1180   } else if (aacparse->header_type == DSPAAC_HEADER_NOT_PARSED || lost_sync) {
1181
1182     ret = gst_aac_parse_detect_stream (aacparse, map.data, map.size,
1183         GST_BASE_PARSE_DRAINING (parse), &framesize, skipsize);
1184
1185   } else if (aacparse->header_type == DSPAAC_HEADER_ADTS) {
1186     guint needed_data = 1024;
1187
1188     ret = gst_aac_parse_check_adts_frame (aacparse, map.data, map.size,
1189         GST_BASE_PARSE_DRAINING (parse), &framesize, &needed_data);
1190
1191     if (!ret) {
1192       GST_DEBUG ("buffer didn't contain valid frame");
1193       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
1194           needed_data);
1195     }
1196
1197   } else if (aacparse->header_type == DSPAAC_HEADER_LOAS) {
1198     guint needed_data = 1024;
1199
1200     ret = gst_aac_parse_check_loas_frame (aacparse, map.data,
1201         map.size, GST_BASE_PARSE_DRAINING (parse), &framesize, &needed_data);
1202
1203     if (!ret) {
1204       GST_DEBUG ("buffer didn't contain valid frame");
1205       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
1206           needed_data);
1207     }
1208
1209   } else {
1210     GST_DEBUG ("buffer didn't contain valid frame");
1211     gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
1212         ADTS_MAX_SIZE);
1213   }
1214
1215   if (G_UNLIKELY (!ret))
1216     goto exit;
1217
1218   if (aacparse->header_type == DSPAAC_HEADER_ADTS) {
1219     /* see above */
1220     frame->overhead = 7;
1221
1222     gst_aac_parse_parse_adts_header (aacparse, map.data,
1223         &rate, &channels, NULL, NULL);
1224
1225     GST_LOG_OBJECT (aacparse, "rate: %d, chans: %d", rate, channels);
1226
1227     if (G_UNLIKELY (rate != aacparse->sample_rate
1228             || channels != aacparse->channels)) {
1229       aacparse->sample_rate = rate;
1230       aacparse->channels = channels;
1231
1232       if (!gst_aac_parse_set_src_caps (aacparse, NULL)) {
1233         /* If linking fails, we need to return appropriate error */
1234         ret = GST_FLOW_NOT_LINKED;
1235       }
1236
1237       gst_base_parse_set_frame_rate (GST_BASE_PARSE (aacparse),
1238           aacparse->sample_rate, aacparse->frame_samples, 2, 2);
1239     }
1240   } else if (aacparse->header_type == DSPAAC_HEADER_LOAS) {
1241     gboolean setcaps = FALSE;
1242
1243     /* see above */
1244     frame->overhead = 3;
1245
1246     if (!gst_aac_parse_read_loas_config (aacparse, map.data, map.size, &rate,
1247             &channels, NULL)) {
1248       GST_WARNING_OBJECT (aacparse, "Error reading LOAS config");
1249     } else if (G_UNLIKELY (rate != aacparse->sample_rate
1250             || channels != aacparse->channels)) {
1251       aacparse->sample_rate = rate;
1252       aacparse->channels = channels;
1253       setcaps = TRUE;
1254       GST_INFO_OBJECT (aacparse, "New LOAS config: %d Hz, %d channels", rate,
1255           channels);
1256     }
1257
1258     /* We want to set caps both at start, and when rate/channels change.
1259        Since only some LOAS frames have that info, we may receive frames
1260        before knowing about rate/channels. */
1261     if (setcaps
1262         || !gst_pad_has_current_caps (GST_BASE_PARSE_SRC_PAD (aacparse))) {
1263       if (!gst_aac_parse_set_src_caps (aacparse, NULL)) {
1264         /* If linking fails, we need to return appropriate error */
1265         ret = GST_FLOW_NOT_LINKED;
1266       }
1267
1268       gst_base_parse_set_frame_rate (GST_BASE_PARSE (aacparse),
1269           aacparse->sample_rate, aacparse->frame_samples, 2, 2);
1270     }
1271   }
1272
1273   if (aacparse->header_type == DSPAAC_HEADER_NONE
1274       && aacparse->output_header_type == DSPAAC_HEADER_ADTS) {
1275     if (!gst_aac_parse_prepend_adts_headers (aacparse, frame)) {
1276       GST_ERROR_OBJECT (aacparse, "Failed to prepend ADTS headers to frame");
1277       ret = GST_FLOW_ERROR;
1278     }
1279   }
1280
1281 exit:
1282   gst_buffer_unmap (buffer, &map);
1283
1284   if (ret) {
1285     /* found, skip if needed */
1286     if (*skipsize > 0)
1287       return GST_FLOW_OK;
1288     *skipsize = 0;
1289   } else {
1290     if (*skipsize < 0)
1291       *skipsize = 1;
1292   }
1293
1294   if (ret && framesize <= map.size) {
1295     return gst_base_parse_finish_frame (parse, frame, framesize);
1296   }
1297
1298   return GST_FLOW_OK;
1299 }
1300
1301 static GstFlowReturn
1302 gst_aac_parse_pre_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1303 {
1304   GstAacParse *aacparse = GST_AAC_PARSE (parse);
1305
1306   if (!aacparse->sent_codec_tag) {
1307     GstTagList *taglist;
1308     GstCaps *caps;
1309
1310     taglist = gst_tag_list_new_empty ();
1311
1312     /* codec tag */
1313     caps = gst_pad_get_current_caps (GST_BASE_PARSE_SRC_PAD (parse));
1314     gst_pb_utils_add_codec_description_to_tag_list (taglist,
1315         GST_TAG_AUDIO_CODEC, caps);
1316     gst_caps_unref (caps);
1317
1318     gst_pad_push_event (GST_BASE_PARSE_SRC_PAD (aacparse),
1319         gst_event_new_tag (taglist));
1320
1321     /* also signals the end of first-frame processing */
1322     aacparse->sent_codec_tag = TRUE;
1323   }
1324
1325   /* As a special case, we can remove the ADTS framing and output raw AAC. */
1326   if (aacparse->header_type == DSPAAC_HEADER_ADTS
1327       && aacparse->output_header_type == DSPAAC_HEADER_NONE) {
1328     guint header_size;
1329     GstMapInfo map;
1330     gst_buffer_map (frame->buffer, &map, GST_MAP_READ);
1331     header_size = (map.data[1] & 1) ? 7 : 9;    /* optional CRC */
1332     gst_buffer_unmap (frame->buffer, &map);
1333     gst_buffer_resize (frame->buffer, header_size,
1334         gst_buffer_get_size (frame->buffer) - header_size);
1335   }
1336
1337   return GST_FLOW_OK;
1338 }
1339
1340
1341 /**
1342  * gst_aac_parse_start:
1343  * @parse: #GstBaseParse.
1344  *
1345  * Implementation of "start" vmethod in #GstBaseParse class.
1346  *
1347  * Returns: TRUE if startup succeeded.
1348  */
1349 static gboolean
1350 gst_aac_parse_start (GstBaseParse * parse)
1351 {
1352   GstAacParse *aacparse;
1353
1354   aacparse = GST_AAC_PARSE (parse);
1355   GST_DEBUG ("start");
1356   aacparse->frame_samples = 1024;
1357   gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse), ADTS_MAX_SIZE);
1358   aacparse->sent_codec_tag = FALSE;
1359   return TRUE;
1360 }
1361
1362
1363 /**
1364  * gst_aac_parse_stop:
1365  * @parse: #GstBaseParse.
1366  *
1367  * Implementation of "stop" vmethod in #GstBaseParse class.
1368  *
1369  * Returns: TRUE is stopping succeeded.
1370  */
1371 static gboolean
1372 gst_aac_parse_stop (GstBaseParse * parse)
1373 {
1374   GST_DEBUG ("stop");
1375   return TRUE;
1376 }
1377
1378 static void
1379 remove_fields (GstCaps * caps)
1380 {
1381   guint i, n;
1382
1383   n = gst_caps_get_size (caps);
1384   for (i = 0; i < n; i++) {
1385     GstStructure *s = gst_caps_get_structure (caps, i);
1386
1387     gst_structure_remove_field (s, "framed");
1388   }
1389 }
1390
1391 static GstCaps *
1392 gst_aac_parse_sink_getcaps (GstBaseParse * parse, GstCaps * filter)
1393 {
1394   GstCaps *peercaps, *templ;
1395   GstCaps *res;
1396
1397   templ = gst_pad_get_pad_template_caps (GST_BASE_PARSE_SINK_PAD (parse));
1398
1399   if (filter) {
1400     GstCaps *fcopy = gst_caps_copy (filter);
1401     /* Remove the fields we convert */
1402     remove_fields (fcopy);
1403     peercaps = gst_pad_peer_query_caps (GST_BASE_PARSE_SRC_PAD (parse), fcopy);
1404     gst_caps_unref (fcopy);
1405   } else
1406     peercaps = gst_pad_peer_query_caps (GST_BASE_PARSE_SRC_PAD (parse), NULL);
1407
1408   if (peercaps) {
1409     peercaps = gst_caps_make_writable (peercaps);
1410     /* Remove the fields we convert */
1411     remove_fields (peercaps);
1412
1413     res = gst_caps_intersect_full (peercaps, templ, GST_CAPS_INTERSECT_FIRST);
1414     gst_caps_unref (peercaps);
1415     gst_caps_unref (templ);
1416   } else {
1417     res = templ;
1418   }
1419
1420   if (filter) {
1421     GstCaps *intersection;
1422
1423     intersection =
1424         gst_caps_intersect_full (filter, res, GST_CAPS_INTERSECT_FIRST);
1425     gst_caps_unref (res);
1426     res = intersection;
1427   }
1428
1429   return res;
1430 }