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