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