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