aacparse: Fix svace issue(DIVISION_BY_ZERO)
[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 #ifdef TIZEN_FEATURE_AACPARSE_MODIFICATION /* to get more accurate duration */
77 #define AAC_MAX_ESTIMATE_DURATION_BUF (1024 * 1024) /* use first 1 Mbyte */
78 #define AAC_SAMPLE_PER_FRAME 1024
79
80 #define AAC_MAX_PULL_RANGE_BUF  (1 * 1024 * 1024)   /* 1 MByte */
81 #define AAC_LARGE_FILE_SIZE     (2 * 1024 * 1024)    /* 2 MByte */
82 #define gst_aac_parse_parent_class parent_class
83 #endif
84
85 #define AAC_FRAME_DURATION(parse) (GST_SECOND/parse->frames_per_sec)
86
87 static const gint loas_sample_rate_table[32] = {
88   96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
89   16000, 12000, 11025, 8000, 7350, 0, 0, 0
90 };
91
92 static const gint loas_channels_table[32] = {
93   0, 1, 2, 3, 4, 5, 6, 8,
94   0, 0, 0, 7, 8, 0, 8, 0
95 };
96
97 static gboolean gst_aac_parse_start (GstBaseParse * parse);
98 static gboolean gst_aac_parse_stop (GstBaseParse * parse);
99
100 static gboolean gst_aac_parse_sink_setcaps (GstBaseParse * parse,
101     GstCaps * caps);
102 static GstCaps *gst_aac_parse_sink_getcaps (GstBaseParse * parse,
103     GstCaps * filter);
104
105 static GstFlowReturn gst_aac_parse_handle_frame (GstBaseParse * parse,
106     GstBaseParseFrame * frame, gint * skipsize);
107 static GstFlowReturn gst_aac_parse_pre_push_frame (GstBaseParse * parse,
108     GstBaseParseFrame * frame);
109
110 #ifdef TIZEN_FEATURE_AACPARSE_MODIFICATION
111 static guint gst_aac_parse_adts_get_fast_frame_len (const guint8 * data);
112 static gboolean gst_aac_parse_src_eventfunc(GstBaseParse * parse,
113     GstEvent * event);
114 /* make full aac(adts) index table when seek */
115 static gboolean gst_aac_parse_adts_src_eventfunc (GstBaseParse * parse,
116     GstEvent * event);
117 int get_aac_parse_get_adts_frame_length (const unsigned char* data,
118     gint64 offset);
119 static gboolean gst_aac_parse_estimate_duration (GstBaseParse * parse);
120 #endif
121
122 G_DEFINE_TYPE (GstAacParse, gst_aac_parse, GST_TYPE_BASE_PARSE);
123
124 #ifdef TIZEN_FEATURE_AACPARSE_MODIFICATION
125 static inline gint
126 gst_aac_parse_get_sample_rate_from_index (guint sr_idx)
127 {
128   static const guint aac_sample_rates[] = { 96000, 88200, 64000, 48000, 44100,
129     32000, 24000, 22050, 16000, 12000, 11025, 8000
130   };
131
132   if (sr_idx < G_N_ELEMENTS (aac_sample_rates))
133     return aac_sample_rates[sr_idx];
134   GST_WARNING ("Invalid sample rate index %u", sr_idx);
135   return 0;
136 }
137 #endif
138 /**
139  * gst_aac_parse_class_init:
140  * @klass: #GstAacParseClass.
141  *
142  */
143 static void
144 gst_aac_parse_class_init (GstAacParseClass * klass)
145 {
146   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
147   GstBaseParseClass *parse_class = GST_BASE_PARSE_CLASS (klass);
148
149   GST_DEBUG_CATEGORY_INIT (aacparse_debug, "aacparse", 0,
150       "AAC audio stream parser");
151
152   gst_element_class_add_pad_template (element_class,
153       gst_static_pad_template_get (&sink_template));
154   gst_element_class_add_pad_template (element_class,
155       gst_static_pad_template_get (&src_template));
156
157   gst_element_class_set_static_metadata (element_class,
158       "AAC audio stream parser", "Codec/Parser/Audio",
159       "Advanced Audio Coding parser", "Stefan Kost <stefan.kost@nokia.com>");
160
161   parse_class->start = GST_DEBUG_FUNCPTR (gst_aac_parse_start);
162   parse_class->stop = GST_DEBUG_FUNCPTR (gst_aac_parse_stop);
163   parse_class->set_sink_caps = GST_DEBUG_FUNCPTR (gst_aac_parse_sink_setcaps);
164   parse_class->get_sink_caps = GST_DEBUG_FUNCPTR (gst_aac_parse_sink_getcaps);
165   parse_class->handle_frame = GST_DEBUG_FUNCPTR (gst_aac_parse_handle_frame);
166   parse_class->pre_push_frame =
167       GST_DEBUG_FUNCPTR (gst_aac_parse_pre_push_frame);
168 #ifdef TIZEN_FEATURE_AACPARSE_MODIFICATION
169   /* make full aac(adts) index table when seek */
170   parse_class->src_event = GST_DEBUG_FUNCPTR (gst_aac_parse_src_eventfunc);
171 #endif
172 }
173
174
175 /**
176  * gst_aac_parse_init:
177  * @aacparse: #GstAacParse.
178  * @klass: #GstAacParseClass.
179  *
180  */
181 static void
182 gst_aac_parse_init (GstAacParse * aacparse)
183 {
184   GST_DEBUG ("initialized");
185   GST_PAD_SET_ACCEPT_INTERSECT (GST_BASE_PARSE_SINK_PAD (aacparse));
186   GST_PAD_SET_ACCEPT_TEMPLATE (GST_BASE_PARSE_SINK_PAD (aacparse));
187 #ifdef TIZEN_FEATURE_AACPARSE_MODIFICATION
188   /* to get more correct duration */
189   aacparse->first_frame = TRUE;
190 #endif
191 }
192
193
194 /**
195  * gst_aac_parse_set_src_caps:
196  * @aacparse: #GstAacParse.
197  * @sink_caps: (proposed) caps of sink pad
198  *
199  * Set source pad caps according to current knowledge about the
200  * audio stream.
201  *
202  * Returns: TRUE if caps were successfully set.
203  */
204 static gboolean
205 gst_aac_parse_set_src_caps (GstAacParse * aacparse, GstCaps * sink_caps)
206 {
207   GstStructure *s;
208   GstCaps *src_caps = NULL, *allowed;
209   gboolean res = FALSE;
210   const gchar *stream_format;
211   guint8 codec_data[2];
212   guint16 codec_data_data;
213   gint sample_rate_idx;
214
215   GST_DEBUG_OBJECT (aacparse, "sink caps: %" GST_PTR_FORMAT, sink_caps);
216   if (sink_caps)
217     src_caps = gst_caps_copy (sink_caps);
218   else
219     src_caps = gst_caps_new_empty_simple ("audio/mpeg");
220
221   gst_caps_set_simple (src_caps, "framed", G_TYPE_BOOLEAN, TRUE,
222       "mpegversion", G_TYPE_INT, aacparse->mpegversion, NULL);
223
224   aacparse->output_header_type = aacparse->header_type;
225   switch (aacparse->header_type) {
226     case DSPAAC_HEADER_NONE:
227       stream_format = "raw";
228       break;
229     case DSPAAC_HEADER_ADTS:
230       stream_format = "adts";
231       break;
232     case DSPAAC_HEADER_ADIF:
233       stream_format = "adif";
234       break;
235     case DSPAAC_HEADER_LOAS:
236       stream_format = "loas";
237       break;
238     default:
239       stream_format = NULL;
240   }
241
242   /* Generate codec data to be able to set profile/level on the caps */
243   sample_rate_idx =
244       gst_codec_utils_aac_get_index_from_sample_rate (aacparse->sample_rate);
245   if (sample_rate_idx < 0)
246     goto not_a_known_rate;
247   codec_data_data =
248       (aacparse->object_type << 11) |
249       (sample_rate_idx << 7) | (aacparse->channels << 3);
250   GST_WRITE_UINT16_BE (codec_data, codec_data_data);
251   gst_codec_utils_aac_caps_set_level_and_profile (src_caps, codec_data, 2);
252
253   s = gst_caps_get_structure (src_caps, 0);
254   if (aacparse->sample_rate > 0)
255     gst_structure_set (s, "rate", G_TYPE_INT, aacparse->sample_rate, NULL);
256   if (aacparse->channels > 0)
257     gst_structure_set (s, "channels", G_TYPE_INT, aacparse->channels, NULL);
258   if (stream_format)
259     gst_structure_set (s, "stream-format", G_TYPE_STRING, stream_format, NULL);
260
261   allowed = gst_pad_get_allowed_caps (GST_BASE_PARSE (aacparse)->srcpad);
262   if (allowed && !gst_caps_can_intersect (src_caps, allowed)) {
263     GST_DEBUG_OBJECT (GST_BASE_PARSE (aacparse)->srcpad,
264         "Caps can not intersect");
265     if (aacparse->header_type == DSPAAC_HEADER_ADTS) {
266       GST_DEBUG_OBJECT (GST_BASE_PARSE (aacparse)->srcpad,
267           "Input is ADTS, trying raw");
268       gst_caps_set_simple (src_caps, "stream-format", G_TYPE_STRING, "raw",
269           NULL);
270       if (gst_caps_can_intersect (src_caps, allowed)) {
271         GstBuffer *codec_data_buffer;
272
273         GST_DEBUG_OBJECT (GST_BASE_PARSE (aacparse)->srcpad,
274             "Caps can intersect, we will drop the ADTS layer");
275         aacparse->output_header_type = DSPAAC_HEADER_NONE;
276
277         /* The codec_data data is according to AudioSpecificConfig,
278            ISO/IEC 14496-3, 1.6.2.1 */
279         codec_data_buffer = gst_buffer_new_and_alloc (2);
280         gst_buffer_fill (codec_data_buffer, 0, codec_data, 2);
281         gst_caps_set_simple (src_caps, "codec_data", GST_TYPE_BUFFER,
282             codec_data_buffer, NULL);
283       }
284     } else if (aacparse->header_type == DSPAAC_HEADER_NONE) {
285       GST_DEBUG_OBJECT (GST_BASE_PARSE (aacparse)->srcpad,
286           "Input is raw, trying ADTS");
287       gst_caps_set_simple (src_caps, "stream-format", G_TYPE_STRING, "adts",
288           NULL);
289       if (gst_caps_can_intersect (src_caps, allowed)) {
290         GST_DEBUG_OBJECT (GST_BASE_PARSE (aacparse)->srcpad,
291             "Caps can intersect, we will prepend ADTS headers");
292         aacparse->output_header_type = DSPAAC_HEADER_ADTS;
293       }
294     }
295   }
296   if (allowed)
297     gst_caps_unref (allowed);
298
299   GST_DEBUG_OBJECT (aacparse, "setting src caps: %" GST_PTR_FORMAT, src_caps);
300
301   res = gst_pad_set_caps (GST_BASE_PARSE (aacparse)->srcpad, src_caps);
302   gst_caps_unref (src_caps);
303   return res;
304
305 not_a_known_rate:
306   GST_ERROR_OBJECT (aacparse, "Not a known sample rate: %d",
307       aacparse->sample_rate);
308   gst_caps_unref (src_caps);
309   return FALSE;
310 }
311
312
313 /**
314  * gst_aac_parse_sink_setcaps:
315  * @sinkpad: GstPad
316  * @caps: GstCaps
317  *
318  * Implementation of "set_sink_caps" vmethod in #GstBaseParse class.
319  *
320  * Returns: TRUE on success.
321  */
322 static gboolean
323 gst_aac_parse_sink_setcaps (GstBaseParse * parse, GstCaps * caps)
324 {
325   GstAacParse *aacparse;
326   GstStructure *structure;
327   gchar *caps_str;
328   const GValue *value;
329
330   aacparse = GST_AAC_PARSE (parse);
331   structure = gst_caps_get_structure (caps, 0);
332   caps_str = gst_caps_to_string (caps);
333
334   GST_DEBUG_OBJECT (aacparse, "setcaps: %s", caps_str);
335   g_free (caps_str);
336
337   /* This is needed at least in case of RTP
338    * Parses the codec_data information to get ObjectType,
339    * number of channels and samplerate */
340   value = gst_structure_get_value (structure, "codec_data");
341   if (value) {
342     GstBuffer *buf = gst_value_get_buffer (value);
343
344     if (buf) {
345       GstMapInfo map;
346       guint sr_idx;
347
348       gst_buffer_map (buf, &map, GST_MAP_READ);
349
350       sr_idx = ((map.data[0] & 0x07) << 1) | ((map.data[1] & 0x80) >> 7);
351       aacparse->object_type = (map.data[0] & 0xf8) >> 3;
352       aacparse->sample_rate =
353           gst_codec_utils_aac_get_sample_rate_from_index (sr_idx);
354       aacparse->channels = (map.data[1] & 0x78) >> 3;
355       if (aacparse->channels == 7)
356         aacparse->channels = 8;
357       else if (aacparse->channels == 11)
358         aacparse->channels = 7;
359       else if (aacparse->channels == 12 || aacparse->channels == 14)
360         aacparse->channels = 8;
361       aacparse->header_type = DSPAAC_HEADER_NONE;
362       aacparse->mpegversion = 4;
363       aacparse->frame_samples = (map.data[1] & 4) ? 960 : 1024;
364       gst_buffer_unmap (buf, &map);
365
366       GST_DEBUG ("codec_data: object_type=%d, sample_rate=%d, channels=%d, "
367           "samples=%d", aacparse->object_type, aacparse->sample_rate,
368           aacparse->channels, aacparse->frame_samples);
369
370       /* arrange for metadata and get out of the way */
371       gst_aac_parse_set_src_caps (aacparse, caps);
372       if (aacparse->header_type == aacparse->output_header_type)
373         gst_base_parse_set_passthrough (parse, TRUE);
374     } else
375       return FALSE;
376
377     /* caps info overrides */
378     gst_structure_get_int (structure, "rate", &aacparse->sample_rate);
379     gst_structure_get_int (structure, "channels", &aacparse->channels);
380   } else {
381     aacparse->sample_rate = 0;
382     aacparse->channels = 0;
383     aacparse->header_type = DSPAAC_HEADER_NOT_PARSED;
384     gst_base_parse_set_passthrough (parse, FALSE);
385   }
386
387   return TRUE;
388 }
389
390
391 /**
392  * gst_aac_parse_adts_get_frame_len:
393  * @data: block of data containing an ADTS header.
394  *
395  * This function calculates ADTS frame length from the given header.
396  *
397  * Returns: size of the ADTS frame.
398  */
399 static inline guint
400 gst_aac_parse_adts_get_frame_len (const guint8 * data)
401 {
402   return ((data[3] & 0x03) << 11) | (data[4] << 3) | ((data[5] & 0xe0) >> 5);
403 }
404
405
406 /**
407  * gst_aac_parse_check_adts_frame:
408  * @aacparse: #GstAacParse.
409  * @data: Data to be checked.
410  * @avail: Amount of data passed.
411  * @framesize: If valid ADTS frame was found, this will be set to tell the
412  *             found frame size in bytes.
413  * @needed_data: If frame was not found, this may be set to tell how much
414  *               more data is needed in the next round to detect the frame
415  *               reliably. This may happen when a frame header candidate
416  *               is found but it cannot be guaranteed to be the header without
417  *               peeking the following data.
418  *
419  * Check if the given data contains contains ADTS frame. The algorithm
420  * will examine ADTS frame header and calculate the frame size. Also, another
421  * consecutive ADTS frame header need to be present after the found frame.
422  * Otherwise the data is not considered as a valid ADTS frame. However, this
423  * "extra check" is omitted when EOS has been received. In this case it is
424  * enough when data[0] contains a valid ADTS header.
425  *
426  * This function may set the #needed_data to indicate that a possible frame
427  * candidate has been found, but more data (#needed_data bytes) is needed to
428  * be absolutely sure. When this situation occurs, FALSE will be returned.
429  *
430  * When a valid frame is detected, this function will use
431  * gst_base_parse_set_min_frame_size() function from #GstBaseParse class
432  * to set the needed bytes for next frame.This way next data chunk is already
433  * of correct size.
434  *
435  * Returns: TRUE if the given data contains a valid ADTS header.
436  */
437 static gboolean
438 gst_aac_parse_check_adts_frame (GstAacParse * aacparse,
439     const guint8 * data, const guint avail, gboolean drain,
440     guint * framesize, guint * needed_data)
441 {
442   guint crc_size;
443
444   *needed_data = 0;
445
446   /* Absolute minimum to perform the ADTS syncword,
447      layer and sampling frequency tests */
448   if (G_UNLIKELY (avail < 3)) {
449     *needed_data = 3;
450     return FALSE;
451   }
452
453   /* Syncword and layer tests */
454   if ((data[0] == 0xff) && ((data[1] & 0xf6) == 0xf0)) {
455
456     /* Sampling frequency test */
457     if (G_UNLIKELY ((data[2] & 0x3C) >> 2 == 15))
458       return FALSE;
459
460     /* This looks like an ADTS frame header but
461        we need at least 6 bytes to proceed */
462     if (G_UNLIKELY (avail < 6)) {
463       *needed_data = 6;
464       return FALSE;
465     }
466
467     *framesize = gst_aac_parse_adts_get_frame_len (data);
468
469     /* If frame has CRC, it needs 2 bytes
470        for it at the end of the header */
471     crc_size = (data[1] & 0x01) ? 0 : 2;
472
473     /* CRC size test */
474     if (*framesize < 7 + crc_size) {
475       *needed_data = 7 + crc_size;
476       return FALSE;
477     }
478
479     /* In EOS mode this is enough. No need to examine the data further.
480        We also relax the check when we have sync, on the assumption that
481        if we're not looking at random data, we have a much higher chance
482        to get the correct sync, and this avoids losing two frames when
483        a single bit corruption happens. */
484     if (drain || !GST_BASE_PARSE_LOST_SYNC (aacparse)) {
485       return TRUE;
486     }
487
488     if (*framesize + ADTS_MAX_SIZE > avail) {
489       /* We have found a possible frame header candidate, but can't be
490          sure since we don't have enough data to check the next frame */
491       GST_DEBUG ("NEED MORE DATA: we need %d, available %d",
492           *framesize + ADTS_MAX_SIZE, avail);
493       *needed_data = *framesize + ADTS_MAX_SIZE;
494       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
495           *framesize + ADTS_MAX_SIZE);
496       return FALSE;
497     }
498
499     if ((data[*framesize] == 0xff) && ((data[*framesize + 1] & 0xf6) == 0xf0)) {
500       guint nextlen = gst_aac_parse_adts_get_frame_len (data + (*framesize));
501
502       GST_LOG ("ADTS frame found, len: %d bytes", *framesize);
503       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
504           nextlen + ADTS_MAX_SIZE);
505       return TRUE;
506     }
507   }
508   return FALSE;
509 }
510
511 static gboolean
512 gst_aac_parse_latm_get_value (GstAacParse * aacparse, GstBitReader * br,
513     guint32 * value)
514 {
515   guint8 bytes, i, byte;
516
517   *value = 0;
518   if (!gst_bit_reader_get_bits_uint8 (br, &bytes, 2))
519     return FALSE;
520   for (i = 0; i < bytes; ++i) {
521     *value <<= 8;
522     if (!gst_bit_reader_get_bits_uint8 (br, &byte, 8))
523       return FALSE;
524     *value += byte;
525   }
526   return TRUE;
527 }
528
529 static gboolean
530 gst_aac_parse_get_audio_object_type (GstAacParse * aacparse, GstBitReader * br,
531     guint8 * audio_object_type)
532 {
533   if (!gst_bit_reader_get_bits_uint8 (br, audio_object_type, 5))
534     return FALSE;
535   if (*audio_object_type == 31) {
536     if (!gst_bit_reader_get_bits_uint8 (br, audio_object_type, 6))
537       return FALSE;
538     *audio_object_type += 32;
539   }
540   GST_LOG_OBJECT (aacparse, "audio object type %u", *audio_object_type);
541   return TRUE;
542 }
543
544 static gboolean
545 gst_aac_parse_get_audio_sample_rate (GstAacParse * aacparse, GstBitReader * br,
546     gint * sample_rate)
547 {
548   guint8 sampling_frequency_index;
549   if (!gst_bit_reader_get_bits_uint8 (br, &sampling_frequency_index, 4))
550     return FALSE;
551   GST_LOG_OBJECT (aacparse, "sampling_frequency_index: %u",
552       sampling_frequency_index);
553   if (sampling_frequency_index == 0xf) {
554     guint32 sampling_rate;
555     if (!gst_bit_reader_get_bits_uint32 (br, &sampling_rate, 24))
556       return FALSE;
557     *sample_rate = sampling_rate;
558   } else {
559     *sample_rate = loas_sample_rate_table[sampling_frequency_index];
560     if (!*sample_rate)
561       return FALSE;
562   }
563   return TRUE;
564 }
565
566 /* See table 1.13 in ISO/IEC 14496-3 */
567 static gboolean
568 gst_aac_parse_read_loas_audio_specific_config (GstAacParse * aacparse,
569     GstBitReader * br, gint * sample_rate, gint * channels, guint32 * bits)
570 {
571   guint8 audio_object_type, channel_configuration;
572
573   if (!gst_aac_parse_get_audio_object_type (aacparse, br, &audio_object_type))
574     return FALSE;
575
576   if (!gst_aac_parse_get_audio_sample_rate (aacparse, br, sample_rate))
577     return FALSE;
578
579   if (!gst_bit_reader_get_bits_uint8 (br, &channel_configuration, 4))
580     return FALSE;
581   GST_LOG_OBJECT (aacparse, "channel_configuration: %d", channel_configuration);
582   *channels = loas_channels_table[channel_configuration];
583   if (!*channels)
584     return FALSE;
585
586   if (audio_object_type == 5) {
587     GST_LOG_OBJECT (aacparse,
588         "Audio object type 5, so rereading sampling rate...");
589     if (!gst_aac_parse_get_audio_sample_rate (aacparse, br, sample_rate))
590       return FALSE;
591   }
592
593   GST_INFO_OBJECT (aacparse, "Found LOAS config: %d Hz, %d channels",
594       *sample_rate, *channels);
595
596   /* There's LOTS of stuff next, but we ignore it for now as we have
597      what we want (sample rate and number of channels */
598   GST_DEBUG_OBJECT (aacparse,
599       "Need more code to parse humongous LOAS data, currently ignored");
600   if (bits)
601     *bits = 0;
602   return TRUE;
603 }
604
605
606 static gboolean
607 gst_aac_parse_read_loas_config (GstAacParse * aacparse, const guint8 * data,
608     guint avail, gint * sample_rate, gint * channels, gint * version)
609 {
610   GstBitReader br;
611   guint8 u8, v, vA;
612
613   /* No version in the bitstream, but the spec has LOAS in the MPEG-4 section */
614   if (version)
615     *version = 4;
616
617   gst_bit_reader_init (&br, data, avail);
618
619   /* skip sync word (11 bits) and size (13 bits) */
620   if (!gst_bit_reader_skip (&br, 11 + 13))
621     return FALSE;
622
623   /* First bit is "use last config" */
624   if (!gst_bit_reader_get_bits_uint8 (&br, &u8, 1))
625     return FALSE;
626   if (u8) {
627     GST_LOG_OBJECT (aacparse, "Frame uses previous config");
628     if (!aacparse->sample_rate || !aacparse->channels) {
629       GST_DEBUG_OBJECT (aacparse,
630           "No previous config to use. We'll look for more data.");
631       return FALSE;
632     }
633     *sample_rate = aacparse->sample_rate;
634     *channels = aacparse->channels;
635     return TRUE;
636   }
637
638   GST_DEBUG_OBJECT (aacparse, "Frame contains new config");
639
640   if (!gst_bit_reader_get_bits_uint8 (&br, &v, 1))
641     return FALSE;
642   if (v) {
643     if (!gst_bit_reader_get_bits_uint8 (&br, &vA, 1))
644       return FALSE;
645   } else
646     vA = 0;
647
648   GST_LOG_OBJECT (aacparse, "v %d, vA %d", v, vA);
649   if (vA == 0) {
650     guint8 same_time, subframes, num_program, prog;
651     if (v == 1) {
652       guint32 value;
653       if (!gst_aac_parse_latm_get_value (aacparse, &br, &value))
654         return FALSE;
655     }
656     if (!gst_bit_reader_get_bits_uint8 (&br, &same_time, 1))
657       return FALSE;
658     if (!gst_bit_reader_get_bits_uint8 (&br, &subframes, 6))
659       return FALSE;
660     if (!gst_bit_reader_get_bits_uint8 (&br, &num_program, 4))
661       return FALSE;
662     GST_LOG_OBJECT (aacparse, "same_time %d, subframes %d, num_program %d",
663         same_time, subframes, num_program);
664
665     for (prog = 0; prog <= num_program; ++prog) {
666       guint8 num_layer, layer;
667       if (!gst_bit_reader_get_bits_uint8 (&br, &num_layer, 3))
668         return FALSE;
669       GST_LOG_OBJECT (aacparse, "Program %d: %d layers", prog, num_layer);
670
671       for (layer = 0; layer <= num_layer; ++layer) {
672         guint8 use_same_config;
673         if (prog == 0 && layer == 0) {
674           use_same_config = 0;
675         } else {
676           if (!gst_bit_reader_get_bits_uint8 (&br, &use_same_config, 1))
677             return FALSE;
678         }
679         if (!use_same_config) {
680           if (v == 0) {
681             if (!gst_aac_parse_read_loas_audio_specific_config (aacparse, &br,
682                     sample_rate, channels, NULL))
683               return FALSE;
684           } else {
685             guint32 bits, asc_len;
686             if (!gst_aac_parse_latm_get_value (aacparse, &br, &asc_len))
687               return FALSE;
688             if (!gst_aac_parse_read_loas_audio_specific_config (aacparse, &br,
689                     sample_rate, channels, &bits))
690               return FALSE;
691             asc_len -= bits;
692             if (!gst_bit_reader_skip (&br, asc_len))
693               return FALSE;
694           }
695         }
696       }
697     }
698     GST_LOG_OBJECT (aacparse, "More data ignored");
699   } else {
700     GST_WARNING_OBJECT (aacparse, "Spec says \"TBD\"...");
701     return FALSE;
702   }
703   return TRUE;
704 }
705
706 /**
707  * gst_aac_parse_loas_get_frame_len:
708  * @data: block of data containing a LOAS header.
709  *
710  * This function calculates LOAS frame length from the given header.
711  *
712  * Returns: size of the LOAS frame.
713  */
714 static inline guint
715 gst_aac_parse_loas_get_frame_len (const guint8 * data)
716 {
717   return (((data[1] & 0x1f) << 8) | data[2]) + 3;
718 }
719
720
721 /**
722  * gst_aac_parse_check_loas_frame:
723  * @aacparse: #GstAacParse.
724  * @data: Data to be checked.
725  * @avail: Amount of data passed.
726  * @framesize: If valid LOAS frame was found, this will be set to tell the
727  *             found frame size in bytes.
728  * @needed_data: If frame was not found, this may be set to tell how much
729  *               more data is needed in the next round to detect the frame
730  *               reliably. This may happen when a frame header candidate
731  *               is found but it cannot be guaranteed to be the header without
732  *               peeking the following data.
733  *
734  * Check if the given data contains contains LOAS frame. The algorithm
735  * will examine LOAS frame header and calculate the frame size. Also, another
736  * consecutive LOAS frame header need to be present after the found frame.
737  * Otherwise the data is not considered as a valid LOAS frame. However, this
738  * "extra check" is omitted when EOS has been received. In this case it is
739  * enough when data[0] contains a valid LOAS header.
740  *
741  * This function may set the #needed_data to indicate that a possible frame
742  * candidate has been found, but more data (#needed_data bytes) is needed to
743  * be absolutely sure. When this situation occurs, FALSE will be returned.
744  *
745  * When a valid frame is detected, this function will use
746  * gst_base_parse_set_min_frame_size() function from #GstBaseParse class
747  * to set the needed bytes for next frame.This way next data chunk is already
748  * of correct size.
749  *
750  * LOAS can have three different formats, if I read the spec correctly. Only
751  * one of them is supported here, as the two samples I have use this one.
752  *
753  * Returns: TRUE if the given data contains a valid LOAS header.
754  */
755 static gboolean
756 gst_aac_parse_check_loas_frame (GstAacParse * aacparse,
757     const guint8 * data, const guint avail, gboolean drain,
758     guint * framesize, guint * needed_data)
759 {
760   *needed_data = 0;
761
762   /* 3 byte header */
763   if (G_UNLIKELY (avail < 3)) {
764     *needed_data = 3;
765     return FALSE;
766   }
767
768   if ((data[0] == 0x56) && ((data[1] & 0xe0) == 0xe0)) {
769     *framesize = gst_aac_parse_loas_get_frame_len (data);
770     GST_DEBUG_OBJECT (aacparse, "Found %u byte LOAS frame", *framesize);
771
772     /* In EOS mode this is enough. No need to examine the data further.
773        We also relax the check when we have sync, on the assumption that
774        if we're not looking at random data, we have a much higher chance
775        to get the correct sync, and this avoids losing two frames when
776        a single bit corruption happens. */
777     if (drain || !GST_BASE_PARSE_LOST_SYNC (aacparse)) {
778       return TRUE;
779     }
780
781     if (*framesize + LOAS_MAX_SIZE > avail) {
782       /* We have found a possible frame header candidate, but can't be
783          sure since we don't have enough data to check the next frame */
784       GST_DEBUG ("NEED MORE DATA: we need %d, available %d",
785           *framesize + LOAS_MAX_SIZE, avail);
786       *needed_data = *framesize + LOAS_MAX_SIZE;
787       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
788           *framesize + LOAS_MAX_SIZE);
789       return FALSE;
790     }
791
792     if ((data[*framesize] == 0x56) && ((data[*framesize + 1] & 0xe0) == 0xe0)) {
793       guint nextlen = gst_aac_parse_loas_get_frame_len (data + (*framesize));
794
795       GST_LOG ("LOAS frame found, len: %d bytes", *framesize);
796       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
797           nextlen + LOAS_MAX_SIZE);
798       return TRUE;
799     }
800   }
801   return FALSE;
802 }
803
804 /* caller ensure sufficient data */
805 static inline void
806 gst_aac_parse_parse_adts_header (GstAacParse * aacparse, const guint8 * data,
807     gint * rate, gint * channels, gint * object, gint * version)
808 {
809
810   if (rate) {
811     gint sr_idx = (data[2] & 0x3c) >> 2;
812
813     *rate = gst_codec_utils_aac_get_sample_rate_from_index (sr_idx);
814   }
815   if (channels) {
816     *channels = ((data[2] & 0x01) << 2) | ((data[3] & 0xc0) >> 6);
817     if (*channels == 7)
818       *channels = 8;
819   }
820
821   if (version)
822     *version = (data[1] & 0x08) ? 2 : 4;
823   if (object)
824     *object = ((data[2] & 0xc0) >> 6) + 1;
825 }
826
827 /**
828  * gst_aac_parse_detect_stream:
829  * @aacparse: #GstAacParse.
830  * @data: A block of data that needs to be examined for stream characteristics.
831  * @avail: Size of the given datablock.
832  * @framesize: If valid stream was found, this will be set to tell the
833  *             first frame size in bytes.
834  * @skipsize: If valid stream was found, this will be set to tell the first
835  *            audio frame position within the given data.
836  *
837  * Examines the given piece of data and try to detect the format of it. It
838  * checks for "ADIF" header (in the beginning of the clip) and ADTS frame
839  * header. If the stream is detected, TRUE will be returned and #framesize
840  * is set to indicate the found frame size. Additionally, #skipsize might
841  * be set to indicate the number of bytes that need to be skipped, a.k.a. the
842  * position of the frame inside given data chunk.
843  *
844  * Returns: TRUE on success.
845  */
846 static gboolean
847 gst_aac_parse_detect_stream (GstAacParse * aacparse,
848     const guint8 * data, const guint avail, gboolean drain,
849     guint * framesize, gint * skipsize)
850 {
851   gboolean found = FALSE;
852   guint need_data_adts = 0, need_data_loas;
853   guint i = 0;
854
855   GST_DEBUG_OBJECT (aacparse, "Parsing header data");
856
857   /* FIXME: No need to check for ADIF if we are not in the beginning of the
858      stream */
859
860   /* Can we even parse the header? */
861   if (avail < MAX (ADTS_MAX_SIZE, LOAS_MAX_SIZE)) {
862     GST_DEBUG_OBJECT (aacparse, "Not enough data to check");
863     return FALSE;
864   }
865
866   for (i = 0; i < avail - 4; i++) {
867     if (((data[i] == 0xff) && ((data[i + 1] & 0xf6) == 0xf0)) ||
868         ((data[i] == 0x56) && ((data[i + 1] & 0xe0) == 0xe0)) ||
869         strncmp ((char *) data + i, "ADIF", 4) == 0) {
870       GST_DEBUG_OBJECT (aacparse, "Found signature at offset %u", i);
871       found = TRUE;
872
873       if (i) {
874         /* Trick: tell the parent class that we didn't find the frame yet,
875            but make it skip 'i' amount of bytes. Next time we arrive
876            here we have full frame in the beginning of the data. */
877         *skipsize = i;
878         return FALSE;
879       }
880       break;
881     }
882   }
883   if (!found) {
884     if (i)
885       *skipsize = i;
886     return FALSE;
887   }
888
889   if (gst_aac_parse_check_adts_frame (aacparse, data, avail, drain,
890           framesize, &need_data_adts)) {
891     gint rate, channels;
892
893     GST_INFO ("ADTS ID: %d, framesize: %d", (data[1] & 0x08) >> 3, *framesize);
894
895     gst_aac_parse_parse_adts_header (aacparse, data, &rate, &channels,
896         &aacparse->object_type, &aacparse->mpegversion);
897
898     if (!channels || !framesize) {
899       GST_DEBUG_OBJECT (aacparse, "impossible ADTS configuration");
900       return FALSE;
901     }
902
903     aacparse->header_type = DSPAAC_HEADER_ADTS;
904     gst_base_parse_set_frame_rate (GST_BASE_PARSE (aacparse), rate,
905         aacparse->frame_samples, 2, 2);
906
907     GST_DEBUG ("ADTS: samplerate %d, channels %d, objtype %d, version %d",
908         rate, channels, aacparse->object_type, aacparse->mpegversion);
909
910     gst_base_parse_set_syncable (GST_BASE_PARSE (aacparse), TRUE);
911
912     return TRUE;
913   }
914
915   if (gst_aac_parse_check_loas_frame (aacparse, data, avail, drain,
916           framesize, &need_data_loas)) {
917     gint rate = 0, channels = 0;
918
919     GST_INFO ("LOAS, framesize: %d", *framesize);
920
921     aacparse->header_type = DSPAAC_HEADER_LOAS;
922
923     if (!gst_aac_parse_read_loas_config (aacparse, data, avail, &rate,
924             &channels, &aacparse->mpegversion)) {
925       /* This is pretty normal when skipping data at the start of
926        * random stream (MPEG-TS capture for example) */
927       GST_LOG_OBJECT (aacparse, "Error reading LOAS config");
928       return FALSE;
929     }
930
931     if (rate && channels) {
932       gst_base_parse_set_frame_rate (GST_BASE_PARSE (aacparse), rate,
933           aacparse->frame_samples, 2, 2);
934
935       /* Don't store the sample rate and channels yet -
936        * this is just format detection. */
937       GST_DEBUG ("LOAS: samplerate %d, channels %d, objtype %d, version %d",
938           rate, channels, aacparse->object_type, aacparse->mpegversion);
939     }
940
941     gst_base_parse_set_syncable (GST_BASE_PARSE (aacparse), TRUE);
942
943     return TRUE;
944   }
945
946   if (need_data_adts || need_data_loas) {
947     /* This tells the parent class not to skip any data */
948     *skipsize = 0;
949     return FALSE;
950   }
951
952   if (avail < ADIF_MAX_SIZE)
953     return FALSE;
954
955   if (memcmp (data + i, "ADIF", 4) == 0) {
956     const guint8 *adif;
957     int skip_size = 0;
958     int bitstream_type;
959     int sr_idx;
960     GstCaps *sinkcaps;
961
962     aacparse->header_type = DSPAAC_HEADER_ADIF;
963     aacparse->mpegversion = 4;
964
965     /* Skip the "ADIF" bytes */
966     adif = data + i + 4;
967
968     /* copyright string */
969     if (adif[0] & 0x80)
970       skip_size += 9;           /* skip 9 bytes */
971
972     bitstream_type = adif[0 + skip_size] & 0x10;
973     aacparse->bitrate =
974         ((unsigned int) (adif[0 + skip_size] & 0x0f) << 19) |
975         ((unsigned int) adif[1 + skip_size] << 11) |
976         ((unsigned int) adif[2 + skip_size] << 3) |
977         ((unsigned int) adif[3 + skip_size] & 0xe0);
978
979     /* CBR */
980     if (bitstream_type == 0) {
981 #if 0
982       /* Buffer fullness parsing. Currently not needed... */
983       guint num_elems = 0;
984       guint fullness = 0;
985
986       num_elems = (adif[3 + skip_size] & 0x1e);
987       GST_INFO ("ADIF num_config_elems: %d", num_elems);
988
989       fullness = ((unsigned int) (adif[3 + skip_size] & 0x01) << 19) |
990           ((unsigned int) adif[4 + skip_size] << 11) |
991           ((unsigned int) adif[5 + skip_size] << 3) |
992           ((unsigned int) (adif[6 + skip_size] & 0xe0) >> 5);
993
994       GST_INFO ("ADIF buffer fullness: %d", fullness);
995 #endif
996       aacparse->object_type = ((adif[6 + skip_size] & 0x01) << 1) |
997           ((adif[7 + skip_size] & 0x80) >> 7);
998       sr_idx = (adif[7 + skip_size] & 0x78) >> 3;
999     }
1000     /* VBR */
1001     else {
1002       aacparse->object_type = (adif[4 + skip_size] & 0x18) >> 3;
1003       sr_idx = ((adif[4 + skip_size] & 0x07) << 1) |
1004           ((adif[5 + skip_size] & 0x80) >> 7);
1005     }
1006
1007     /* FIXME: This gives totally wrong results. Duration calculation cannot
1008        be based on this */
1009     aacparse->sample_rate =
1010         gst_codec_utils_aac_get_sample_rate_from_index (sr_idx);
1011
1012     /* baseparse is not given any fps,
1013      * so it will give up on timestamps, seeking, etc */
1014
1015     /* FIXME: Can we assume this? */
1016     aacparse->channels = 2;
1017
1018     GST_INFO ("ADIF: br=%d, samplerate=%d, objtype=%d",
1019         aacparse->bitrate, aacparse->sample_rate, aacparse->object_type);
1020
1021     gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse), 512);
1022
1023     /* arrange for metadata and get out of the way */
1024     sinkcaps = gst_pad_get_current_caps (GST_BASE_PARSE_SINK_PAD (aacparse));
1025     gst_aac_parse_set_src_caps (aacparse, sinkcaps);
1026     if (sinkcaps)
1027       gst_caps_unref (sinkcaps);
1028
1029     /* not syncable, not easily seekable (unless we push data from start */
1030     gst_base_parse_set_syncable (GST_BASE_PARSE_CAST (aacparse), FALSE);
1031     gst_base_parse_set_passthrough (GST_BASE_PARSE_CAST (aacparse), TRUE);
1032     gst_base_parse_set_average_bitrate (GST_BASE_PARSE_CAST (aacparse), 0);
1033
1034     *framesize = avail;
1035     return TRUE;
1036   }
1037
1038   /* This should never happen */
1039   return FALSE;
1040 }
1041
1042 /**
1043  * gst_aac_parse_get_audio_profile_object_type
1044  * @aacparse: #GstAacParse.
1045  *
1046  * Gets the MPEG-2 profile or the MPEG-4 object type value corresponding to the
1047  * mpegversion and profile of @aacparse's src pad caps, according to the
1048  * values defined by table 1.A.11 in ISO/IEC 14496-3.
1049  *
1050  * Returns: the profile or object type value corresponding to @aacparse's src
1051  * pad caps, if such a value exists; otherwise G_MAXUINT8.
1052  */
1053 static guint8
1054 gst_aac_parse_get_audio_profile_object_type (GstAacParse * aacparse)
1055 {
1056   GstCaps *srccaps;
1057   GstStructure *srcstruct;
1058   const gchar *profile;
1059   guint8 ret;
1060
1061   srccaps = gst_pad_get_current_caps (GST_BASE_PARSE_SRC_PAD (aacparse));
1062   srcstruct = gst_caps_get_structure (srccaps, 0);
1063   profile = gst_structure_get_string (srcstruct, "profile");
1064   if (G_UNLIKELY (profile == NULL)) {
1065     gst_caps_unref (srccaps);
1066     return G_MAXUINT8;
1067   }
1068
1069   if (g_strcmp0 (profile, "main") == 0) {
1070     ret = (guint8) 0U;
1071   } else if (g_strcmp0 (profile, "lc") == 0) {
1072     ret = (guint8) 1U;
1073   } else if (g_strcmp0 (profile, "ssr") == 0) {
1074     ret = (guint8) 2U;
1075   } else if (g_strcmp0 (profile, "ltp") == 0) {
1076     if (G_LIKELY (aacparse->mpegversion == 4))
1077       ret = (guint8) 3U;
1078     else
1079       ret = G_MAXUINT8;         /* LTP Object Type allowed only for MPEG-4 */
1080   } else {
1081     ret = G_MAXUINT8;
1082   }
1083
1084   gst_caps_unref (srccaps);
1085   return ret;
1086 }
1087
1088 /**
1089  * gst_aac_parse_get_audio_channel_configuration
1090  * @num_channels: number of audio channels.
1091  *
1092  * Gets the Channel Configuration value, as defined by table 1.19 in ISO/IEC
1093  * 14496-3, for a given number of audio channels.
1094  *
1095  * Returns: the Channel Configuration value corresponding to @num_channels, if
1096  * such a value exists; otherwise G_MAXUINT8.
1097  */
1098 static guint8
1099 gst_aac_parse_get_audio_channel_configuration (gint num_channels)
1100 {
1101   if (num_channels >= 1 && num_channels <= 6)   /* Mono up to & including 5.1 */
1102     return (guint8) num_channels;
1103   else if (num_channels == 8)   /* 7.1 */
1104     return (guint8) 7U;
1105   else
1106     return G_MAXUINT8;
1107
1108   /* FIXME: Add support for configurations 11, 12 and 14 from
1109    * ISO/IEC 14496-3:2009/PDAM 4 based on the actual channel layout
1110    */
1111 }
1112
1113 /**
1114  * gst_aac_parse_get_audio_sampling_frequency_index:
1115  * @sample_rate: audio sampling rate.
1116  *
1117  * Gets the Sampling Frequency Index value, as defined by table 1.18 in ISO/IEC
1118  * 14496-3, for a given sampling rate.
1119  *
1120  * Returns: the Sampling Frequency Index value corresponding to @sample_rate,
1121  * if such a value exists; otherwise G_MAXUINT8.
1122  */
1123 static guint8
1124 gst_aac_parse_get_audio_sampling_frequency_index (gint sample_rate)
1125 {
1126   switch (sample_rate) {
1127     case 96000:
1128       return 0x0U;
1129     case 88200:
1130       return 0x1U;
1131     case 64000:
1132       return 0x2U;
1133     case 48000:
1134       return 0x3U;
1135     case 44100:
1136       return 0x4U;
1137     case 32000:
1138       return 0x5U;
1139     case 24000:
1140       return 0x6U;
1141     case 22050:
1142       return 0x7U;
1143     case 16000:
1144       return 0x8U;
1145     case 12000:
1146       return 0x9U;
1147     case 11025:
1148       return 0xAU;
1149     case 8000:
1150       return 0xBU;
1151     case 7350:
1152       return 0xCU;
1153     default:
1154       return G_MAXUINT8;
1155   }
1156 }
1157
1158 /**
1159  * gst_aac_parse_prepend_adts_headers:
1160  * @aacparse: #GstAacParse.
1161  * @frame: raw AAC frame to which ADTS headers shall be prepended.
1162  *
1163  * Prepends ADTS headers to a raw AAC audio frame.
1164  *
1165  * Returns: TRUE if ADTS headers were successfully prepended; FALSE otherwise.
1166  */
1167 static gboolean
1168 gst_aac_parse_prepend_adts_headers (GstAacParse * aacparse,
1169     GstBaseParseFrame * frame)
1170 {
1171   GstMemory *mem;
1172   guint8 *adts_headers;
1173   gsize buf_size;
1174   gsize frame_size;
1175   guint8 id, profile, channel_configuration, sampling_frequency_index;
1176
1177   id = (aacparse->mpegversion == 4) ? 0x0U : 0x1U;
1178   profile = gst_aac_parse_get_audio_profile_object_type (aacparse);
1179   if (profile == G_MAXUINT8) {
1180     GST_ERROR_OBJECT (aacparse, "Unsupported audio profile or object type");
1181     return FALSE;
1182   }
1183   channel_configuration =
1184       gst_aac_parse_get_audio_channel_configuration (aacparse->channels);
1185   if (channel_configuration == G_MAXUINT8) {
1186     GST_ERROR_OBJECT (aacparse, "Unsupported number of channels");
1187     return FALSE;
1188   }
1189   sampling_frequency_index =
1190       gst_aac_parse_get_audio_sampling_frequency_index (aacparse->sample_rate);
1191   if (sampling_frequency_index == G_MAXUINT8) {
1192     GST_ERROR_OBJECT (aacparse, "Unsupported sampling frequency");
1193     return FALSE;
1194   }
1195
1196   frame->out_buffer = gst_buffer_copy (frame->buffer);
1197   buf_size = gst_buffer_get_size (frame->out_buffer);
1198   frame_size = buf_size + ADTS_HEADERS_LENGTH;
1199
1200   if (G_UNLIKELY (frame_size >= 0x4000)) {
1201     GST_ERROR_OBJECT (aacparse, "Frame size is too big for ADTS");
1202     return FALSE;
1203   }
1204
1205   adts_headers = (guint8 *) g_malloc0 (ADTS_HEADERS_LENGTH);
1206
1207   /* Note: no error correction bits are added to the resulting ADTS frames */
1208   adts_headers[0] = 0xFFU;
1209   adts_headers[1] = 0xF0U | (id << 3) | 0x1U;
1210   adts_headers[2] = (profile << 6) | (sampling_frequency_index << 2) | 0x2U |
1211       (channel_configuration & 0x4U);
1212   adts_headers[3] = ((channel_configuration & 0x3U) << 6) | 0x30U |
1213       (guint8) (frame_size >> 11);
1214   adts_headers[4] = (guint8) ((frame_size >> 3) & 0x00FF);
1215   adts_headers[5] = (guint8) (((frame_size & 0x0007) << 5) + 0x1FU);
1216   adts_headers[6] = 0xFCU;
1217
1218   mem = gst_memory_new_wrapped (0, adts_headers, ADTS_HEADERS_LENGTH, 0,
1219       ADTS_HEADERS_LENGTH, adts_headers, g_free);
1220   gst_buffer_prepend_memory (frame->out_buffer, mem);
1221
1222   return TRUE;
1223 }
1224
1225 /**
1226  * gst_aac_parse_check_valid_frame:
1227  * @parse: #GstBaseParse.
1228  * @frame: #GstBaseParseFrame.
1229  * @skipsize: How much data parent class should skip in order to find the
1230  *            frame header.
1231  *
1232  * Implementation of "handle_frame" vmethod in #GstBaseParse class.
1233  *
1234  * Also determines frame overhead.
1235  * ADTS streams have a 7 byte header in each frame. MP4 and ADIF streams don't have
1236  * a per-frame header. LOAS has 3 bytes.
1237  *
1238  * We're making a couple of simplifying assumptions:
1239  *
1240  * 1. We count Program Configuration Elements rather than searching for them
1241  *    in the streams to discount them - the overhead is negligible.
1242  *
1243  * 2. We ignore CRC. This has a worst-case impact of (num_raw_blocks + 1)*16
1244  *    bits, which should still not be significant enough to warrant the
1245  *    additional parsing through the headers
1246  *
1247  * Returns: a #GstFlowReturn.
1248  */
1249 static GstFlowReturn
1250 gst_aac_parse_handle_frame (GstBaseParse * parse,
1251     GstBaseParseFrame * frame, gint * skipsize)
1252 {
1253   GstMapInfo map;
1254   GstAacParse *aacparse;
1255   gboolean ret = FALSE;
1256   gboolean lost_sync;
1257   GstBuffer *buffer;
1258   guint framesize;
1259   gint rate = 0, channels = 0;
1260
1261   aacparse = GST_AAC_PARSE (parse);
1262   buffer = frame->buffer;
1263
1264   gst_buffer_map (buffer, &map, GST_MAP_READ);
1265
1266   *skipsize = -1;
1267   lost_sync = GST_BASE_PARSE_LOST_SYNC (parse);
1268
1269   if (aacparse->header_type == DSPAAC_HEADER_ADIF ||
1270       aacparse->header_type == DSPAAC_HEADER_NONE) {
1271     /* There is nothing to parse */
1272     framesize = map.size;
1273     ret = TRUE;
1274
1275   } else if (aacparse->header_type == DSPAAC_HEADER_NOT_PARSED || lost_sync) {
1276
1277     ret = gst_aac_parse_detect_stream (aacparse, map.data, map.size,
1278         GST_BASE_PARSE_DRAINING (parse), &framesize, skipsize);
1279
1280   } else if (aacparse->header_type == DSPAAC_HEADER_ADTS) {
1281     guint needed_data = 1024;
1282
1283     ret = gst_aac_parse_check_adts_frame (aacparse, map.data, map.size,
1284         GST_BASE_PARSE_DRAINING (parse), &framesize, &needed_data);
1285
1286     if (!ret && needed_data) {
1287       GST_DEBUG ("buffer didn't contain valid frame");
1288       *skipsize = 0;
1289       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
1290           needed_data);
1291     }
1292
1293   } else if (aacparse->header_type == DSPAAC_HEADER_LOAS) {
1294     guint needed_data = 1024;
1295
1296     ret = gst_aac_parse_check_loas_frame (aacparse, map.data,
1297         map.size, GST_BASE_PARSE_DRAINING (parse), &framesize, &needed_data);
1298
1299     if (!ret && needed_data) {
1300       GST_DEBUG ("buffer didn't contain valid frame");
1301       *skipsize = 0;
1302       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
1303           needed_data);
1304     }
1305
1306   } else {
1307     GST_DEBUG ("buffer didn't contain valid frame");
1308     gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse),
1309         ADTS_MAX_SIZE);
1310   }
1311
1312   if (G_UNLIKELY (!ret))
1313     goto exit;
1314
1315   if (aacparse->header_type == DSPAAC_HEADER_ADTS) {
1316     /* see above */
1317     frame->overhead = 7;
1318
1319     gst_aac_parse_parse_adts_header (aacparse, map.data,
1320         &rate, &channels, NULL, NULL);
1321
1322     GST_LOG_OBJECT (aacparse, "rate: %d, chans: %d", rate, channels);
1323
1324     if (G_UNLIKELY (rate != aacparse->sample_rate
1325             || channels != aacparse->channels)) {
1326       aacparse->sample_rate = rate;
1327       aacparse->channels = channels;
1328
1329       if (!gst_aac_parse_set_src_caps (aacparse, NULL)) {
1330         /* If linking fails, we need to return appropriate error */
1331         ret = GST_FLOW_NOT_LINKED;
1332       }
1333
1334       gst_base_parse_set_frame_rate (GST_BASE_PARSE (aacparse),
1335           aacparse->sample_rate, aacparse->frame_samples, 2, 2);
1336     }
1337 #ifdef TIZEN_FEATURE_AACPARSE_MODIFICATION
1338     if (aacparse->first_frame == TRUE) {
1339       gboolean ret = FALSE;
1340       aacparse->first_frame = FALSE;
1341
1342       ret = gst_aac_parse_estimate_duration(parse);
1343       if (!ret) {
1344         GST_WARNING_OBJECT (aacparse, "can not estimate total duration");
1345         ret = GST_FLOW_NOT_SUPPORTED;
1346       }
1347     }
1348 #endif
1349   } else if (aacparse->header_type == DSPAAC_HEADER_LOAS) {
1350     gboolean setcaps = FALSE;
1351
1352     /* see above */
1353     frame->overhead = 3;
1354
1355     if (!gst_aac_parse_read_loas_config (aacparse, map.data, map.size, &rate,
1356             &channels, NULL) || !rate || !channels) {
1357       /* This is pretty normal when skipping data at the start of
1358        * random stream (MPEG-TS capture for example) */
1359       GST_DEBUG_OBJECT (aacparse, "Error reading LOAS config. Skipping.");
1360       *skipsize = map.size;
1361       goto exit;
1362     }
1363
1364     if (G_UNLIKELY (rate != aacparse->sample_rate
1365             || channels != aacparse->channels)) {
1366       aacparse->sample_rate = rate;
1367       aacparse->channels = channels;
1368       setcaps = TRUE;
1369       GST_INFO_OBJECT (aacparse, "New LOAS config: %d Hz, %d channels", rate,
1370           channels);
1371     }
1372
1373     /* We want to set caps both at start, and when rate/channels change.
1374        Since only some LOAS frames have that info, we may receive frames
1375        before knowing about rate/channels. */
1376     if (setcaps
1377         || !gst_pad_has_current_caps (GST_BASE_PARSE_SRC_PAD (aacparse))) {
1378       if (!gst_aac_parse_set_src_caps (aacparse, NULL)) {
1379         /* If linking fails, we need to return appropriate error */
1380         ret = GST_FLOW_NOT_LINKED;
1381       }
1382
1383       gst_base_parse_set_frame_rate (GST_BASE_PARSE (aacparse),
1384           aacparse->sample_rate, aacparse->frame_samples, 2, 2);
1385     }
1386   }
1387 #ifdef TIZEN_FEATURE_AACPARSE_MODIFICATION
1388   else if(aacparse->header_type == DSPAAC_HEADER_ADIF)
1389   {
1390       /* to get more correct duration */
1391       int file_size = 0;
1392       float estimated_duration = 0;
1393       gint64 total_file_size;
1394       gst_base_parse_get_upstream_size(parse, &total_file_size);
1395       estimated_duration = ((total_file_size * 8) / (float)(aacparse->bitrate * 1000))* GST_SECOND;
1396       gst_base_parse_set_duration (parse, GST_FORMAT_TIME, estimated_duration * 1000, 0);
1397   }
1398 #endif
1399
1400   if (aacparse->header_type == DSPAAC_HEADER_NONE
1401       && aacparse->output_header_type == DSPAAC_HEADER_ADTS) {
1402     if (!gst_aac_parse_prepend_adts_headers (aacparse, frame)) {
1403       GST_ERROR_OBJECT (aacparse, "Failed to prepend ADTS headers to frame");
1404       ret = GST_FLOW_ERROR;
1405     }
1406   }
1407
1408 exit:
1409   gst_buffer_unmap (buffer, &map);
1410
1411   if (ret) {
1412     /* found, skip if needed */
1413     if (*skipsize > 0)
1414       return GST_FLOW_OK;
1415     *skipsize = 0;
1416   } else {
1417     if (*skipsize < 0)
1418       *skipsize = 1;
1419   }
1420
1421   if (ret && framesize <= map.size) {
1422     return gst_base_parse_finish_frame (parse, frame, framesize);
1423   }
1424
1425   return GST_FLOW_OK;
1426 }
1427
1428 static GstFlowReturn
1429 gst_aac_parse_pre_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1430 {
1431   GstAacParse *aacparse = GST_AAC_PARSE (parse);
1432
1433   if (!aacparse->sent_codec_tag) {
1434     GstTagList *taglist;
1435     GstCaps *caps;
1436
1437     taglist = gst_tag_list_new_empty ();
1438
1439     /* codec tag */
1440     caps = gst_pad_get_current_caps (GST_BASE_PARSE_SRC_PAD (parse));
1441     gst_pb_utils_add_codec_description_to_tag_list (taglist,
1442         GST_TAG_AUDIO_CODEC, caps);
1443     gst_caps_unref (caps);
1444
1445     gst_base_parse_merge_tags (parse, taglist, GST_TAG_MERGE_REPLACE);
1446     gst_tag_list_unref (taglist);
1447
1448     /* also signals the end of first-frame processing */
1449     aacparse->sent_codec_tag = TRUE;
1450   }
1451
1452   /* As a special case, we can remove the ADTS framing and output raw AAC. */
1453   if (aacparse->header_type == DSPAAC_HEADER_ADTS
1454       && aacparse->output_header_type == DSPAAC_HEADER_NONE) {
1455     guint header_size;
1456     GstMapInfo map;
1457     gst_buffer_map (frame->buffer, &map, GST_MAP_READ);
1458     header_size = (map.data[1] & 1) ? 7 : 9;    /* optional CRC */
1459     gst_buffer_unmap (frame->buffer, &map);
1460     gst_buffer_resize (frame->buffer, header_size,
1461         gst_buffer_get_size (frame->buffer) - header_size);
1462   }
1463
1464   return GST_FLOW_OK;
1465 }
1466
1467
1468 /**
1469  * gst_aac_parse_start:
1470  * @parse: #GstBaseParse.
1471  *
1472  * Implementation of "start" vmethod in #GstBaseParse class.
1473  *
1474  * Returns: TRUE if startup succeeded.
1475  */
1476 static gboolean
1477 gst_aac_parse_start (GstBaseParse * parse)
1478 {
1479   GstAacParse *aacparse;
1480
1481   aacparse = GST_AAC_PARSE (parse);
1482   GST_DEBUG ("start");
1483   aacparse->frame_samples = 1024;
1484   gst_base_parse_set_min_frame_size (GST_BASE_PARSE (aacparse), ADTS_MAX_SIZE);
1485   aacparse->sent_codec_tag = FALSE;
1486   return TRUE;
1487 }
1488
1489
1490 /**
1491  * gst_aac_parse_stop:
1492  * @parse: #GstBaseParse.
1493  *
1494  * Implementation of "stop" vmethod in #GstBaseParse class.
1495  *
1496  * Returns: TRUE is stopping succeeded.
1497  */
1498 static gboolean
1499 gst_aac_parse_stop (GstBaseParse * parse)
1500 {
1501   GST_DEBUG ("stop");
1502   return TRUE;
1503 }
1504
1505 static void
1506 remove_fields (GstCaps * caps)
1507 {
1508   guint i, n;
1509
1510   n = gst_caps_get_size (caps);
1511   for (i = 0; i < n; i++) {
1512     GstStructure *s = gst_caps_get_structure (caps, i);
1513
1514     gst_structure_remove_field (s, "framed");
1515   }
1516 }
1517
1518 static void
1519 add_conversion_fields (GstCaps * caps)
1520 {
1521   guint i, n;
1522
1523   n = gst_caps_get_size (caps);
1524   for (i = 0; i < n; i++) {
1525     GstStructure *s = gst_caps_get_structure (caps, i);
1526
1527     if (gst_structure_has_field (s, "stream-format")) {
1528       const GValue *v = gst_structure_get_value (s, "stream-format");
1529
1530       if (G_VALUE_HOLDS_STRING (v)) {
1531         const gchar *str = g_value_get_string (v);
1532
1533         if (strcmp (str, "adts") == 0 || strcmp (str, "raw") == 0) {
1534           GValue va = G_VALUE_INIT;
1535           GValue vs = G_VALUE_INIT;
1536
1537           g_value_init (&va, GST_TYPE_LIST);
1538           g_value_init (&vs, G_TYPE_STRING);
1539           g_value_set_string (&vs, "adts");
1540           gst_value_list_append_value (&va, &vs);
1541           g_value_set_string (&vs, "raw");
1542           gst_value_list_append_value (&va, &vs);
1543           gst_structure_set_value (s, "stream-format", &va);
1544           g_value_unset (&va);
1545           g_value_unset (&vs);
1546         }
1547       } else if (GST_VALUE_HOLDS_LIST (v)) {
1548         gboolean contains_raw = FALSE;
1549         gboolean contains_adts = FALSE;
1550         guint m = gst_value_list_get_size (v), j;
1551
1552         for (j = 0; j < m; j++) {
1553           const GValue *ve = gst_value_list_get_value (v, j);
1554           const gchar *str;
1555
1556           if (G_VALUE_HOLDS_STRING (ve) && (str = g_value_get_string (ve))) {
1557             if (strcmp (str, "adts") == 0)
1558               contains_adts = TRUE;
1559             else if (strcmp (str, "raw") == 0)
1560               contains_raw = TRUE;
1561           }
1562         }
1563
1564         if (contains_adts || contains_raw) {
1565           GValue va = G_VALUE_INIT;
1566           GValue vs = G_VALUE_INIT;
1567
1568           g_value_init (&va, GST_TYPE_LIST);
1569           g_value_init (&vs, G_TYPE_STRING);
1570           g_value_copy (v, &va);
1571
1572           if (!contains_raw) {
1573             g_value_set_string (&vs, "raw");
1574             gst_value_list_append_value (&va, &vs);
1575           }
1576           if (!contains_adts) {
1577             g_value_set_string (&vs, "adts");
1578             gst_value_list_append_value (&va, &vs);
1579           }
1580
1581           gst_structure_set_value (s, "stream-format", &va);
1582
1583           g_value_unset (&vs);
1584           g_value_unset (&va);
1585         }
1586       }
1587     }
1588   }
1589 }
1590
1591 static GstCaps *
1592 gst_aac_parse_sink_getcaps (GstBaseParse * parse, GstCaps * filter)
1593 {
1594   GstCaps *peercaps, *templ;
1595   GstCaps *res;
1596
1597   templ = gst_pad_get_pad_template_caps (GST_BASE_PARSE_SINK_PAD (parse));
1598
1599   if (filter) {
1600     GstCaps *fcopy = gst_caps_copy (filter);
1601     /* Remove the fields we convert */
1602     remove_fields (fcopy);
1603     add_conversion_fields (fcopy);
1604     peercaps = gst_pad_peer_query_caps (GST_BASE_PARSE_SRC_PAD (parse), fcopy);
1605     gst_caps_unref (fcopy);
1606   } else
1607     peercaps = gst_pad_peer_query_caps (GST_BASE_PARSE_SRC_PAD (parse), NULL);
1608
1609   if (peercaps) {
1610     peercaps = gst_caps_make_writable (peercaps);
1611     /* Remove the fields we convert */
1612     remove_fields (peercaps);
1613     add_conversion_fields (peercaps);
1614
1615     res = gst_caps_intersect_full (peercaps, templ, GST_CAPS_INTERSECT_FIRST);
1616     gst_caps_unref (peercaps);
1617     gst_caps_unref (templ);
1618   } else {
1619     res = templ;
1620   }
1621
1622   if (filter) {
1623     GstCaps *intersection;
1624
1625     intersection =
1626         gst_caps_intersect_full (filter, res, GST_CAPS_INTERSECT_FIRST);
1627     gst_caps_unref (res);
1628     res = intersection;
1629   }
1630
1631   return res;
1632 }
1633
1634 #ifdef TIZEN_FEATURE_AACPARSE_MODIFICATION
1635 /**
1636  * get_aac_parse_get_adts_framelength:
1637  * @data: #GstBufferData.
1638  * @offset: #GstBufferData offset
1639  *
1640  * Implementation to get adts framelength by using first some frame.
1641  *
1642  * Returns: frame size
1643  */
1644 int get_aac_parse_get_adts_frame_length (const unsigned char* data,
1645     gint64 offset)
1646 {
1647   const gint adts_header_length_no_crc = 7;
1648   const gint adts_header_length_with_crc = 9;
1649   gint frame_size = 0;
1650   gint protection_absent;
1651   gint head_size;
1652
1653   /* check of syncword */
1654   if ((data[offset+0] != 0xff) || ((data[offset+1] & 0xf6) != 0xf0)) {
1655     GST_ERROR("check sync word is fail\n");
1656     return  -1;
1657   }
1658
1659   /* check of protection absent */
1660   protection_absent = (data[offset+1] & 0x01);
1661
1662   /*check of frame length */
1663   frame_size = (data[offset+3] & 0x3) << 11 | data[offset+4] << 3 | data[offset+5] >> 5;
1664
1665   /* check of header size */
1666   /* protectionAbsent is 0 if there is CRC */
1667   head_size = protection_absent ? adts_header_length_no_crc : adts_header_length_with_crc;
1668   if (head_size > frame_size) {
1669     GST_ERROR("return frame length as 0 (frameSize %u < headSize %u)", frame_size, head_size);
1670     return 0;
1671   }
1672
1673   return frame_size;
1674 }
1675
1676 /**
1677  * gst_aac_parse_estimate_duration:
1678  * @parse: #GstBaseParse.
1679  *
1680  * Implementation to get estimated total duration by using first some frame.
1681  *
1682  * Returns: TRUE if we can get estimated total duraion
1683  */
1684 static gboolean
1685 gst_aac_parse_estimate_duration (GstBaseParse * parse)
1686 {
1687   gboolean ret = FALSE;
1688   GstFlowReturn res = GST_FLOW_OK;
1689   gint64 pull_size = 0, file_size = 0, offset = 0, num_frames=0, duration=0;
1690   guint profile = 0, sample_rate_index = 0, sample_rate = 0, channel = 0;
1691   guint frame_size = 0, frame_duration_us = 0, estimated_bitrate = 0;
1692   guint  lost_sync_count=0;
1693   GstClockTime estimated_duration = GST_CLOCK_TIME_NONE;
1694   GstBuffer *buffer = NULL;
1695   guint8 *buf = NULL;
1696   gint i = 0;
1697   GstPadMode pad_mode = GST_PAD_MODE_NONE;
1698   GstAacParse *aacparse;
1699   gint64 buffer_size = 0;
1700
1701   aacparse = GST_AAC_PARSE (parse);
1702   GST_LOG_OBJECT (aacparse, "gst_aac_parse_estimate_duration enter");
1703
1704   /* check baseparse define these fuction */
1705   gst_base_parse_get_pad_mode(parse, &pad_mode);
1706   if (pad_mode != GST_PAD_MODE_PULL) {
1707     GST_INFO_OBJECT (aacparse, "aac parser is not pull mode. can not estimate duration");
1708     return FALSE;
1709   }
1710
1711   gst_base_parse_get_upstream_size (parse, &file_size);
1712
1713   if (file_size < ADIF_MAX_SIZE) {
1714     GST_ERROR_OBJECT (aacparse, "file size is too short");
1715     return FALSE;
1716   }
1717
1718   pull_size = MIN(file_size, AAC_MAX_ESTIMATE_DURATION_BUF);
1719
1720   res = gst_pad_pull_range (parse->sinkpad, 0, pull_size, &buffer);
1721   if (res != GST_FLOW_OK) {
1722     GST_ERROR_OBJECT (aacparse, "gst_pad_pull_range failed!");
1723     return FALSE;
1724   }
1725
1726   GstMapInfo map;
1727   gst_buffer_map(buffer, &map, GST_MAP_READ);
1728   buf = map.data;
1729   buffer_size = map.size;
1730   if (buffer_size != pull_size) {
1731     GST_ERROR_OBJECT(aacparse, "We got different buffer_size(%d) with pull_size(%d).",
1732         buffer_size, pull_size);
1733   }
1734
1735   /* MODIFICATION : add defence codes for real buffer_size is different with pull_size */
1736   for (i = 0; i < buffer_size; i ++) {
1737     if ((buf[i] == 0xff) && ((buf[i+1] & 0xf6) == 0xf0)) { /* aac sync word */
1738       profile = (buf[i+2] >> 6) & 0x3;
1739       sample_rate_index = (buf[i+2] >> 2) & 0xf;
1740       sample_rate = gst_aac_parse_get_sample_rate_from_index(sample_rate_index);
1741       if (sample_rate == 0) {
1742           GST_WARNING_OBJECT (aacparse, "Invalid sample rate index (0)");
1743           goto EXIT;
1744       }
1745       channel = (buf[i+2] & 0x1) << 2 | (buf[i+3] >> 6);
1746
1747       GST_INFO_OBJECT (aacparse, "found sync. aac fs=%d, ch=%d", sample_rate, channel);
1748
1749       /* count number of frames */
1750       /*MODIFICATION : add defence codes for real buffer_size is different with pull_size*/
1751       //while (offset < pull_size) {
1752       while (offset < buffer_size) {
1753         frame_size = get_aac_parse_get_adts_frame_length(buf, i + offset);
1754         if (frame_size  == 0) {
1755           GST_ERROR_OBJECT (aacparse, "framesize error at offset %"G_GINT64_FORMAT, offset);
1756           break;
1757         } else if (frame_size == -1) {
1758           offset++;
1759           lost_sync_count++;    //  lost sync count limmitation 2K Bytes
1760           if (lost_sync_count > (1024*2)) {
1761             GST_WARNING_OBJECT (aacparse, "lost_sync_count is larger than 2048");
1762             goto EXIT;
1763           }
1764         } else {
1765           offset += frame_size;
1766           num_frames++;
1767           lost_sync_count=0;
1768         }
1769       } /* while */
1770
1771       /* if we can got full file, we can calculate the accurate duration */
1772       /*MODIFICATION : add defence codes for real buffer_size is different with pull_size*/
1773       //if (pull_size == file_size) {
1774       if (buffer_size == file_size) {
1775         gfloat duration_for_one_frame = 0;
1776         GstClockTime calculated_duration = GST_CLOCK_TIME_NONE;
1777
1778         GST_INFO_OBJECT (aacparse, "we got total file (%d bytes). do not estimate but make Accurate total duration.", pull_size);
1779
1780         duration_for_one_frame = (gfloat)AAC_SAMPLE_PER_FRAME / (gfloat)sample_rate;
1781         calculated_duration = num_frames * duration_for_one_frame * 1000 * 1000 * 1000;
1782
1783         GST_INFO_OBJECT (aacparse, "duration_for_one_frame %f ms", duration_for_one_frame);
1784         GST_INFO_OBJECT (aacparse, "calculated duration = %"GST_TIME_FORMAT,
1785             GST_TIME_ARGS(calculated_duration));
1786         /* 0 means disable estimate */
1787         gst_base_parse_set_duration (parse, GST_FORMAT_TIME, calculated_duration, 0);
1788
1789       } else {
1790         GST_INFO_OBJECT (aacparse, "we got %d bytes in total file (%"G_GINT64_FORMAT
1791             "). can not make accurate duration but Estimate.", pull_size, file_size);
1792         frame_duration_us = (1024 * 1000000ll + (sample_rate - 1)) / sample_rate;
1793         duration = num_frames * frame_duration_us;
1794
1795         if (duration == 0) {
1796           GST_WARNING_OBJECT (aacparse, "Invalid duration");
1797           goto EXIT;
1798         }
1799         estimated_bitrate = (gint)((gfloat)(offset * 8) / (gfloat)(duration / 1000));
1800
1801         if (estimated_bitrate == 0) {
1802           GST_WARNING_OBJECT (aacparse, "Invalid estimated_bitrate");
1803           goto EXIT;
1804         }
1805         estimated_duration = (GstClockTime)((file_size * 8) / (estimated_bitrate * 1000)) * GST_SECOND;
1806
1807         GST_INFO_OBJECT (aacparse, "number of frame = %"G_GINT64_FORMAT, num_frames);
1808         GST_INFO_OBJECT (aacparse, "duration = %"G_GINT64_FORMAT, duration / 1000000);
1809         GST_INFO_OBJECT (aacparse, "byte = %"G_GINT64_FORMAT, offset);
1810         GST_INFO_OBJECT (aacparse, "estimated bitrate = %d bps", estimated_bitrate);
1811         GST_INFO_OBJECT (aacparse, "estimated duration = %"GST_TIME_FORMAT, GST_TIME_ARGS(estimated_duration));
1812
1813         gst_base_parse_set_average_bitrate (parse, estimated_bitrate * 1000);
1814         /* set update_interval as duration(sec)/2 */
1815         gst_base_parse_set_duration (parse, GST_FORMAT_TIME, estimated_duration, (gint)(duration/2));
1816       }
1817
1818       break;
1819     }
1820   }
1821   ret = TRUE;
1822
1823 EXIT:
1824   gst_buffer_unmap(buffer, &map);
1825   gst_buffer_unref(buffer);
1826   return ret;
1827 }
1828
1829
1830 /* perform seek in push based mode:
1831    find BYTE position to move to based on time and delegate to upstream
1832 */
1833 static gboolean
1834 gst_aac_audio_parse_do_push_seek (GstBaseParse * parse,
1835     GstPad * pad, GstEvent * event)
1836 {
1837   GstAacParse *aacparse;
1838   aacparse = GST_AAC_PARSE(parse);
1839
1840   gdouble rate;
1841   GstFormat format;
1842   GstSeekFlags flags;
1843   GstSeekType cur_type, stop_type;
1844   gint64 cur, stop;
1845   gboolean res;
1846   gint64 byte_cur;
1847   gint64 esimate_byte;
1848   gint32 frame_dur;
1849   gint64 upstream_total_bytes = 0;
1850   GstFormat fmt = GST_FORMAT_BYTES;
1851
1852   GST_INFO_OBJECT (parse, "doing aac push-based seek");
1853
1854   gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur, &stop_type, &stop);
1855
1856   /* FIXME, always play to the end */
1857   stop = -1;
1858
1859   /* only forward streaming and seeking is possible */
1860   if (rate <= 0)
1861     goto unsupported_seek;
1862
1863   if ( cur == 0 ) {
1864     /* handle rewind only */
1865     cur_type = GST_SEEK_TYPE_SET;
1866     byte_cur = 0;
1867     stop_type = GST_SEEK_TYPE_NONE;
1868     stop = -1;
1869     flags |= GST_SEEK_FLAG_FLUSH;
1870   } else {
1871     /* handle normal seek */
1872     cur_type = GST_SEEK_TYPE_SET;
1873     stop_type = GST_SEEK_TYPE_NONE;
1874     stop = -1;
1875     flags |= GST_SEEK_FLAG_FLUSH;
1876
1877     esimate_byte = (cur / (1000 * 1000)) * aacparse->frame_byte;
1878     if (aacparse->sample_rate> 0)
1879       frame_dur = (aacparse->spf * 1000) / aacparse->sample_rate;
1880     else
1881       goto unsupported_seek;
1882     if (frame_dur > 0)
1883       byte_cur =  esimate_byte / (frame_dur);
1884     else
1885       goto unsupported_seek;
1886
1887     GST_INFO_OBJECT(parse, "frame_byte(%d) spf(%d)  rate (%d) ", aacparse->frame_byte, aacparse->spf, aacparse->sample_rate);
1888     GST_INFO_OBJECT(parse, "seek cur (%"G_GINT64_FORMAT") = (%"GST_TIME_FORMAT") ", cur, GST_TIME_ARGS (cur));
1889     GST_INFO_OBJECT(parse, "esimate_byte(%"G_GINT64_FORMAT")  esimate_byte (%d)", esimate_byte, frame_dur );
1890   }
1891
1892   /* obtain real upstream total bytes */
1893   if (!gst_pad_peer_query_duration (parse->sinkpad, fmt, &upstream_total_bytes))
1894     upstream_total_bytes = 0;
1895     GST_INFO_OBJECT (aacparse, "gst_pad_query_peer_duration -upstream_total_bytes (%"G_GUINT64_FORMAT")", upstream_total_bytes);
1896     aacparse->file_size = upstream_total_bytes;
1897
1898   if ( (byte_cur == -1) || (byte_cur > aacparse->file_size))
1899   {
1900     GST_INFO_OBJECT(parse, "[WEB-ERROR] seek cur (%"G_GINT64_FORMAT") > file_size (%"G_GINT64_FORMAT") ", cur, aacparse->file_size );
1901     goto abort_seek;
1902   }
1903
1904   GST_INFO_OBJECT (parse, "Pushing BYTE seek rate %g, "  "start %" G_GINT64_FORMAT ", stop %" G_GINT64_FORMAT, rate, byte_cur,  stop);
1905
1906   if (!(flags & GST_SEEK_FLAG_KEY_UNIT)) {
1907     GST_INFO_OBJECT (parse, "Requested seek time: %" GST_TIME_FORMAT ", calculated seek offset: %" G_GUINT64_FORMAT, GST_TIME_ARGS (cur), byte_cur);
1908   }
1909
1910   /* BYTE seek event */
1911   event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags, cur_type, byte_cur, stop_type, stop);
1912   res = gst_pad_push_event (parse->sinkpad, event);
1913
1914   return res;
1915
1916   /* ERRORS */
1917
1918 abort_seek:
1919   {
1920     GST_DEBUG_OBJECT (parse, "could not determine byte position to seek to, " "seek aborted.");
1921     return FALSE;
1922   }
1923
1924 unsupported_seek:
1925   {
1926     GST_DEBUG_OBJECT (parse, "unsupported seek, seek aborted.");
1927     return FALSE;
1928   }
1929 }
1930
1931
1932 static guint
1933 gst_aac_parse_adts_get_fast_frame_len (const guint8 * data)
1934 {
1935   int length;
1936   if ((data[0] == 0xff) && ((data[1] & 0xf6) == 0xf0)) {
1937     length = ((data[3] & 0x03) << 11) | (data[4] << 3) | ((data[5] & 0xe0) >> 5);
1938   } else {
1939     length = 0;
1940   }
1941   return length;
1942 }
1943
1944 static gboolean
1945 gst_aac_parse_src_eventfunc(GstBaseParse * parse, GstEvent * event)
1946 {
1947   gboolean  handled = FALSE;
1948   GstAacParse *aacparse;
1949   aacparse = GST_AAC_PARSE(parse);
1950
1951   GST_DEBUG("Entering gst_aac_parse_src_eventfunc header type = %d", aacparse->header_type);
1952   if(aacparse->header_type == DSPAAC_HEADER_ADTS)
1953     return gst_aac_parse_adts_src_eventfunc (parse, event);
1954   else
1955     goto aac_seek_null_exit;
1956 aac_seek_null_exit:
1957
1958   /* call baseparse src_event function to handle event */
1959   handled = GST_BASE_PARSE_CLASS (parent_class)->src_event (parse, event);
1960   return handled;
1961 }
1962
1963 /**
1964  * gst_aac_parse_adts_src_eventfunc:
1965  * @parse: #GstBaseParse. #event
1966  *
1967  * before baseparse handles seek event, make full amr index table.
1968  *
1969  * Returns: TRUE on success.
1970  */
1971 static gboolean
1972 gst_aac_parse_adts_src_eventfunc (GstBaseParse * parse, GstEvent * event)
1973 {
1974   gboolean handled = FALSE;
1975   GstAacParse *aacparse;
1976   aacparse = GST_AAC_PARSE (parse);
1977
1978   switch (GST_EVENT_TYPE (event)) {
1979     case GST_EVENT_SEEK:
1980       {
1981         GstFlowReturn res = GST_FLOW_OK;
1982         gint64 base_offset = 0, sync_offset = 0, cur = 0;
1983         gint32 frame_count = 1;    /* do not add first frame because it is already in index table */
1984         gint64 second_count = 0;   /* initial 1 second */
1985         gint64 total_file_size = 0, start_offset = 0;
1986         GstClockTime current_ts = GST_CLOCK_TIME_NONE;
1987         GstPadMode pad_mode = GST_PAD_MODE_NONE;
1988        gboolean large_file_flag = FALSE;
1989
1990         /* check baseparse define these fuction */
1991         gst_base_parse_get_pad_mode(parse, &pad_mode);
1992         if (pad_mode != GST_PAD_MODE_PULL) {
1993           gboolean ret = FALSE;
1994           GST_INFO_OBJECT (aacparse, "aac parser is PUSH MODE.");
1995           GstPad* srcpad = parse->srcpad;
1996           /* check NULL */
1997           ret = gst_aac_audio_parse_do_push_seek(parse, srcpad, event);
1998           gst_object_unref(srcpad);
1999           return ret;
2000         }
2001         gst_base_parse_get_upstream_size(parse, &total_file_size);
2002         gst_base_parse_get_index_last_offset(parse, &start_offset);
2003         gst_base_parse_get_index_last_ts(parse, &current_ts);
2004
2005         if (total_file_size > AAC_LARGE_FILE_SIZE ) {
2006            large_file_flag = TRUE;
2007           gst_base_parse_set_seek_mode(parse, 0);
2008           GST_INFO_OBJECT (aacparse, "larger than big size (2MB).");
2009           goto aac_seek_null_exit;
2010         }
2011
2012         GST_DEBUG("gst_aac_parse_adts_src_eventfunc GST_EVENT_SEEK enter");
2013
2014         if (total_file_size == 0 || start_offset >= total_file_size) {
2015           GST_ERROR("last index offset %d is larger than file size %d", start_offset, total_file_size);
2016           break;
2017         }
2018
2019         gst_event_parse_seek (event, NULL, NULL, NULL, NULL, &cur, NULL, NULL);
2020         if (cur <= current_ts) {
2021           GST_INFO("seek to %"GST_TIME_FORMAT" within index table %"GST_TIME_FORMAT". do not make index table",
2022               GST_TIME_ARGS(cur), GST_TIME_ARGS(current_ts));
2023           break;
2024         } else {
2025           GST_INFO("seek to %"GST_TIME_FORMAT" without index table %"GST_TIME_FORMAT". make index table",
2026               GST_TIME_ARGS(cur), GST_TIME_ARGS(current_ts));
2027         }
2028
2029         GST_INFO("make AAC(ADTS) Index Table. file_size  = %"G_GINT64_FORMAT" last idx offset=%"G_GINT64_FORMAT
2030             ", last idx ts=%"GST_TIME_FORMAT, total_file_size, start_offset, GST_TIME_ARGS(current_ts));
2031
2032         base_offset = start_offset; /* set base by start offset */
2033         second_count = current_ts + GST_SECOND; /* 1sec */
2034
2035         /************************************/
2036         /* STEP 0: Setting parse information */
2037         /************************************/
2038           aacparse->spf = aacparse->frame_samples;
2039           aacparse->frame_duration = (aacparse->spf * 1000 * 100) / aacparse->sample_rate;  /* duration per frame (msec) */
2040           aacparse->frame_per_sec = (aacparse->sample_rate) / aacparse->spf;          /* frames per second (ea) */
2041
2042         /************************************/
2043         /* STEP 1: MAX_PULL_RANGE_BUF cycle */
2044         /************************************/
2045         while (total_file_size - base_offset >= AAC_MAX_PULL_RANGE_BUF) {
2046           gint64 offset = 0;
2047           GstBuffer *buffer = NULL;
2048           guint8 *buf = NULL;
2049
2050          GST_INFO("gst_pad_pull_range %d bytes (from %"G_GINT64_FORMAT") use max size", AAC_MAX_PULL_RANGE_BUF, base_offset);
2051           res = gst_pad_pull_range (parse->sinkpad, base_offset, base_offset + AAC_MAX_PULL_RANGE_BUF, &buffer);
2052           if (res != GST_FLOW_OK) {
2053             GST_ERROR ("gst_pad_pull_range failed!");
2054             break;
2055           }
2056
2057           GstMapInfo map;
2058           gst_buffer_map(buffer, &map, GST_MAP_READ);
2059           buf = map.data;
2060           if (buf == NULL) {
2061             gst_buffer_unmap(buffer, &map);
2062             GST_WARNING("buffer is NULL in make aac seek table's STEP1");
2063             gst_buffer_unref (buffer);
2064             goto aac_seek_null_exit;
2065           }
2066
2067           while (offset <= AAC_MAX_PULL_RANGE_BUF) {
2068             gint frame_size = 0;
2069             guint32 header;
2070
2071             /* make sure the values in the frame header look sane */
2072             frame_size = gst_aac_parse_adts_get_fast_frame_len (buf);
2073
2074             if ((frame_size > 0) && (frame_size < (AAC_MAX_PULL_RANGE_BUF - offset))) {
2075               if (current_ts > second_count)  { /* 1 sec == xx frames. we make idx per sec */
2076                 gst_base_parse_add_index_entry (parse, base_offset +offset, current_ts, TRUE, TRUE); /* force */
2077                 GST_DEBUG("Adding  index ts=%"GST_TIME_FORMAT" offset %"G_GINT64_FORMAT,
2078                     GST_TIME_ARGS(current_ts), base_offset + offset);
2079                 second_count += GST_SECOND;    /* 1sec */
2080               }
2081
2082               current_ts += (aacparse->frame_duration * GST_MSECOND) / 100; /* each frame is (frame_duration) ms */
2083               offset += frame_size;
2084               buf += frame_size;
2085               frame_count++;
2086             } else if (frame_size >= (AAC_MAX_PULL_RANGE_BUF - offset)) {
2087               GST_DEBUG("we need refill buffer");
2088               break;
2089             } else {
2090               GST_WARNING("we lost sync");
2091               buf++;
2092               offset++;
2093             }
2094           } /* while */
2095
2096           base_offset = base_offset + offset;
2097
2098           gst_buffer_unmap(buffer, &map);
2099           gst_buffer_unref (buffer);
2100         } /* end MAX buffer cycle */
2101
2102         /*******************************/
2103         /* STEP 2: Remain Buffer cycle */
2104         /*******************************/
2105         if (total_file_size - base_offset > 0) {
2106           gint64 offset = 0;
2107           GstBuffer *buffer = NULL;
2108           guint8 *buf = NULL;
2109
2110           GST_INFO("gst_pad_pull_range %"G_GINT64_FORMAT" bytes (from %"G_GINT64_FORMAT") use remain_buf size",
2111               total_file_size - base_offset, base_offset);
2112           res = gst_pad_pull_range (parse->sinkpad, base_offset, total_file_size, &buffer);
2113           if (res != GST_FLOW_OK) {
2114             GST_ERROR ("gst_pad_pull_range failed!");
2115             break;
2116           }
2117
2118           GstMapInfo map;
2119           gst_buffer_map(buffer, &map, GST_MAP_READ);
2120           buf = map.data;
2121           if (buf == NULL) {
2122             gst_buffer_unmap(buffer, &map);
2123             GST_WARNING("buffer is NULL in make aac seek table's STEP2");
2124             gst_buffer_unref (buffer);
2125             goto aac_seek_null_exit;
2126           }
2127
2128           while (base_offset + offset < total_file_size) {
2129             gint frame_size = 0;
2130             guint32 header;
2131
2132             /* make sure the values in the frame header look sane */
2133             frame_size = gst_aac_parse_adts_get_fast_frame_len (buf);
2134
2135             if ((frame_size > 0) && (frame_size <= (total_file_size - (base_offset + offset)))) {
2136               if (current_ts > second_count) {  /* 1 sec == xx frames. we make idx per sec */
2137                 gst_base_parse_add_index_entry (parse, base_offset +offset, current_ts, TRUE, TRUE); /* force */
2138                 GST_DEBUG("Adding  index ts=%"GST_TIME_FORMAT" offset %"G_GINT64_FORMAT,
2139                     GST_TIME_ARGS(current_ts), base_offset + offset);
2140                 second_count += GST_SECOND;    /* 1sec */
2141               }
2142
2143               current_ts += (aacparse->frame_duration * GST_MSECOND) / 100; /* each frame is (frame_duration) ms */
2144               offset += frame_size;
2145               buf += frame_size;
2146               frame_count++;
2147             } else if (frame_size == 0) {
2148               GST_DEBUG("Frame size is 0 so, Decoding end..");
2149               break;
2150             } else {
2151               GST_WARNING("we lost sync");
2152               buf++;
2153               offset++;
2154             }
2155           } /* while */
2156
2157           gst_buffer_unmap(buffer, &map);
2158           gst_buffer_unref (buffer);
2159         } /* end remain_buf buffer cycle */
2160
2161         GST_DEBUG("gst_aac_parse_adts_src_eventfunc GST_EVENT_SEEK leave");
2162       }
2163      break;
2164
2165     default:
2166       break;
2167   }
2168
2169 aac_seek_null_exit:
2170
2171   /* call baseparse src_event function to handle event */
2172   handled = GST_BASE_PARSE_CLASS (parent_class)->src_event (parse, event);
2173   return handled;
2174 }
2175 #endif //end of #ifdef TIZEN_FEATURE_AACPARSE_MODIFICATION