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