mp3: Make the seek more robust
[libav.git] / libavformat / mp3dec.c
1 /*
2 * MP3 demuxer
3 * Copyright (c) 2003 Fabrice Bellard
4 *
5 * This file is part of Libav.
6 *
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * Libav 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 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include "libavutil/avstring.h"
23 #include "libavutil/intreadwrite.h"
24 #include "libavutil/crc.h"
25 #include "libavutil/dict.h"
26 #include "libavutil/mathematics.h"
27 #include "avformat.h"
28 #include "internal.h"
29 #include "avio_internal.h"
30 #include "id3v2.h"
31 #include "id3v1.h"
32 #include "replaygain.h"
33
34 #include "libavcodec/avcodec.h"
35 #include "libavcodec/mpegaudiodecheader.h"
36
37 #define XING_FLAG_FRAMES 0x01
38 #define XING_FLAG_SIZE 0x02
39 #define XING_FLAG_TOC 0x04
40 #define XING_FLAC_QSCALE 0x08
41
42 #define XING_TOC_COUNT 100
43
44 typedef struct MP3DecContext {
45 int xing_toc;
46 unsigned frames; /* Total number of frames in file */
47 unsigned size; /* Total number of bytes in the stream */
48 int is_cbr;
49 } MP3DecContext;
50
51 /* mp3 read */
52
53 static int mp3_read_probe(AVProbeData *p)
54 {
55 int max_frames, first_frames = 0;
56 int fsize, frames, sample_rate;
57 uint32_t header;
58 uint8_t *buf, *buf0, *buf2, *end;
59 AVCodecContext *avctx = avcodec_alloc_context3(NULL);
60
61 if (!avctx)
62 return AVERROR(ENOMEM);
63
64 buf0 = p->buf;
65 end = p->buf + p->buf_size - sizeof(uint32_t);
66 while(buf0 < end && !*buf0)
67 buf0++;
68
69 max_frames = 0;
70 buf = buf0;
71
72 for(; buf < end; buf= buf2+1) {
73 buf2 = buf;
74
75 for(frames = 0; buf2 < end; frames++) {
76 header = AV_RB32(buf2);
77 fsize = avpriv_mpa_decode_header(avctx, header, &sample_rate,
78 &sample_rate, &sample_rate,
79 &sample_rate);
80 if(fsize < 0)
81 break;
82 buf2 += fsize;
83 }
84 max_frames = FFMAX(max_frames, frames);
85 if(buf == buf0)
86 first_frames= frames;
87 }
88 avcodec_free_context(&avctx);
89 // keep this in sync with ac3 probe, both need to avoid
90 // issues with MPEG-files!
91 if (first_frames >= 10)
92 return AVPROBE_SCORE_EXTENSION + 5;
93 if (first_frames >= 4)
94 return AVPROBE_SCORE_EXTENSION + 1;
95
96 if (max_frames) {
97 int pes = 0, i;
98 unsigned int code = -1;
99
100 #define VIDEO_ID 0x000001e0
101 #define AUDIO_ID 0x000001c0
102 /* do a search for mpegps headers to be able to properly bias
103 * towards mpegps if we detect this stream as both. */
104 for (i = 0; i<p->buf_size; i++) {
105 code = (code << 8) + p->buf[i];
106 if ((code & 0xffffff00) == 0x100) {
107 if ((code & 0x1f0) == VIDEO_ID) pes++;
108 else if((code & 0x1e0) == AUDIO_ID) pes++;
109 }
110 }
111
112 if (pes)
113 max_frames = (max_frames + pes - 1) / pes;
114 }
115 if (max_frames > 500) return AVPROBE_SCORE_EXTENSION;
116 else if (max_frames >= 4) return AVPROBE_SCORE_EXTENSION / 2;
117 else if (max_frames >= 1) return 1;
118 else return 0;
119 //mpegps_mp3_unrecognized_format.mpg has max_frames=3
120 }
121
122 static void read_xing_toc(AVFormatContext *s, int64_t filesize, int64_t duration)
123 {
124 int i;
125 MP3DecContext *mp3 = s->priv_data;
126
127 if (!filesize &&
128 !(filesize = avio_size(s->pb))) {
129 av_log(s, AV_LOG_WARNING, "Cannot determine file size, skipping TOC table.\n");
130 return;
131 }
132
133 for (i = 0; i < XING_TOC_COUNT; i++) {
134 uint8_t b = avio_r8(s->pb);
135
136 av_add_index_entry(s->streams[0],
137 av_rescale(b, filesize, 256),
138 av_rescale(i, duration, XING_TOC_COUNT),
139 0, 0, AVINDEX_KEYFRAME);
140 }
141 mp3->xing_toc = 1;
142 }
143
144 static void mp3_parse_info_tag(AVFormatContext *s, AVStream *st,
145 MPADecodeHeader *c, uint32_t spf)
146 {
147 #define LAST_BITS(k, n) ((k) & ((1 << (n)) - 1))
148 #define MIDDLE_BITS(k, m, n) LAST_BITS((k) >> (m), ((n) - (m)))
149
150 uint16_t crc;
151 uint32_t v;
152
153 char version[10];
154
155 uint32_t peak = 0;
156 int32_t r_gain = INT32_MIN, a_gain = INT32_MIN;
157
158 MP3DecContext *mp3 = s->priv_data;
159 const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
160
161 /* Check for Xing / Info tag */
162 avio_skip(s->pb, xing_offtbl[c->lsf == 1][c->nb_channels == 1]);
163 v = avio_rb32(s->pb);
164 mp3->is_cbr = v == MKBETAG('I', 'n', 'f', 'o');
165 if (v != MKBETAG('X', 'i', 'n', 'g') && !mp3->is_cbr)
166 return;
167
168 v = avio_rb32(s->pb);
169 if (v & XING_FLAG_FRAMES)
170 mp3->frames = avio_rb32(s->pb);
171 if (v & XING_FLAG_SIZE)
172 mp3->size = avio_rb32(s->pb);
173 if (v & XING_FLAG_TOC && mp3->frames)
174 read_xing_toc(s, mp3->size, av_rescale_q(mp3->frames,
175 (AVRational){spf, c->sample_rate},
176 st->time_base));
177
178 /* VBR quality */
179 if (v & XING_FLAC_QSCALE)
180 avio_rb32(s->pb);
181
182 /* Encoder short version string */
183 memset(version, 0, sizeof(version));
184 avio_read(s->pb, version, 9);
185
186 /* Info Tag revision + VBR method */
187 avio_r8(s->pb);
188
189 /* Lowpass filter value */
190 avio_r8(s->pb);
191
192 /* ReplayGain peak */
193 v = avio_rb32(s->pb);
194 peak = av_rescale(v, 100000, 1 << 23);
195
196 /* Radio ReplayGain */
197 v = avio_rb16(s->pb);
198
199 if (MIDDLE_BITS(v, 13, 15) == 1) {
200 r_gain = MIDDLE_BITS(v, 0, 8) * 10000;
201
202 if (v & (1 << 9))
203 r_gain *= -1;
204 }
205
206 /* Audiophile ReplayGain */
207 v = avio_rb16(s->pb);
208
209 if (MIDDLE_BITS(v, 13, 15) == 2) {
210 a_gain = MIDDLE_BITS(v, 0, 8) * 10000;
211
212 if (v & (1 << 9))
213 a_gain *= -1;
214 }
215
216 /* Encoding flags + ATH Type */
217 avio_r8(s->pb);
218
219 /* if ABR {specified bitrate} else {minimal bitrate} */
220 avio_r8(s->pb);
221
222 /* Encoder delays */
223 avio_rb24(s->pb);
224
225 /* Misc */
226 avio_r8(s->pb);
227
228 /* MP3 gain */
229 avio_r8(s->pb);
230
231 /* Preset and surround info */
232 avio_rb16(s->pb);
233
234 /* Music length */
235 avio_rb32(s->pb);
236
237 /* Music CRC */
238 avio_rb16(s->pb);
239
240 /* Info Tag CRC */
241 crc = ffio_get_checksum(s->pb);
242 v = avio_rb16(s->pb);
243
244 if (v == crc) {
245 ff_replaygain_export_raw(st, r_gain, peak, a_gain, 0);
246 av_dict_set(&st->metadata, "encoder", version, 0);
247 }
248 }
249
250 static void mp3_parse_vbri_tag(AVFormatContext *s, AVStream *st, int64_t base)
251 {
252 uint32_t v;
253 MP3DecContext *mp3 = s->priv_data;
254
255 /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
256 avio_seek(s->pb, base + 4 + 32, SEEK_SET);
257 v = avio_rb32(s->pb);
258 if (v == MKBETAG('V', 'B', 'R', 'I')) {
259 /* Check tag version */
260 if (avio_rb16(s->pb) == 1) {
261 /* skip delay and quality */
262 avio_skip(s->pb, 4);
263 mp3->size = avio_rb32(s->pb);
264 mp3->frames = avio_rb32(s->pb);
265 }
266 }
267 }
268
269 /**
270 * Try to find Xing/Info/VBRI tags and compute duration from info therein
271 */
272 static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
273 {
274 uint32_t v, spf;
275 MPADecodeHeader c;
276 int vbrtag_size = 0;
277 MP3DecContext *mp3 = s->priv_data;
278
279 ffio_init_checksum(s->pb, ff_crcA001_update, 0);
280
281 v = avio_rb32(s->pb);
282 if(ff_mpa_check_header(v) < 0)
283 return -1;
284
285 if (avpriv_mpegaudio_decode_header(&c, v) == 0)
286 vbrtag_size = c.frame_size;
287 if(c.layer != 3)
288 return -1;
289
290 spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
291
292 mp3->frames = 0;
293 mp3->size = 0;
294
295 mp3_parse_info_tag(s, st, &c, spf);
296 mp3_parse_vbri_tag(s, st, base);
297
298 if (!mp3->frames && !mp3->size)
299 return -1;
300
301 /* Skip the vbr tag frame */
302 avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
303
304 if (mp3->frames)
305 st->duration = av_rescale_q(mp3->frames, (AVRational){spf, c.sample_rate},
306 st->time_base);
307 if (mp3->size && mp3->frames && !mp3->is_cbr)
308 st->codec->bit_rate = av_rescale(mp3->size, 8 * c.sample_rate, mp3->frames * (int64_t)spf);
309
310 return 0;
311 }
312
313 static int mp3_read_header(AVFormatContext *s)
314 {
315 AVStream *st;
316 int64_t off;
317 int ret;
318
319 st = avformat_new_stream(s, NULL);
320 if (!st)
321 return AVERROR(ENOMEM);
322
323 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
324 st->codec->codec_id = AV_CODEC_ID_MP3;
325 st->need_parsing = AVSTREAM_PARSE_FULL;
326 st->start_time = 0;
327
328 // lcm of all mp3 sample rates
329 avpriv_set_pts_info(st, 64, 1, 14112000);
330
331 off = avio_tell(s->pb);
332
333 if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
334 ff_id3v1_read(s);
335
336 if (mp3_parse_vbr_tags(s, st, off) < 0)
337 avio_seek(s->pb, off, SEEK_SET);
338
339 ret = ff_replaygain_export(st, s->metadata);
340 if (ret < 0)
341 return ret;
342
343 /* the parameters will be extracted from the compressed bitstream */
344 return 0;
345 }
346
347 #define MP3_PACKET_SIZE 1024
348
349 static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
350 {
351 int ret;
352
353 ret = av_get_packet(s->pb, pkt, MP3_PACKET_SIZE);
354 if (ret < 0)
355 return ret;
356
357 pkt->stream_index = 0;
358
359 if (ret > ID3v1_TAG_SIZE &&
360 memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)
361 ret -= ID3v1_TAG_SIZE;
362
363 /* note: we need to modify the packet size here to handle the last
364 packet */
365 pkt->size = ret;
366 return ret;
367 }
368
369 #define SEEK_PACKETS 4
370 #define SEEK_WINDOW (SEEK_PACKETS * MP3_PACKET_SIZE)
371
372 /* The toc entry can position to the wrong byte offset, try to pick
373 * the closest frame by probing the data in a window of 4 packets.
374 */
375
376 static int check(AVIOContext *pb, int64_t pos, int64_t *out_pos)
377 {
378 MPADecodeHeader mh = { 0 };
379 int i;
380 uint32_t header;
381 int64_t off = 0;
382
383
384 for (i = 0; i < SEEK_PACKETS; i++) {
385 off = avio_seek(pb, pos + mh.frame_size, SEEK_SET);
386 if (off < 0)
387 break;
388
389 header = avio_rb32(pb);
390
391 if (ff_mpa_check_header(header) < 0 ||
392 avpriv_mpegaudio_decode_header(&mh, header))
393 break;
394 out_pos[i] = off;
395 }
396
397 return i;
398 }
399
400 static int reposition(AVFormatContext *s, int64_t pos)
401 {
402 int ret, best_valid = -1;
403 int64_t p, best_pos = -1;
404
405 for (p = FFMAX(pos - SEEK_WINDOW / 2, 0); p < pos + SEEK_WINDOW / 2; p++) {
406 int64_t out_pos[SEEK_PACKETS];
407 ret = check(s->pb, p, out_pos);
408
409 if (best_valid < ret) {
410 int i;
411 for (i = 0; i < ret; i++) {
412 if (llabs(best_pos - pos) > llabs(out_pos[i] - pos)) {
413 best_pos = out_pos[i];
414 best_valid = ret;
415 }
416 }
417 if (best_pos == pos && best_valid == SEEK_PACKETS)
418 break;
419 }
420 }
421
422 if (best_valid <= 0)
423 return AVERROR(ENOSYS);
424
425 avio_seek(s->pb, best_pos, SEEK_SET);
426
427 return 0;
428 }
429
430 static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
431 int flags)
432 {
433 MP3DecContext *mp3 = s->priv_data;
434 AVIndexEntry *ie;
435 AVStream *st = s->streams[0];
436 int64_t ret = av_index_search_timestamp(st, timestamp, flags);
437
438 if (!mp3->xing_toc)
439 return AVERROR(ENOSYS);
440
441 if (ret < 0)
442 return ret;
443
444 ie = &st->index_entries[ret];
445
446 ret = reposition(s, ie->pos);
447 if (ret < 0)
448 return ret;
449
450 ff_update_cur_dts(s, st, ie->timestamp);
451
452 return 0;
453 }
454
455 AVInputFormat ff_mp3_demuxer = {
456 .name = "mp3",
457 .long_name = NULL_IF_CONFIG_SMALL("MP2/3 (MPEG audio layer 2/3)"),
458 .read_probe = mp3_read_probe,
459 .read_header = mp3_read_header,
460 .read_packet = mp3_read_packet,
461 .read_seek = mp3_seek,
462 .priv_data_size = sizeof(MP3DecContext),
463 .flags = AVFMT_GENERIC_INDEX,
464 .extensions = "mp2,mp3,m2a,mpa", /* XXX: use probe */
465 };