Merge branch 'move_subdir_good' into tizen_gst_1.19.2_mono
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-good / gst / audioparsers / gstmpegaudioparse.c
1 /* GStreamer MPEG audio parser
2  * Copyright (C) 2006-2007 Jan Schmidt <thaytan@mad.scientist.com>
3  * Copyright (C) 2010 Mark Nauwelaerts <mnauw users sf net>
4  * Copyright (C) 2010 Nokia Corporation. All rights reserved.
5  *   Contact: Stefan Kost <stefan.kost@nokia.com>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22 /**
23  * SECTION:element-mpegaudioparse
24  * @title: mpegaudioparse
25  * @short_description: MPEG audio parser
26  * @see_also: #GstAmrParse, #GstAACParse
27  *
28  * Parses and frames mpeg1 audio streams. Provides seeking.
29  *
30  * ## Example launch line
31  * |[
32  * gst-launch-1.0 filesrc location=test.mp3 ! mpegaudioparse ! mpg123audiodec
33  *  ! audioconvert ! audioresample ! autoaudiosink
34  * ]|
35  *
36  */
37
38 /* FIXME: we should make the base class (GstBaseParse) aware of the
39  * XING seek table somehow, so it can use it properly for things like
40  * accurate seeks. Currently it can only do a lookup via the convert function,
41  * but then doesn't know what the result represents exactly. One could either
42  * add a vfunc for index lookup, or just make mpegaudioparse populate the
43  * base class's index via the API provided.
44  */
45 #ifdef HAVE_CONFIG_H
46 #include "config.h"
47 #endif
48
49 #include <string.h>
50
51 #include "gstaudioparserselements.h"
52 #include "gstmpegaudioparse.h"
53 #include <gst/base/gstbytereader.h>
54 #include <gst/pbutils/pbutils.h>
55
56 GST_DEBUG_CATEGORY_STATIC (mpeg_audio_parse_debug);
57 #define GST_CAT_DEFAULT mpeg_audio_parse_debug
58
59 #define MPEG_AUDIO_CHANNEL_MODE_UNKNOWN -1
60 #define MPEG_AUDIO_CHANNEL_MODE_STEREO 0
61 #define MPEG_AUDIO_CHANNEL_MODE_JOINT_STEREO 1
62 #define MPEG_AUDIO_CHANNEL_MODE_DUAL_CHANNEL 2
63 #define MPEG_AUDIO_CHANNEL_MODE_MONO 3
64
65 #define CRC_UNKNOWN -1
66 #define CRC_PROTECTED 0
67 #define CRC_NOT_PROTECTED 1
68
69 #define XING_FRAMES_FLAG     0x0001
70 #define XING_BYTES_FLAG      0x0002
71 #define XING_TOC_FLAG        0x0004
72 #define XING_VBR_SCALE_FLAG  0x0008
73
74 #define MIN_FRAME_SIZE       6
75
76 #ifdef TIZEN_FEATURE_MP3PARSE_MODIFICATION
77 #define DEFAULT_CHECK_HTTP_SEEK FALSE
78
79 /* Property */
80 enum
81 {
82   PROP_0,
83   PROP_CHECK_HTTP_SEEK
84 };
85 #endif
86
87 static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
88     GST_PAD_SRC,
89     GST_PAD_ALWAYS,
90     GST_STATIC_CAPS ("audio/mpeg, "
91         "mpegversion = (int) 1, "
92         "layer = (int) [ 1, 3 ], "
93         "mpegaudioversion = (int) [ 1, 3], "
94         "rate = (int) [ 8000, 48000 ], "
95         "channels = (int) [ 1, 2 ], " "parsed=(boolean) true")
96     );
97
98 static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
99     GST_PAD_SINK,
100     GST_PAD_ALWAYS,
101     GST_STATIC_CAPS ("audio/mpeg, mpegversion = (int) 1")
102     );
103
104 static void gst_mpeg_audio_parse_finalize (GObject * object);
105
106 static gboolean gst_mpeg_audio_parse_start (GstBaseParse * parse);
107 static gboolean gst_mpeg_audio_parse_stop (GstBaseParse * parse);
108
109 #ifdef TIZEN_FEATURE_MP3PARSE_MODIFICATION
110 static void gst_mpeg_audio_parse_set_property (GObject * object, guint prop_id,
111     const GValue * value, GParamSpec * pspec);
112 static void gst_mpeg_audio_parse_get_property (GObject * object, guint prop_id,
113     GValue * value, GParamSpec * pspec);
114 static gboolean gst_mpeg_audio_parse_src_eventfunc (GstBaseParse * parse,
115     GstEvent * event);
116 #endif
117
118 static GstFlowReturn gst_mpeg_audio_parse_handle_frame (GstBaseParse * parse,
119     GstBaseParseFrame * frame, gint * skipsize);
120 static GstFlowReturn gst_mpeg_audio_parse_pre_push_frame (GstBaseParse * parse,
121     GstBaseParseFrame * frame);
122 static gboolean gst_mpeg_audio_parse_convert (GstBaseParse * parse,
123     GstFormat src_format, gint64 src_value,
124     GstFormat dest_format, gint64 * dest_value);
125 static GstCaps *gst_mpeg_audio_parse_get_sink_caps (GstBaseParse * parse,
126     GstCaps * filter);
127
128 static void gst_mpeg_audio_parse_handle_first_frame (GstMpegAudioParse *
129     mp3parse, GstBuffer * buf);
130
131 #define gst_mpeg_audio_parse_parent_class parent_class
132 G_DEFINE_TYPE (GstMpegAudioParse, gst_mpeg_audio_parse, GST_TYPE_BASE_PARSE);
133 GST_ELEMENT_REGISTER_DEFINE (mpegaudioparse, "mpegaudioparse",
134     GST_RANK_PRIMARY + 2, GST_TYPE_MPEG_AUDIO_PARSE);
135
136 #define GST_TYPE_MPEG_AUDIO_CHANNEL_MODE  \
137     (gst_mpeg_audio_channel_mode_get_type())
138
139 static const GEnumValue mpeg_audio_channel_mode[] = {
140   {MPEG_AUDIO_CHANNEL_MODE_UNKNOWN, "Unknown", "unknown"},
141   {MPEG_AUDIO_CHANNEL_MODE_MONO, "Mono", "mono"},
142   {MPEG_AUDIO_CHANNEL_MODE_DUAL_CHANNEL, "Dual Channel", "dual-channel"},
143   {MPEG_AUDIO_CHANNEL_MODE_JOINT_STEREO, "Joint Stereo", "joint-stereo"},
144   {MPEG_AUDIO_CHANNEL_MODE_STEREO, "Stereo", "stereo"},
145   {0, NULL, NULL},
146 };
147
148 static GType
149 gst_mpeg_audio_channel_mode_get_type (void)
150 {
151   static GType mpeg_audio_channel_mode_type = 0;
152
153   if (!mpeg_audio_channel_mode_type) {
154     mpeg_audio_channel_mode_type =
155         g_enum_register_static ("GstMpegAudioChannelMode",
156         mpeg_audio_channel_mode);
157   }
158   return mpeg_audio_channel_mode_type;
159 }
160
161 static const gchar *
162 gst_mpeg_audio_channel_mode_get_nick (gint mode)
163 {
164   guint i;
165   for (i = 0; i < G_N_ELEMENTS (mpeg_audio_channel_mode); i++) {
166     if (mpeg_audio_channel_mode[i].value == mode)
167       return mpeg_audio_channel_mode[i].value_nick;
168   }
169   return NULL;
170 }
171
172 static void
173 gst_mpeg_audio_parse_class_init (GstMpegAudioParseClass * klass)
174 {
175   GstBaseParseClass *parse_class = GST_BASE_PARSE_CLASS (klass);
176   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
177   GObjectClass *object_class = G_OBJECT_CLASS (klass);
178
179   GST_DEBUG_CATEGORY_INIT (mpeg_audio_parse_debug, "mpegaudioparse", 0,
180       "MPEG1 audio stream parser");
181
182   object_class->finalize = gst_mpeg_audio_parse_finalize;
183
184   parse_class->start = GST_DEBUG_FUNCPTR (gst_mpeg_audio_parse_start);
185   parse_class->stop = GST_DEBUG_FUNCPTR (gst_mpeg_audio_parse_stop);
186   parse_class->handle_frame =
187       GST_DEBUG_FUNCPTR (gst_mpeg_audio_parse_handle_frame);
188   parse_class->pre_push_frame =
189       GST_DEBUG_FUNCPTR (gst_mpeg_audio_parse_pre_push_frame);
190   parse_class->convert = GST_DEBUG_FUNCPTR (gst_mpeg_audio_parse_convert);
191   parse_class->get_sink_caps =
192       GST_DEBUG_FUNCPTR (gst_mpeg_audio_parse_get_sink_caps);
193
194 #ifdef TIZEN_FEATURE_MP3PARSE_MODIFICATION
195   object_class->set_property =
196       GST_DEBUG_FUNCPTR (gst_mpeg_audio_parse_set_property);
197   object_class->get_property =
198       GST_DEBUG_FUNCPTR (gst_mpeg_audio_parse_get_property);
199
200   g_object_class_install_property (object_class, PROP_CHECK_HTTP_SEEK,
201       g_param_spec_boolean ("http-pull-mp3dec", "enable/disable",
202           "enable/disable mp3dec http seek pull mode",
203           DEFAULT_CHECK_HTTP_SEEK, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
204   /* T.B.D : make full mp3 index table when seek */
205   parse_class->src_event = gst_mpeg_audio_parse_src_eventfunc;
206 #endif
207
208   /* register tags */
209 #define GST_TAG_CRC      "has-crc"
210 #define GST_TAG_MODE     "channel-mode"
211
212   gst_tag_register (GST_TAG_CRC, GST_TAG_FLAG_META, G_TYPE_BOOLEAN,
213       "has crc", "Using CRC", NULL);
214   gst_tag_register (GST_TAG_MODE, GST_TAG_FLAG_ENCODED, G_TYPE_STRING,
215       "channel mode", "MPEG audio channel mode", NULL);
216
217   g_type_class_ref (GST_TYPE_MPEG_AUDIO_CHANNEL_MODE);
218
219   gst_element_class_add_static_pad_template (element_class, &sink_template);
220   gst_element_class_add_static_pad_template (element_class, &src_template);
221
222   gst_element_class_set_static_metadata (element_class, "MPEG1 Audio Parser",
223       "Codec/Parser/Audio",
224       "Parses and frames mpeg1 audio streams (levels 1-3), provides seek",
225       "Jan Schmidt <thaytan@mad.scientist.com>,"
226       "Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>");
227 }
228
229 static void
230 gst_mpeg_audio_parse_reset (GstMpegAudioParse * mp3parse)
231 {
232   mp3parse->channels = -1;
233   mp3parse->rate = -1;
234   mp3parse->sent_codec_tag = FALSE;
235   mp3parse->last_posted_crc = CRC_UNKNOWN;
236   mp3parse->last_posted_channel_mode = MPEG_AUDIO_CHANNEL_MODE_UNKNOWN;
237   mp3parse->freerate = 0;
238
239   mp3parse->hdr_bitrate = 0;
240   mp3parse->bitrate_is_constant = TRUE;
241
242   mp3parse->xing_flags = 0;
243   mp3parse->xing_bitrate = 0;
244   mp3parse->xing_frames = 0;
245   mp3parse->xing_total_time = 0;
246   mp3parse->xing_bytes = 0;
247   mp3parse->xing_vbr_scale = 0;
248   memset (mp3parse->xing_seek_table, 0, sizeof (mp3parse->xing_seek_table));
249   memset (mp3parse->xing_seek_table_inverse, 0,
250       sizeof (mp3parse->xing_seek_table_inverse));
251
252   mp3parse->vbri_bitrate = 0;
253   mp3parse->vbri_frames = 0;
254   mp3parse->vbri_total_time = 0;
255   mp3parse->vbri_bytes = 0;
256   mp3parse->vbri_seek_points = 0;
257   g_free (mp3parse->vbri_seek_table);
258   mp3parse->vbri_seek_table = NULL;
259
260   mp3parse->encoder_delay = 0;
261   mp3parse->encoder_padding = 0;
262 }
263
264 static void
265 gst_mpeg_audio_parse_init (GstMpegAudioParse * mp3parse)
266 {
267   gst_mpeg_audio_parse_reset (mp3parse);
268   GST_PAD_SET_ACCEPT_INTERSECT (GST_BASE_PARSE_SINK_PAD (mp3parse));
269   GST_PAD_SET_ACCEPT_TEMPLATE (GST_BASE_PARSE_SINK_PAD (mp3parse));
270 }
271
272 static void
273 gst_mpeg_audio_parse_finalize (GObject * object)
274 {
275   G_OBJECT_CLASS (parent_class)->finalize (object);
276 }
277
278 static gboolean
279 gst_mpeg_audio_parse_start (GstBaseParse * parse)
280 {
281   GstMpegAudioParse *mp3parse = GST_MPEG_AUDIO_PARSE (parse);
282
283   gst_base_parse_set_min_frame_size (GST_BASE_PARSE (mp3parse), MIN_FRAME_SIZE);
284   GST_DEBUG_OBJECT (parse, "starting");
285
286   gst_mpeg_audio_parse_reset (mp3parse);
287
288 #ifdef TIZEN_FEATURE_MP3PARSE_MODIFICATION
289   if (mp3parse->http_seek_flag) {
290     /* Don't need Accurate Seek table (in http pull mode) */
291     GST_INFO_OBJECT (parse, "Enable (1) : mp3parse->http_seek_flag");
292   } else {
293     GST_INFO_OBJECT (parse, "Disable (0) : mp3parse->http_seek_flag");
294   }
295 #endif
296
297   return TRUE;
298 }
299
300 #ifdef TIZEN_FEATURE_MP3PARSE_MODIFICATION
301 static void
302 gst_mpeg_audio_parse_set_property (GObject * object, guint prop_id,
303     const GValue * value, GParamSpec * pspec)
304 {
305   GstMpegAudioParse *mp3parse = GST_MPEG_AUDIO_PARSE (object);
306   GST_INFO_OBJECT (mp3parse, "set_property() START- prop_id(%d)", prop_id);
307   switch (prop_id) {
308     case PROP_CHECK_HTTP_SEEK:
309       mp3parse->http_seek_flag = g_value_get_boolean (value);
310       GST_INFO_OBJECT (mp3parse, "http_seek_flag(%d)",
311           mp3parse->http_seek_flag);
312       break;
313     default:
314       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
315       break;
316   }
317 }
318
319 static void
320 gst_mpeg_audio_parse_get_property (GObject * object, guint prop_id,
321     GValue * value, GParamSpec * pspec)
322 {
323   GstMpegAudioParse *mp3parse = GST_MPEG_AUDIO_PARSE (object);
324   GST_INFO_OBJECT (mp3parse, "get_property() START- prop_id(%d)", prop_id);
325   switch (prop_id) {
326     case PROP_CHECK_HTTP_SEEK:
327       g_value_set_boolean (value, mp3parse->http_seek_flag);
328       GST_INFO_OBJECT (mp3parse, "http_seek_flag(%d)",
329           mp3parse->http_seek_flag);
330       break;
331     default:
332       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
333       break;
334   }
335 }
336 #endif
337
338 static gboolean
339 gst_mpeg_audio_parse_stop (GstBaseParse * parse)
340 {
341   GstMpegAudioParse *mp3parse = GST_MPEG_AUDIO_PARSE (parse);
342
343   GST_DEBUG_OBJECT (parse, "stopping");
344
345   gst_mpeg_audio_parse_reset (mp3parse);
346
347   return TRUE;
348 }
349
350 static const guint mp3types_bitrates[2][3][16] = {
351   {
352         {0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448,},
353         {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384,},
354         {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,}
355       },
356   {
357         {0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256,},
358         {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160,},
359         {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160,}
360       },
361 };
362
363 static const guint mp3types_freqs[3][3] = { {44100, 48000, 32000},
364 {22050, 24000, 16000},
365 {11025, 12000, 8000}
366 };
367
368 static inline guint
369 mp3_type_frame_length_from_header (GstMpegAudioParse * mp3parse, guint32 header,
370     guint * put_version, guint * put_layer, guint * put_channels,
371     guint * put_bitrate, guint * put_samplerate, guint * put_mode,
372     guint * put_crc)
373 {
374   guint length;
375   gulong mode, samplerate, bitrate, layer, channels, padding, crc;
376   gulong version;
377   gint lsf, mpg25;
378
379   if (header & (1 << 20)) {
380     lsf = (header & (1 << 19)) ? 0 : 1;
381     mpg25 = 0;
382   } else {
383     lsf = 1;
384     mpg25 = 1;
385   }
386
387   version = 1 + lsf + mpg25;
388
389   layer = 4 - ((header >> 17) & 0x3);
390
391   crc = (header >> 16) & 0x1;
392
393   bitrate = (header >> 12) & 0xF;
394   bitrate = mp3types_bitrates[lsf][layer - 1][bitrate] * 1000;
395   if (!bitrate) {
396     GST_LOG_OBJECT (mp3parse, "using freeform bitrate");
397     bitrate = mp3parse->freerate;
398   }
399
400   samplerate = (header >> 10) & 0x3;
401   samplerate = mp3types_freqs[lsf + mpg25][samplerate];
402
403   /* force 0 length if 0 bitrate */
404   padding = (bitrate > 0) ? (header >> 9) & 0x1 : 0;
405
406   mode = (header >> 6) & 0x3;
407   channels = (mode == 3) ? 1 : 2;
408
409   switch (layer) {
410     case 1:
411       length = 4 * ((bitrate * 12) / samplerate + padding);
412       break;
413     case 2:
414       length = (bitrate * 144) / samplerate + padding;
415       break;
416     default:
417     case 3:
418       length = (bitrate * 144) / (samplerate << lsf) + padding;
419       break;
420   }
421
422   GST_DEBUG_OBJECT (mp3parse, "Calculated mp3 frame length of %u bytes",
423       length);
424   GST_DEBUG_OBJECT (mp3parse, "samplerate = %lu, bitrate = %lu, version = %lu, "
425       "layer = %lu, channels = %lu, mode = %s", samplerate, bitrate, version,
426       layer, channels, gst_mpeg_audio_channel_mode_get_nick (mode));
427
428   if (put_version)
429     *put_version = version;
430   if (put_layer)
431     *put_layer = layer;
432   if (put_channels)
433     *put_channels = channels;
434   if (put_bitrate)
435     *put_bitrate = bitrate;
436   if (put_samplerate)
437     *put_samplerate = samplerate;
438   if (put_mode)
439     *put_mode = mode;
440   if (put_crc)
441     *put_crc = crc;
442
443   return length;
444 }
445
446 /* Minimum number of consecutive, valid-looking frames to consider
447  * for resyncing */
448 #define MIN_RESYNC_FRAMES 3
449
450 /* Perform extended validation to check that subsequent headers match
451  * the first header given here in important characteristics, to avoid
452  * false sync. We look for a minimum of MIN_RESYNC_FRAMES consecutive
453  * frames to match their major characteristics.
454  *
455  * If at_eos is set to TRUE, we just check that we don't find any invalid
456  * frames in whatever data is available, rather than requiring a full
457  * MIN_RESYNC_FRAMES of data.
458  *
459  * Returns TRUE if we've seen enough data to validate or reject the frame.
460  * If TRUE is returned, then *valid contains TRUE if it validated, or false
461  * if we decided it was false sync.
462  * If FALSE is returned, then *valid contains minimum needed data.
463  */
464 static gboolean
465 gst_mp3parse_validate_extended (GstMpegAudioParse * mp3parse, GstBuffer * buf,
466     guint32 header, int bpf, gboolean at_eos, gint * valid)
467 {
468   guint32 next_header;
469   GstMapInfo map;
470   gboolean res = TRUE;
471   int frames_found = 1;
472   int offset = bpf;
473
474   gst_buffer_map (buf, &map, GST_MAP_READ);
475
476   while (frames_found < MIN_RESYNC_FRAMES) {
477     /* Check if we have enough data for all these frames, plus the next
478        frame header. */
479     if (map.size < offset + 4) {
480       if (at_eos) {
481         /* Running out of data at EOS is fine; just accept it */
482         *valid = TRUE;
483         goto cleanup;
484       } else {
485         *valid = offset + 4;
486         res = FALSE;
487         goto cleanup;
488       }
489     }
490
491     next_header = GST_READ_UINT32_BE (map.data + offset);
492     GST_DEBUG_OBJECT (mp3parse, "At %d: header=%08X, header2=%08X, bpf=%d",
493         offset, (unsigned int) header, (unsigned int) next_header, bpf);
494
495 /* mask the bits which are allowed to differ between frames */
496 #define HDRMASK ~((0xF << 12)  /* bitrate */ | \
497                   (0x1 <<  9)  /* padding */ | \
498                   (0xf <<  4)  /* mode|mode extension */ | \
499                   (0xf))        /* copyright|emphasis */
500
501     if ((next_header & HDRMASK) != (header & HDRMASK)) {
502       /* If any of the unmasked bits don't match, then it's not valid */
503       GST_DEBUG_OBJECT (mp3parse, "next header doesn't match "
504           "(header=%08X (%08X), header2=%08X (%08X), bpf=%d)",
505           (guint) header, (guint) header & HDRMASK, (guint) next_header,
506           (guint) next_header & HDRMASK, bpf);
507       *valid = FALSE;
508       goto cleanup;
509     } else if (((next_header >> 12) & 0xf) == 0xf) {
510       /* The essential parts were the same, but the bitrate held an
511          invalid value - also reject */
512       GST_DEBUG_OBJECT (mp3parse, "next header invalid (bitrate)");
513       *valid = FALSE;
514       goto cleanup;
515     }
516
517     bpf = mp3_type_frame_length_from_header (mp3parse, next_header,
518         NULL, NULL, NULL, NULL, NULL, NULL, NULL);
519
520     /* if no bitrate, and no freeform rate known, then fail */
521     if (G_UNLIKELY (!bpf)) {
522       GST_DEBUG_OBJECT (mp3parse, "next header invalid (bitrate 0)");
523       *valid = FALSE;
524       goto cleanup;
525     }
526
527     offset += bpf;
528     frames_found++;
529   }
530
531   *valid = TRUE;
532
533 cleanup:
534   gst_buffer_unmap (buf, &map);
535   return res;
536 }
537
538 static gboolean
539 gst_mpeg_audio_parse_head_check (GstMpegAudioParse * mp3parse,
540     unsigned long head)
541 {
542   GST_DEBUG_OBJECT (mp3parse, "checking mp3 header 0x%08lx", head);
543   /* if it's not a valid sync */
544   if ((head & 0xffe00000) != 0xffe00000) {
545     GST_WARNING_OBJECT (mp3parse, "invalid sync");
546     return FALSE;
547   }
548   /* if it's an invalid MPEG version */
549   if (((head >> 19) & 3) == 0x1) {
550     GST_WARNING_OBJECT (mp3parse, "invalid MPEG version: 0x%lx",
551         (head >> 19) & 3);
552     return FALSE;
553   }
554   /* if it's an invalid layer */
555   if (!((head >> 17) & 3)) {
556     GST_WARNING_OBJECT (mp3parse, "invalid layer: 0x%lx", (head >> 17) & 3);
557     return FALSE;
558   }
559   /* if it's an invalid bitrate */
560   if (((head >> 12) & 0xf) == 0xf) {
561     GST_WARNING_OBJECT (mp3parse, "invalid bitrate: 0x%lx", (head >> 12) & 0xf);
562     return FALSE;
563   }
564   /* if it's an invalid samplerate */
565   if (((head >> 10) & 0x3) == 0x3) {
566     GST_WARNING_OBJECT (mp3parse, "invalid samplerate: 0x%lx",
567         (head >> 10) & 0x3);
568     return FALSE;
569   }
570
571   if ((head & 0x3) == 0x2) {
572     /* Ignore this as there are some files with emphasis 0x2 that can
573      * be played fine. See BGO #537235 */
574     GST_WARNING_OBJECT (mp3parse, "invalid emphasis: 0x%lx", head & 0x3);
575   }
576
577   return TRUE;
578 }
579
580 /* Determines possible freeform frame rate/size by looking for next
581  * header with valid bitrate (0 or otherwise valid) (and sufficiently
582  * matching current header).
583  *
584  * Returns TRUE if we've found such one, and *rate then contains rate
585  * (or *rate contains 0 if decided no freeframe size could be determined).
586  * If not enough data, returns FALSE.
587  */
588 static gboolean
589 gst_mp3parse_find_freerate (GstMpegAudioParse * mp3parse, GstMapInfo * map,
590     guint32 header, gboolean at_eos, gint * _rate)
591 {
592   guint32 next_header;
593   const guint8 *data;
594   guint available;
595   int offset = 4;
596   gulong samplerate, rate, layer, padding;
597   gboolean valid;
598   gint lsf, mpg25;
599
600   available = map->size;
601   data = map->data;
602
603   *_rate = 0;
604
605   /* pick apart header again partially */
606   if (header & (1 << 20)) {
607     lsf = (header & (1 << 19)) ? 0 : 1;
608     mpg25 = 0;
609   } else {
610     lsf = 1;
611     mpg25 = 1;
612   }
613   layer = 4 - ((header >> 17) & 0x3);
614   samplerate = (header >> 10) & 0x3;
615   samplerate = mp3types_freqs[lsf + mpg25][samplerate];
616   padding = (header >> 9) & 0x1;
617
618   for (; offset < available; ++offset) {
619     /* Check if we have enough data for all these frames, plus the next
620        frame header. */
621     if (available < offset + 4) {
622       if (at_eos) {
623         /* Running out of data; failed to determine size */
624         return TRUE;
625       } else {
626         return FALSE;
627       }
628     }
629
630     valid = FALSE;
631     next_header = GST_READ_UINT32_BE (data + offset);
632     if ((next_header & 0xFFE00000) != 0xFFE00000)
633       goto next;
634
635     GST_DEBUG_OBJECT (mp3parse, "At %d: header=%08X, header2=%08X",
636         offset, (unsigned int) header, (unsigned int) next_header);
637
638     if ((next_header & HDRMASK) != (header & HDRMASK)) {
639       /* If any of the unmasked bits don't match, then it's not valid */
640       GST_DEBUG_OBJECT (mp3parse, "next header doesn't match "
641           "(header=%08X (%08X), header2=%08X (%08X))",
642           (guint) header, (guint) header & HDRMASK, (guint) next_header,
643           (guint) next_header & HDRMASK);
644       goto next;
645     } else if (((next_header >> 12) & 0xf) == 0xf) {
646       /* The essential parts were the same, but the bitrate held an
647          invalid value - also reject */
648       GST_DEBUG_OBJECT (mp3parse, "next header invalid (bitrate)");
649       goto next;
650     }
651
652     valid = TRUE;
653
654   next:
655     /* almost accept as free frame */
656     if (layer == 1) {
657       rate = samplerate * (offset - 4 * padding + 4) / 48000;
658     } else {
659       rate = samplerate * (offset - padding + 1) / (144 >> lsf) / 1000;
660     }
661
662     if (valid) {
663       GST_LOG_OBJECT (mp3parse, "calculated rate %lu", rate * 1000);
664       if (rate < 8 || (layer == 3 && rate > 640)) {
665         GST_DEBUG_OBJECT (mp3parse, "rate invalid");
666         if (rate < 8) {
667           /* maybe some hope */
668           continue;
669         } else {
670           GST_DEBUG_OBJECT (mp3parse, "aborting");
671           /* give up */
672           break;
673         }
674       }
675       *_rate = rate * 1000;
676       break;
677     } else {
678       /* avoid indefinite searching */
679       if (rate > 1000) {
680         GST_DEBUG_OBJECT (mp3parse, "exceeded sanity rate; aborting");
681         break;
682       }
683     }
684   }
685
686   return TRUE;
687 }
688
689 static GstFlowReturn
690 gst_mpeg_audio_parse_handle_frame (GstBaseParse * parse,
691     GstBaseParseFrame * frame, gint * skipsize)
692 {
693   GstMpegAudioParse *mp3parse = GST_MPEG_AUDIO_PARSE (parse);
694   GstBuffer *buf = frame->buffer;
695   GstByteReader reader;
696   gint off, bpf = 0;
697   gboolean lost_sync, draining, valid, caps_change;
698   guint32 header;
699   guint bitrate, layer, rate, channels, version, mode, crc;
700   GstMapInfo map;
701   gboolean res = FALSE;
702
703   gst_buffer_map (buf, &map, GST_MAP_READ);
704   if (G_UNLIKELY (map.size < 6)) {
705     *skipsize = 1;
706     goto cleanup;
707   }
708
709   gst_byte_reader_init (&reader, map.data, map.size);
710
711   off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffe00000, 0xffe00000,
712       0, map.size);
713
714   GST_LOG_OBJECT (parse, "possible sync at buffer offset %d", off);
715
716   /* didn't find anything that looks like a sync word, skip */
717   if (off < 0) {
718     *skipsize = map.size - 3;
719     goto cleanup;
720   }
721
722   /* possible frame header, but not at offset 0? skip bytes before sync */
723   if (off > 0) {
724     *skipsize = off;
725     goto cleanup;
726   }
727
728   /* make sure the values in the frame header look sane */
729   header = GST_READ_UINT32_BE (map.data);
730   if (!gst_mpeg_audio_parse_head_check (mp3parse, header)) {
731     *skipsize = 1;
732     goto cleanup;
733   }
734
735   GST_LOG_OBJECT (parse, "got frame");
736
737   lost_sync = GST_BASE_PARSE_LOST_SYNC (parse);
738   draining = GST_BASE_PARSE_DRAINING (parse);
739
740   if (G_UNLIKELY (lost_sync))
741     mp3parse->freerate = 0;
742
743   bpf = mp3_type_frame_length_from_header (mp3parse, header,
744       &version, &layer, &channels, &bitrate, &rate, &mode, &crc);
745
746   if (channels != mp3parse->channels || rate != mp3parse->rate ||
747       layer != mp3parse->layer || version != mp3parse->version)
748     caps_change = TRUE;
749   else
750     caps_change = FALSE;
751
752   /* maybe free format */
753   if (bpf == 0) {
754     GST_LOG_OBJECT (mp3parse, "possibly free format");
755     if (lost_sync || mp3parse->freerate == 0) {
756       GST_DEBUG_OBJECT (mp3parse, "finding free format rate");
757       if (!gst_mp3parse_find_freerate (mp3parse, &map, header, draining,
758               &valid)) {
759         /* not enough data */
760         gst_base_parse_set_min_frame_size (parse, valid);
761         *skipsize = 0;
762         goto cleanup;
763       } else {
764         GST_DEBUG_OBJECT (parse, "determined freeform size %d", valid);
765         mp3parse->freerate = valid;
766       }
767     }
768     /* try again */
769     bpf = mp3_type_frame_length_from_header (mp3parse, header,
770         &version, &layer, &channels, &bitrate, &rate, &mode, &crc);
771     if (!bpf) {
772       /* did not come up with valid freeform length, reject after all */
773       *skipsize = 1;
774       goto cleanup;
775     }
776   }
777
778   if (!draining && (lost_sync || caps_change)) {
779     if (!gst_mp3parse_validate_extended (mp3parse, buf, header, bpf, draining,
780             &valid)) {
781       /* not enough data */
782       gst_base_parse_set_min_frame_size (parse, valid);
783       *skipsize = 0;
784       goto cleanup;
785     } else {
786       if (!valid) {
787         *skipsize = off + 2;
788         goto cleanup;
789       }
790     }
791   } else if (draining && lost_sync && caps_change && mp3parse->rate > 0) {
792     /* avoid caps jitter that we can't be sure of */
793     *skipsize = off + 2;
794     goto cleanup;
795   }
796
797   /* restore default minimum */
798   gst_base_parse_set_min_frame_size (parse, MIN_FRAME_SIZE);
799
800   res = TRUE;
801
802   /* metadata handling */
803   if (G_UNLIKELY (caps_change)) {
804     GstCaps *caps = gst_caps_new_simple ("audio/mpeg",
805         "mpegversion", G_TYPE_INT, 1,
806         "mpegaudioversion", G_TYPE_INT, version,
807         "layer", G_TYPE_INT, layer,
808         "rate", G_TYPE_INT, rate,
809         "channels", G_TYPE_INT, channels, "parsed", G_TYPE_BOOLEAN, TRUE, NULL);
810     gst_pad_set_caps (GST_BASE_PARSE_SRC_PAD (parse), caps);
811     gst_caps_unref (caps);
812
813     mp3parse->rate = rate;
814     mp3parse->channels = channels;
815     mp3parse->layer = layer;
816     mp3parse->version = version;
817
818     /* see http://www.codeproject.com/audio/MPEGAudioInfo.asp */
819     if (mp3parse->layer == 1)
820       mp3parse->spf = 384;
821     else if (mp3parse->layer == 2)
822       mp3parse->spf = 1152;
823     else if (mp3parse->version == 1) {
824       mp3parse->spf = 1152;
825     } else {
826       /* MPEG-2 or "2.5" */
827       mp3parse->spf = 576;
828     }
829
830     /* lead_in:
831      * We start pushing 9 frames earlier (29 frames for MPEG2) than
832      * segment start to be able to decode the first frame we want.
833      * 9 (29) frames are the theoretical maximum of frames that contain
834      * data for the current frame (bit reservoir).
835      *
836      * lead_out:
837      * Some mp3 streams have an offset in the timestamps, for which we have to
838      * push the frame *after* the end position in order for the decoder to be
839      * able to decode everything up until the segment.stop position. */
840     gst_base_parse_set_frame_rate (parse, mp3parse->rate, mp3parse->spf,
841         (version == 1) ? 10 : 30, 2);
842   }
843
844   if (mp3parse->hdr_bitrate && mp3parse->hdr_bitrate != bitrate) {
845     mp3parse->bitrate_is_constant = FALSE;
846   }
847   mp3parse->hdr_bitrate = bitrate;
848
849   /* For first frame; check for seek tables and output a codec tag */
850   gst_mpeg_audio_parse_handle_first_frame (mp3parse, buf);
851
852   /* store some frame info for later processing */
853   mp3parse->last_crc = crc;
854   mp3parse->last_mode = mode;
855
856 cleanup:
857   gst_buffer_unmap (buf, &map);
858
859   if (res && bpf <= map.size) {
860     return gst_base_parse_finish_frame (parse, frame, bpf);
861   }
862
863   return GST_FLOW_OK;
864 }
865
866 static void
867 gst_mpeg_audio_parse_handle_first_frame (GstMpegAudioParse * mp3parse,
868     GstBuffer * buf)
869 {
870   const guint32 xing_id = 0x58696e67;   /* 'Xing' in hex */
871   const guint32 info_id = 0x496e666f;   /* 'Info' in hex - found in LAME CBR files */
872   const guint32 vbri_id = 0x56425249;   /* 'VBRI' in hex */
873   const guint32 lame_id = 0x4c414d45;   /* 'LAME' in hex */
874   gint offset_xing, offset_vbri;
875   guint64 avail;
876   gint64 upstream_total_bytes = 0;
877   guint32 read_id_xing = 0, read_id_vbri = 0;
878   GstMapInfo map;
879   guint8 *data;
880   guint bitrate;
881
882   if (mp3parse->sent_codec_tag)
883     return;
884
885   /* Check first frame for Xing info */
886   if (mp3parse->version == 1) { /* MPEG-1 file */
887     if (mp3parse->channels == 1)
888       offset_xing = 0x11;
889     else
890       offset_xing = 0x20;
891   } else {                      /* MPEG-2 header */
892     if (mp3parse->channels == 1)
893       offset_xing = 0x09;
894     else
895       offset_xing = 0x11;
896   }
897
898   /* The VBRI tag is always at offset 0x20 */
899   offset_vbri = 0x20;
900
901   /* Skip the 4 bytes of the MP3 header too */
902   offset_xing += 4;
903   offset_vbri += 4;
904
905   /* Check if we have enough data to read the Xing header */
906   gst_buffer_map (buf, &map, GST_MAP_READ);
907   data = map.data;
908   avail = map.size;
909
910   if (avail >= offset_xing + 4) {
911     read_id_xing = GST_READ_UINT32_BE (data + offset_xing);
912   }
913   if (avail >= offset_vbri + 4) {
914     read_id_vbri = GST_READ_UINT32_BE (data + offset_vbri);
915   }
916
917   /* obtain real upstream total bytes */
918   if (!gst_pad_peer_query_duration (GST_BASE_PARSE_SINK_PAD (mp3parse),
919           GST_FORMAT_BYTES, &upstream_total_bytes))
920     upstream_total_bytes = 0;
921
922   if (read_id_xing == xing_id || read_id_xing == info_id) {
923     guint32 xing_flags;
924     guint bytes_needed = offset_xing + 8;
925     gint64 total_bytes;
926     GstClockTime total_time;
927
928     GST_DEBUG_OBJECT (mp3parse, "Found Xing header marker 0x%x", xing_id);
929
930     /* Move data after Xing header */
931     data += offset_xing + 4;
932
933     /* Read 4 base bytes of flags, big-endian */
934     xing_flags = GST_READ_UINT32_BE (data);
935     data += 4;
936     if (xing_flags & XING_FRAMES_FLAG)
937       bytes_needed += 4;
938     if (xing_flags & XING_BYTES_FLAG)
939       bytes_needed += 4;
940     if (xing_flags & XING_TOC_FLAG)
941       bytes_needed += 100;
942     if (xing_flags & XING_VBR_SCALE_FLAG)
943       bytes_needed += 4;
944     if (avail < bytes_needed) {
945       GST_DEBUG_OBJECT (mp3parse,
946           "Not enough data to read Xing header (need %d)", bytes_needed);
947       goto cleanup;
948     }
949
950     GST_DEBUG_OBJECT (mp3parse, "Reading Xing header");
951     mp3parse->xing_flags = xing_flags;
952
953     if (xing_flags & XING_FRAMES_FLAG) {
954       mp3parse->xing_frames = GST_READ_UINT32_BE (data);
955       if (mp3parse->xing_frames == 0) {
956         GST_WARNING_OBJECT (mp3parse,
957             "Invalid number of frames in Xing header");
958         mp3parse->xing_flags &= ~XING_FRAMES_FLAG;
959       } else {
960         mp3parse->xing_total_time = gst_util_uint64_scale (GST_SECOND,
961             (guint64) (mp3parse->xing_frames) * (mp3parse->spf),
962             mp3parse->rate);
963       }
964
965       data += 4;
966     } else {
967       mp3parse->xing_frames = 0;
968       mp3parse->xing_total_time = 0;
969     }
970
971     if (xing_flags & XING_BYTES_FLAG) {
972       mp3parse->xing_bytes = GST_READ_UINT32_BE (data);
973       if (mp3parse->xing_bytes == 0) {
974         GST_WARNING_OBJECT (mp3parse, "Invalid number of bytes in Xing header");
975         mp3parse->xing_flags &= ~XING_BYTES_FLAG;
976       }
977       data += 4;
978     } else {
979       mp3parse->xing_bytes = 0;
980     }
981
982     /* If we know the upstream size and duration, compute the
983      * total bitrate, rounded up to the nearest kbit/sec */
984     if ((total_time = mp3parse->xing_total_time) &&
985         (total_bytes = mp3parse->xing_bytes)) {
986       mp3parse->xing_bitrate = gst_util_uint64_scale (total_bytes,
987           8 * GST_SECOND, total_time);
988       mp3parse->xing_bitrate += 500;
989       mp3parse->xing_bitrate -= mp3parse->xing_bitrate % 1000;
990     }
991
992     if (xing_flags & XING_TOC_FLAG) {
993       int i, percent = 0;
994       guchar *table = mp3parse->xing_seek_table;
995       guchar old = 0, new;
996       guint first;
997
998       first = data[0];
999       GST_DEBUG_OBJECT (mp3parse,
1000           "Subtracting initial offset of %d bytes from Xing TOC", first);
1001
1002       /* xing seek table: percent time -> 1/256 bytepos */
1003       for (i = 0; i < 100; i++) {
1004         new = data[i] - first;
1005         if (old > new) {
1006           GST_WARNING_OBJECT (mp3parse, "Skipping broken Xing TOC");
1007           mp3parse->xing_flags &= ~XING_TOC_FLAG;
1008           goto skip_toc;
1009         }
1010         mp3parse->xing_seek_table[i] = old = new;
1011       }
1012
1013       /* build inverse table: 1/256 bytepos -> 1/100 percent time */
1014       for (i = 0; i < 256; i++) {
1015         while (percent < 99 && table[percent + 1] <= i)
1016           percent++;
1017
1018         if (table[percent] == i) {
1019           mp3parse->xing_seek_table_inverse[i] = percent * 100;
1020         } else if (percent < 99 && table[percent]) {
1021           gdouble fa, fb, fx;
1022           gint a = percent, b = percent + 1;
1023
1024           fa = table[a];
1025           fb = table[b];
1026           fx = (b - a) / (fb - fa) * (i - fa) + a;
1027           mp3parse->xing_seek_table_inverse[i] = (guint16) (fx * 100);
1028         } else if (percent == 99) {
1029           gdouble fa, fb, fx;
1030           gint a = percent, b = 100;
1031
1032           fa = table[a];
1033           fb = 256.0;
1034           fx = (b - a) / (fb - fa) * (i - fa) + a;
1035           mp3parse->xing_seek_table_inverse[i] = (guint16) (fx * 100);
1036         }
1037       }
1038     skip_toc:
1039       data += 100;
1040     } else {
1041       memset (mp3parse->xing_seek_table, 0, sizeof (mp3parse->xing_seek_table));
1042       memset (mp3parse->xing_seek_table_inverse, 0,
1043           sizeof (mp3parse->xing_seek_table_inverse));
1044     }
1045
1046     if (xing_flags & XING_VBR_SCALE_FLAG) {
1047       mp3parse->xing_vbr_scale = GST_READ_UINT32_BE (data);
1048       data += 4;
1049     } else
1050       mp3parse->xing_vbr_scale = 0;
1051
1052     GST_DEBUG_OBJECT (mp3parse, "Xing header reported %u frames, time %"
1053         GST_TIME_FORMAT ", %u bytes, vbr scale %u", mp3parse->xing_frames,
1054         GST_TIME_ARGS (mp3parse->xing_total_time), mp3parse->xing_bytes,
1055         mp3parse->xing_vbr_scale);
1056
1057     /* check for truncated file */
1058     if (upstream_total_bytes && mp3parse->xing_bytes &&
1059         mp3parse->xing_bytes * 0.8 > upstream_total_bytes) {
1060       GST_WARNING_OBJECT (mp3parse, "File appears to have been truncated; "
1061           "invalidating Xing header duration and size");
1062       mp3parse->xing_flags &= ~XING_BYTES_FLAG;
1063       mp3parse->xing_flags &= ~XING_FRAMES_FLAG;
1064     }
1065
1066     /* Optional LAME tag? */
1067     if (avail - bytes_needed >= 36 && GST_READ_UINT32_BE (data) == lame_id) {
1068       gchar lame_version[10] = { 0, };
1069       guint tag_rev;
1070       guint32 encoder_delay, encoder_padding;
1071
1072       memcpy (lame_version, data, 9);
1073       data += 9;
1074       tag_rev = data[0] >> 4;
1075       GST_DEBUG_OBJECT (mp3parse, "Found LAME tag revision %d created by '%s'",
1076           tag_rev, lame_version);
1077
1078       /* Skip all the information we're not interested in */
1079       data += 12;
1080       /* Encoder delay and end padding */
1081       encoder_delay = GST_READ_UINT24_BE (data);
1082       encoder_delay >>= 12;
1083       encoder_padding = GST_READ_UINT24_BE (data);
1084       encoder_padding &= 0x000fff;
1085
1086       mp3parse->encoder_delay = encoder_delay;
1087       mp3parse->encoder_padding = encoder_padding;
1088
1089       GST_DEBUG_OBJECT (mp3parse, "Encoder delay %u, encoder padding %u",
1090           encoder_delay, encoder_padding);
1091     }
1092   } else if (read_id_vbri == vbri_id) {
1093     gint64 total_bytes, total_frames;
1094     GstClockTime total_time;
1095     guint16 nseek_points;
1096
1097     GST_DEBUG_OBJECT (mp3parse, "Found VBRI header marker 0x%x", vbri_id);
1098
1099     if (avail < offset_vbri + 26) {
1100       GST_DEBUG_OBJECT (mp3parse,
1101           "Not enough data to read VBRI header (need %d)", offset_vbri + 26);
1102       goto cleanup;
1103     }
1104
1105     GST_DEBUG_OBJECT (mp3parse, "Reading VBRI header");
1106
1107     /* Move data after VBRI header */
1108     data += offset_vbri + 4;
1109
1110     if (GST_READ_UINT16_BE (data) != 0x0001) {
1111       GST_WARNING_OBJECT (mp3parse,
1112           "Unsupported VBRI version 0x%x", GST_READ_UINT16_BE (data));
1113       goto cleanup;
1114     }
1115     data += 2;
1116
1117     /* Skip encoder delay */
1118     data += 2;
1119
1120     /* Skip quality */
1121     data += 2;
1122
1123     total_bytes = GST_READ_UINT32_BE (data);
1124     if (total_bytes != 0)
1125       mp3parse->vbri_bytes = total_bytes;
1126     data += 4;
1127
1128     total_frames = GST_READ_UINT32_BE (data);
1129     if (total_frames != 0) {
1130       mp3parse->vbri_frames = total_frames;
1131       mp3parse->vbri_total_time = gst_util_uint64_scale (GST_SECOND,
1132           (guint64) (mp3parse->vbri_frames) * (mp3parse->spf), mp3parse->rate);
1133     }
1134     data += 4;
1135
1136     /* If we know the upstream size and duration, compute the
1137      * total bitrate, rounded up to the nearest kbit/sec */
1138     if ((total_time = mp3parse->vbri_total_time) &&
1139         (total_bytes = mp3parse->vbri_bytes)) {
1140       mp3parse->vbri_bitrate = gst_util_uint64_scale (total_bytes,
1141           8 * GST_SECOND, total_time);
1142       mp3parse->vbri_bitrate += 500;
1143       mp3parse->vbri_bitrate -= mp3parse->vbri_bitrate % 1000;
1144     }
1145
1146     nseek_points = GST_READ_UINT16_BE (data);
1147     data += 2;
1148
1149     if (nseek_points > 0) {
1150       guint scale, seek_bytes, seek_frames;
1151       gint i;
1152
1153       mp3parse->vbri_seek_points = nseek_points;
1154
1155       scale = GST_READ_UINT16_BE (data);
1156       data += 2;
1157
1158       seek_bytes = GST_READ_UINT16_BE (data);
1159       data += 2;
1160
1161       seek_frames = GST_READ_UINT16_BE (data);
1162
1163       if (scale == 0 || seek_bytes == 0 || seek_bytes > 4 || seek_frames == 0) {
1164         GST_WARNING_OBJECT (mp3parse, "Unsupported VBRI seek table");
1165         goto out_vbri;
1166       }
1167
1168       if (avail < offset_vbri + 26 + nseek_points * seek_bytes) {
1169         GST_WARNING_OBJECT (mp3parse,
1170             "Not enough data to read VBRI seek table (need %d)",
1171             offset_vbri + 26 + nseek_points * seek_bytes);
1172         goto out_vbri;
1173       }
1174
1175       if (seek_frames * nseek_points < total_frames - seek_frames ||
1176           seek_frames * nseek_points > total_frames + seek_frames) {
1177         GST_WARNING_OBJECT (mp3parse,
1178             "VBRI seek table doesn't cover the complete file");
1179         goto out_vbri;
1180       }
1181
1182       data = map.data;
1183       data += offset_vbri + 26;
1184
1185       /* VBRI seek table: frame/seek_frames -> byte */
1186       mp3parse->vbri_seek_table = g_new (guint32, nseek_points);
1187       if (seek_bytes == 4)
1188         for (i = 0; i < nseek_points; i++) {
1189           mp3parse->vbri_seek_table[i] = GST_READ_UINT32_BE (data) * scale;
1190           data += 4;
1191       } else if (seek_bytes == 3)
1192         for (i = 0; i < nseek_points; i++) {
1193           mp3parse->vbri_seek_table[i] = GST_READ_UINT24_BE (data) * scale;
1194           data += 3;
1195       } else if (seek_bytes == 2)
1196         for (i = 0; i < nseek_points; i++) {
1197           mp3parse->vbri_seek_table[i] = GST_READ_UINT16_BE (data) * scale;
1198           data += 2;
1199       } else                    /* seek_bytes == 1 */
1200         for (i = 0; i < nseek_points; i++) {
1201           mp3parse->vbri_seek_table[i] = GST_READ_UINT8 (data) * scale;
1202           data += 1;
1203         }
1204     }
1205   out_vbri:
1206
1207     GST_DEBUG_OBJECT (mp3parse, "VBRI header reported %u frames, time %"
1208         GST_TIME_FORMAT ", bytes %u", mp3parse->vbri_frames,
1209         GST_TIME_ARGS (mp3parse->vbri_total_time), mp3parse->vbri_bytes);
1210
1211     /* check for truncated file */
1212     if (upstream_total_bytes && mp3parse->vbri_bytes &&
1213         mp3parse->vbri_bytes * 0.8 > upstream_total_bytes) {
1214       GST_WARNING_OBJECT (mp3parse, "File appears to have been truncated; "
1215           "invalidating VBRI header duration and size");
1216       mp3parse->vbri_valid = FALSE;
1217     } else {
1218       mp3parse->vbri_valid = TRUE;
1219     }
1220   } else {
1221     GST_DEBUG_OBJECT (mp3parse,
1222         "Xing, LAME or VBRI header not found in first frame");
1223   }
1224
1225   /* set duration if tables provided a valid one */
1226   if (mp3parse->xing_flags & XING_FRAMES_FLAG) {
1227     gst_base_parse_set_duration (GST_BASE_PARSE (mp3parse), GST_FORMAT_TIME,
1228         mp3parse->xing_total_time, 0);
1229   }
1230   if (mp3parse->vbri_total_time != 0 && mp3parse->vbri_valid) {
1231     gst_base_parse_set_duration (GST_BASE_PARSE (mp3parse), GST_FORMAT_TIME,
1232         mp3parse->vbri_total_time, 0);
1233   }
1234
1235   /* tell baseclass how nicely we can seek, and a bitrate if one found */
1236   /* FIXME: fill index with seek table */
1237 #if 0
1238   seekable = GST_BASE_PARSE_SEEK_DEFAULT;
1239   if ((mp3parse->xing_flags & XING_TOC_FLAG) && mp3parse->xing_bytes &&
1240       mp3parse->xing_total_time)
1241     seekable = GST_BASE_PARSE_SEEK_TABLE;
1242
1243   if (mp3parse->vbri_seek_table && mp3parse->vbri_bytes &&
1244       mp3parse->vbri_total_time)
1245     seekable = GST_BASE_PARSE_SEEK_TABLE;
1246 #endif
1247
1248   if (mp3parse->xing_bitrate)
1249     bitrate = mp3parse->xing_bitrate;
1250   else if (mp3parse->vbri_bitrate)
1251     bitrate = mp3parse->vbri_bitrate;
1252   else
1253     bitrate = 0;
1254
1255   gst_base_parse_set_average_bitrate (GST_BASE_PARSE (mp3parse), bitrate);
1256
1257 cleanup:
1258   gst_buffer_unmap (buf, &map);
1259 }
1260
1261 static gboolean
1262 gst_mpeg_audio_parse_time_to_bytepos (GstMpegAudioParse * mp3parse,
1263     GstClockTime ts, gint64 * bytepos)
1264 {
1265   gint64 total_bytes;
1266   GstClockTime total_time;
1267
1268   /* If XING seek table exists use this for time->byte conversion */
1269   if ((mp3parse->xing_flags & XING_TOC_FLAG) &&
1270       (total_bytes = mp3parse->xing_bytes) &&
1271       (total_time = mp3parse->xing_total_time)) {
1272     gdouble fa, fb, fx;
1273     gdouble percent =
1274         CLAMP ((100.0 * gst_util_guint64_to_gdouble (ts)) /
1275         gst_util_guint64_to_gdouble (total_time), 0.0, 100.0);
1276     gint index = CLAMP (percent, 0, 99);
1277
1278     fa = mp3parse->xing_seek_table[index];
1279     if (index < 99)
1280       fb = mp3parse->xing_seek_table[index + 1];
1281     else
1282       fb = 256.0;
1283
1284     fx = fa + (fb - fa) * (percent - index);
1285
1286     *bytepos = (1.0 / 256.0) * fx * total_bytes;
1287
1288     return TRUE;
1289   }
1290
1291   if (mp3parse->vbri_seek_table && (total_bytes = mp3parse->vbri_bytes) &&
1292       (total_time = mp3parse->vbri_total_time)) {
1293     gint i, j;
1294     gdouble a, b, fa, fb;
1295
1296     i = gst_util_uint64_scale (ts, mp3parse->vbri_seek_points - 1, total_time);
1297     i = CLAMP (i, 0, mp3parse->vbri_seek_points - 1);
1298
1299     a = gst_guint64_to_gdouble (gst_util_uint64_scale (i, total_time,
1300             mp3parse->vbri_seek_points));
1301     fa = 0.0;
1302     for (j = i; j >= 0; j--)
1303       fa += mp3parse->vbri_seek_table[j];
1304
1305     if (i + 1 < mp3parse->vbri_seek_points) {
1306       b = gst_guint64_to_gdouble (gst_util_uint64_scale (i + 1, total_time,
1307               mp3parse->vbri_seek_points));
1308       fb = fa + mp3parse->vbri_seek_table[i + 1];
1309     } else {
1310       b = gst_guint64_to_gdouble (total_time);
1311       fb = total_bytes;
1312     }
1313
1314     *bytepos = fa + ((fb - fa) / (b - a)) * (gst_guint64_to_gdouble (ts) - a);
1315
1316     return TRUE;
1317   }
1318
1319   /* If we have had a constant bit rate (so far), use it directly, as it
1320    * may give slightly more accurate results than the base class. */
1321   if (mp3parse->bitrate_is_constant && mp3parse->hdr_bitrate) {
1322     *bytepos = gst_util_uint64_scale (ts, mp3parse->hdr_bitrate,
1323         8 * GST_SECOND);
1324     return TRUE;
1325   }
1326
1327   return FALSE;
1328 }
1329
1330 static gboolean
1331 gst_mpeg_audio_parse_bytepos_to_time (GstMpegAudioParse * mp3parse,
1332     gint64 bytepos, GstClockTime * ts)
1333 {
1334   gint64 total_bytes;
1335   GstClockTime total_time;
1336
1337   /* If XING seek table exists use this for byte->time conversion */
1338   if ((mp3parse->xing_flags & XING_TOC_FLAG) &&
1339       (total_bytes = mp3parse->xing_bytes) &&
1340       (total_time = mp3parse->xing_total_time)) {
1341     gdouble fa, fb, fx;
1342     gdouble pos;
1343     gint index;
1344
1345     pos = CLAMP ((bytepos * 256.0) / total_bytes, 0.0, 256.0);
1346     index = CLAMP (pos, 0, 255);
1347     fa = mp3parse->xing_seek_table_inverse[index];
1348     if (index < 255)
1349       fb = mp3parse->xing_seek_table_inverse[index + 1];
1350     else
1351       fb = 10000.0;
1352
1353     fx = fa + (fb - fa) * (pos - index);
1354
1355     *ts = (1.0 / 10000.0) * fx * gst_util_guint64_to_gdouble (total_time);
1356
1357     return TRUE;
1358   }
1359
1360   if (mp3parse->vbri_seek_table &&
1361       (total_bytes = mp3parse->vbri_bytes) &&
1362       (total_time = mp3parse->vbri_total_time)) {
1363     gint i = 0;
1364     guint64 sum = 0;
1365     gdouble a, b, fa, fb;
1366
1367     do {
1368       sum += mp3parse->vbri_seek_table[i];
1369       i++;
1370     } while (i + 1 < mp3parse->vbri_seek_points
1371         && sum + mp3parse->vbri_seek_table[i] < bytepos);
1372     i--;
1373
1374     a = gst_guint64_to_gdouble (sum);
1375     fa = gst_guint64_to_gdouble (gst_util_uint64_scale (i, total_time,
1376             mp3parse->vbri_seek_points));
1377
1378     if (i + 1 < mp3parse->vbri_seek_points) {
1379       b = a + mp3parse->vbri_seek_table[i + 1];
1380       fb = gst_guint64_to_gdouble (gst_util_uint64_scale (i + 1, total_time,
1381               mp3parse->vbri_seek_points));
1382     } else {
1383       b = total_bytes;
1384       fb = gst_guint64_to_gdouble (total_time);
1385     }
1386
1387     *ts = gst_gdouble_to_guint64 (fa + ((fb - fa) / (b - a)) * (bytepos - a));
1388
1389     return TRUE;
1390   }
1391
1392   /* If we have had a constant bit rate (so far), use it directly, as it
1393    * may give slightly more accurate results than the base class. */
1394   if (mp3parse->bitrate_is_constant && mp3parse->hdr_bitrate) {
1395     *ts = gst_util_uint64_scale (bytepos, 8 * GST_SECOND,
1396         mp3parse->hdr_bitrate);
1397     return TRUE;
1398   }
1399
1400   return FALSE;
1401 }
1402
1403 static gboolean
1404 gst_mpeg_audio_parse_convert (GstBaseParse * parse, GstFormat src_format,
1405     gint64 src_value, GstFormat dest_format, gint64 * dest_value)
1406 {
1407   GstMpegAudioParse *mp3parse = GST_MPEG_AUDIO_PARSE (parse);
1408   gboolean res = FALSE;
1409
1410   if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES)
1411     res =
1412         gst_mpeg_audio_parse_time_to_bytepos (mp3parse, src_value, dest_value);
1413   else if (src_format == GST_FORMAT_BYTES && dest_format == GST_FORMAT_TIME)
1414     res = gst_mpeg_audio_parse_bytepos_to_time (mp3parse, src_value,
1415         (GstClockTime *) dest_value);
1416
1417   /* if no tables, fall back to default estimated rate based conversion */
1418   if (!res)
1419     return gst_base_parse_convert_default (parse, src_format, src_value,
1420         dest_format, dest_value);
1421
1422   return res;
1423 }
1424
1425 static GstFlowReturn
1426 gst_mpeg_audio_parse_pre_push_frame (GstBaseParse * parse,
1427     GstBaseParseFrame * frame)
1428 {
1429   GstMpegAudioParse *mp3parse = GST_MPEG_AUDIO_PARSE (parse);
1430   GstTagList *taglist = NULL;
1431
1432   /* we will create a taglist (if any of the parameters has changed)
1433    * to add the tags that changed */
1434   if (mp3parse->last_posted_crc != mp3parse->last_crc) {
1435     gboolean using_crc;
1436
1437     if (!taglist)
1438       taglist = gst_tag_list_new_empty ();
1439
1440     mp3parse->last_posted_crc = mp3parse->last_crc;
1441     if (mp3parse->last_posted_crc == CRC_PROTECTED) {
1442       using_crc = TRUE;
1443     } else {
1444       using_crc = FALSE;
1445     }
1446     gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_CRC,
1447         using_crc, NULL);
1448   }
1449
1450   if (mp3parse->last_posted_channel_mode != mp3parse->last_mode) {
1451     if (!taglist)
1452       taglist = gst_tag_list_new_empty ();
1453
1454     mp3parse->last_posted_channel_mode = mp3parse->last_mode;
1455
1456     gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_MODE,
1457         gst_mpeg_audio_channel_mode_get_nick (mp3parse->last_mode), NULL);
1458   }
1459
1460   /* tag sending done late enough in hook to ensure pending events
1461    * have already been sent */
1462   if (taglist != NULL || !mp3parse->sent_codec_tag) {
1463     GstCaps *caps;
1464
1465     if (taglist == NULL)
1466       taglist = gst_tag_list_new_empty ();
1467
1468     /* codec tag */
1469     caps = gst_pad_get_current_caps (GST_BASE_PARSE_SRC_PAD (parse));
1470     if (G_UNLIKELY (caps == NULL)) {
1471       gst_tag_list_unref (taglist);
1472
1473       if (GST_PAD_IS_FLUSHING (GST_BASE_PARSE_SRC_PAD (parse))) {
1474         GST_INFO_OBJECT (parse, "Src pad is flushing");
1475         return GST_FLOW_FLUSHING;
1476       } else {
1477         GST_INFO_OBJECT (parse, "Src pad is not negotiated!");
1478         return GST_FLOW_NOT_NEGOTIATED;
1479       }
1480     }
1481     gst_pb_utils_add_codec_description_to_tag_list (taglist,
1482         GST_TAG_AUDIO_CODEC, caps);
1483     gst_caps_unref (caps);
1484
1485     if (mp3parse->hdr_bitrate > 0 && mp3parse->xing_bitrate == 0 &&
1486         mp3parse->vbri_bitrate == 0) {
1487       /* We don't have a VBR bitrate, so post the available bitrate as
1488        * nominal and let baseparse calculate the real bitrate */
1489       gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1490           GST_TAG_NOMINAL_BITRATE, mp3parse->hdr_bitrate, NULL);
1491     }
1492
1493     /* also signals the end of first-frame processing */
1494     mp3parse->sent_codec_tag = TRUE;
1495   }
1496
1497   /* if the taglist exists, we need to update it so it gets sent out */
1498   if (taglist) {
1499     gst_base_parse_merge_tags (parse, taglist, GST_TAG_MERGE_REPLACE);
1500     gst_tag_list_unref (taglist);
1501   }
1502
1503   /* usual clipping applies */
1504   frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
1505
1506   return GST_FLOW_OK;
1507 }
1508
1509 static void
1510 remove_fields (GstCaps * caps)
1511 {
1512   guint i, n;
1513
1514   n = gst_caps_get_size (caps);
1515   for (i = 0; i < n; i++) {
1516     GstStructure *s = gst_caps_get_structure (caps, i);
1517
1518     gst_structure_remove_field (s, "parsed");
1519   }
1520 }
1521
1522 static GstCaps *
1523 gst_mpeg_audio_parse_get_sink_caps (GstBaseParse * parse, GstCaps * filter)
1524 {
1525   GstCaps *peercaps, *templ;
1526   GstCaps *res;
1527
1528   templ = gst_pad_get_pad_template_caps (GST_BASE_PARSE_SINK_PAD (parse));
1529   if (filter) {
1530     GstCaps *fcopy = gst_caps_copy (filter);
1531     /* Remove the fields we convert */
1532     remove_fields (fcopy);
1533     peercaps = gst_pad_peer_query_caps (GST_BASE_PARSE_SRC_PAD (parse), fcopy);
1534     gst_caps_unref (fcopy);
1535   } else
1536     peercaps = gst_pad_peer_query_caps (GST_BASE_PARSE_SRC_PAD (parse), NULL);
1537
1538   if (peercaps) {
1539     /* Remove the parsed field */
1540     peercaps = gst_caps_make_writable (peercaps);
1541     remove_fields (peercaps);
1542
1543     res = gst_caps_intersect_full (peercaps, templ, GST_CAPS_INTERSECT_FIRST);
1544     gst_caps_unref (peercaps);
1545     gst_caps_unref (templ);
1546   } else {
1547     res = templ;
1548   }
1549
1550   if (filter) {
1551     GstCaps *intersection;
1552
1553     intersection =
1554         gst_caps_intersect_full (filter, res, GST_CAPS_INTERSECT_FIRST);
1555     gst_caps_unref (res);
1556     res = intersection;
1557   }
1558
1559   return res;
1560 }
1561
1562 #ifdef TIZEN_FEATURE_MP3PARSE_MODIFICATION
1563 /**
1564  * gst_mpeg_audio_parse_src_eventfunc:
1565  * @parse: #GstBaseParse. #event
1566  *
1567  * before baseparse handles seek event, check any mode and flag.
1568  *
1569  * Returns: TRUE on success.
1570  */
1571 static gboolean
1572 gst_mpeg_audio_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
1573 {
1574   gboolean handled = FALSE;
1575   GstMpegAudioParse *mp3parse;
1576   mp3parse = GST_MPEG_AUDIO_PARSE (parse);
1577
1578   GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
1579       GST_EVENT_TYPE_NAME (event));
1580
1581   switch (GST_EVENT_TYPE (event)) {
1582     case GST_EVENT_SEEK:
1583     {
1584       GST_INFO_OBJECT (mp3parse, "GST_EVENT_SEEK enter");
1585       if (mp3parse->http_seek_flag) {
1586         GST_INFO_OBJECT (mp3parse,
1587             "souphttpsrc is PULL MODE (so accurate seek mode is OFF)");
1588         /* Check the declaration of this function in the baseparse */
1589         gst_base_parse_set_seek_mode (parse, 0);
1590         goto mp3_seek_null_exit;
1591       }
1592       GST_INFO_OBJECT (mp3parse, "GST_EVENT_SEEK leave");
1593       break;
1594     }
1595     default:
1596       break;
1597   }
1598
1599 mp3_seek_null_exit:
1600   /* call baseparse src_event function to handle event */
1601   handled = GST_BASE_PARSE_CLASS (parent_class)->src_event (parse, event);
1602
1603   return handled;
1604 }
1605 #endif