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