]> git.sesse.net Git - ffmpeg/blob - libavformat/mp3dec.c
Merge commit 'b18346817d57c96cc47811cf78b26653e96bd304'
[ffmpeg] / libavformat / mp3dec.c
1 /*
2  * MP3 demuxer
3  * Copyright (c) 2003 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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/opt.h"
23 #include "libavutil/avstring.h"
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/crc.h"
26 #include "libavutil/dict.h"
27 #include "libavutil/mathematics.h"
28 #include "avformat.h"
29 #include "internal.h"
30 #include "avio_internal.h"
31 #include "id3v2.h"
32 #include "id3v1.h"
33 #include "replaygain.h"
34
35 #include "libavcodec/avcodec.h"
36 #include "libavcodec/mpegaudiodecheader.h"
37
38 #define XING_FLAG_FRAMES 0x01
39 #define XING_FLAG_SIZE   0x02
40 #define XING_FLAG_TOC    0x04
41 #define XING_FLAC_QSCALE 0x08
42
43 #define XING_TOC_COUNT 100
44
45 typedef struct {
46     AVClass *class;
47     int64_t filesize;
48     int xing_toc;
49     int start_pad;
50     int end_pad;
51     int usetoc;
52     unsigned frames; /* Total number of frames in file */
53     unsigned header_filesize;   /* Total number of bytes in the stream */
54     int is_cbr;
55 } MP3DecContext;
56
57 /* mp3 read */
58
59 static int mp3_read_probe(AVProbeData *p)
60 {
61     int max_frames, first_frames = 0;
62     int fsize, frames;
63     uint32_t header;
64     const uint8_t *buf, *buf0, *buf2, *end;
65     AVCodecContext *avctx = avcodec_alloc_context3(NULL);
66
67     if (!avctx)
68         return AVERROR(ENOMEM);
69
70     buf0 = p->buf;
71     end = p->buf + p->buf_size - sizeof(uint32_t);
72     while(buf0 < end && !*buf0)
73         buf0++;
74
75     max_frames = 0;
76     buf = buf0;
77
78     for(; buf < end; buf= buf2+1) {
79         buf2 = buf;
80         if(ff_mpa_check_header(AV_RB32(buf2)))
81             continue;
82
83         for(frames = 0; buf2 < end; frames++) {
84             int dummy;
85             header = AV_RB32(buf2);
86             fsize = avpriv_mpa_decode_header(avctx, header,
87                                              &dummy, &dummy, &dummy, &dummy);
88             if(fsize < 0)
89                 break;
90             buf2 += fsize;
91         }
92         max_frames = FFMAX(max_frames, frames);
93         if(buf == buf0)
94             first_frames= frames;
95     }
96     avcodec_free_context(&avctx);
97     // keep this in sync with ac3 probe, both need to avoid
98     // issues with MPEG-files!
99     if   (first_frames>=4) return AVPROBE_SCORE_EXTENSION + 1;
100     else if(max_frames>200)return AVPROBE_SCORE_EXTENSION;
101     else if(max_frames>=4 && max_frames >= p->buf_size/10000) return AVPROBE_SCORE_EXTENSION / 2;
102     else if(ff_id3v2_match(buf0, ID3v2_DEFAULT_MAGIC) && 2*ff_id3v2_tag_len(buf0) >= p->buf_size)
103                            return p->buf_size < PROBE_BUF_MAX ? AVPROBE_SCORE_EXTENSION / 4 : AVPROBE_SCORE_EXTENSION - 2;
104     else if(max_frames>=1 && max_frames >= p->buf_size/10000) return 1;
105     else                   return 0;
106 //mpegps_mp3_unrecognized_format.mpg has max_frames=3
107 }
108
109 static void read_xing_toc(AVFormatContext *s, int64_t filesize, int64_t duration)
110 {
111     int i;
112     MP3DecContext *mp3 = s->priv_data;
113     int fill_index = mp3->usetoc && duration > 0;
114
115     if (!filesize &&
116         !(filesize = avio_size(s->pb))) {
117         av_log(s, AV_LOG_WARNING, "Cannot determine file size, skipping TOC table.\n");
118         fill_index = 0;
119     }
120
121     for (i = 0; i < XING_TOC_COUNT; i++) {
122         uint8_t b = avio_r8(s->pb);
123         if (fill_index)
124             av_add_index_entry(s->streams[0],
125                            av_rescale(b, filesize, 256),
126                            av_rescale(i, duration, XING_TOC_COUNT),
127                            0, 0, AVINDEX_KEYFRAME);
128     }
129     if (fill_index)
130         mp3->xing_toc = 1;
131 }
132
133 static void mp3_parse_info_tag(AVFormatContext *s, AVStream *st,
134                                MPADecodeHeader *c, uint32_t spf)
135 {
136 #define LAST_BITS(k, n) ((k) & ((1 << (n)) - 1))
137 #define MIDDLE_BITS(k, m, n) LAST_BITS((k) >> (m), ((n) - (m)))
138
139     uint16_t crc;
140     uint32_t v;
141
142     char version[10];
143
144     uint32_t peak   = 0;
145     int32_t  r_gain = INT32_MIN, a_gain = INT32_MIN;
146
147     MP3DecContext *mp3 = s->priv_data;
148     static const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
149     uint64_t fsize = avio_size(s->pb);
150
151     /* Check for Xing / Info tag */
152     avio_skip(s->pb, xing_offtbl[c->lsf == 1][c->nb_channels == 1]);
153     v = avio_rb32(s->pb);
154     mp3->is_cbr = v == MKBETAG('I', 'n', 'f', 'o');
155     if (v != MKBETAG('X', 'i', 'n', 'g') && !mp3->is_cbr)
156         return;
157
158     v = avio_rb32(s->pb);
159     if (v & XING_FLAG_FRAMES)
160         mp3->frames = avio_rb32(s->pb);
161     if (v & XING_FLAG_SIZE)
162         mp3->header_filesize = avio_rb32(s->pb);
163     if (fsize && mp3->header_filesize) {
164         uint64_t min, delta;
165         min = FFMIN(fsize, mp3->header_filesize);
166         delta = FFMAX(fsize, mp3->header_filesize) - min;
167         if (fsize > mp3->header_filesize && delta > min >> 4) {
168             mp3->frames = 0;
169         } else if (delta > min >> 4) {
170             av_log(s, AV_LOG_WARNING,
171                    "filesize and duration do not match (growing file?)\n");
172         }
173     }
174     if (v & XING_FLAG_TOC)
175         read_xing_toc(s, mp3->header_filesize, av_rescale_q(mp3->frames,
176                                        (AVRational){spf, c->sample_rate},
177                                        st->time_base));
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     v= avio_rb24(s->pb);
224     if(AV_RB32(version) == MKBETAG('L', 'A', 'M', 'E')
225         || AV_RB32(version) == MKBETAG('L', 'a', 'v', 'f')
226         || AV_RB32(version) == MKBETAG('L', 'a', 'v', 'c')
227     ) {
228
229         mp3->start_pad = v>>12;
230         mp3->  end_pad = v&4095;
231         st->skip_samples = mp3->start_pad + 528 + 1;
232         if (mp3->frames) {
233             st->first_discard_sample = -mp3->end_pad + 528 + 1 + mp3->frames * (int64_t)spf;
234             st->last_discard_sample = mp3->frames * (int64_t)spf;
235         }
236         if (!st->start_time)
237             st->start_time = av_rescale_q(st->skip_samples,
238                                             (AVRational){1, c->sample_rate},
239                                             st->time_base);
240         av_log(s, AV_LOG_DEBUG, "pad %d %d\n", mp3->start_pad, mp3->  end_pad);
241     }
242
243     /* Misc */
244     avio_r8(s->pb);
245
246     /* MP3 gain */
247     avio_r8(s->pb);
248
249     /* Preset and surround info */
250     avio_rb16(s->pb);
251
252     /* Music length */
253     avio_rb32(s->pb);
254
255     /* Music CRC */
256     avio_rb16(s->pb);
257
258     /* Info Tag CRC */
259     crc = ffio_get_checksum(s->pb);
260     v   = avio_rb16(s->pb);
261
262     if (v == crc) {
263         ff_replaygain_export_raw(st, r_gain, peak, a_gain, 0);
264         av_dict_set(&st->metadata, "encoder", version, 0);
265     }
266 }
267
268 static void mp3_parse_vbri_tag(AVFormatContext *s, AVStream *st, int64_t base)
269 {
270     uint32_t v;
271     MP3DecContext *mp3 = s->priv_data;
272
273     /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
274     avio_seek(s->pb, base + 4 + 32, SEEK_SET);
275     v = avio_rb32(s->pb);
276     if (v == MKBETAG('V', 'B', 'R', 'I')) {
277         /* Check tag version */
278         if (avio_rb16(s->pb) == 1) {
279             /* skip delay and quality */
280             avio_skip(s->pb, 4);
281             mp3->header_filesize = avio_rb32(s->pb);
282             mp3->frames = avio_rb32(s->pb);
283         }
284     }
285 }
286
287 /**
288  * Try to find Xing/Info/VBRI tags and compute duration from info therein
289  */
290 static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
291 {
292     uint32_t v, spf;
293     MPADecodeHeader c;
294     int vbrtag_size = 0;
295     MP3DecContext *mp3 = s->priv_data;
296
297     ffio_init_checksum(s->pb, ff_crcA001_update, 0);
298
299     v = avio_rb32(s->pb);
300     if(ff_mpa_check_header(v) < 0)
301       return -1;
302
303     if (avpriv_mpegaudio_decode_header(&c, v) == 0)
304         vbrtag_size = c.frame_size;
305     if(c.layer != 3)
306         return -1;
307
308     spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
309
310     mp3->frames = 0;
311     mp3->header_filesize   = 0;
312
313     mp3_parse_info_tag(s, st, &c, spf);
314     mp3_parse_vbri_tag(s, st, base);
315
316     if (!mp3->frames && !mp3->header_filesize)
317         return -1;
318
319     /* Skip the vbr tag frame */
320     avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
321
322     if (mp3->frames)
323         st->duration = av_rescale_q(mp3->frames, (AVRational){spf, c.sample_rate},
324                                     st->time_base);
325     if (mp3->header_filesize && mp3->frames && !mp3->is_cbr)
326         st->codec->bit_rate = av_rescale(mp3->header_filesize, 8 * c.sample_rate, mp3->frames * (int64_t)spf);
327
328     return 0;
329 }
330
331 static int mp3_read_header(AVFormatContext *s)
332 {
333     MP3DecContext *mp3 = s->priv_data;
334     AVStream *st;
335     int64_t off;
336     int ret;
337     int i;
338
339     st = avformat_new_stream(s, NULL);
340     if (!st)
341         return AVERROR(ENOMEM);
342
343     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
344     st->codec->codec_id = AV_CODEC_ID_MP3;
345     st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
346     st->start_time = 0;
347
348     // lcm of all mp3 sample rates
349     avpriv_set_pts_info(st, 64, 1, 14112000);
350
351     s->pb->maxsize = -1;
352     off = avio_tell(s->pb);
353
354     if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
355         ff_id3v1_read(s);
356
357     if(s->pb->seekable)
358         mp3->filesize = avio_size(s->pb);
359
360     if (mp3_parse_vbr_tags(s, st, off) < 0)
361         avio_seek(s->pb, off, SEEK_SET);
362
363     ret = ff_replaygain_export(st, s->metadata);
364     if (ret < 0)
365         return ret;
366
367     // the seek index is relative to the end of the xing vbr headers
368     for (i = 0; i < st->nb_index_entries; i++)
369         st->index_entries[i].pos += avio_tell(s->pb);
370
371     /* the parameters will be extracted from the compressed bitstream */
372     return 0;
373 }
374
375 #define MP3_PACKET_SIZE 1024
376
377 static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
378 {
379     MP3DecContext *mp3 = s->priv_data;
380     int ret, size;
381     int64_t pos;
382
383     size= MP3_PACKET_SIZE;
384     pos = avio_tell(s->pb);
385     if(mp3->filesize > ID3v1_TAG_SIZE && pos < mp3->filesize)
386         size= FFMIN(size, mp3->filesize - pos);
387
388     ret= av_get_packet(s->pb, pkt, size);
389     if (ret <= 0) {
390         if(ret<0)
391             return ret;
392         return AVERROR_EOF;
393     }
394
395     pkt->flags &= ~AV_PKT_FLAG_CORRUPT;
396     pkt->stream_index = 0;
397
398     if (ret >= ID3v1_TAG_SIZE &&
399         memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)
400         ret -= ID3v1_TAG_SIZE;
401
402     /* note: we need to modify the packet size here to handle the last
403        packet */
404     pkt->size = ret;
405     return ret;
406 }
407
408 static int check(AVFormatContext *s, int64_t pos)
409 {
410     int64_t ret = avio_seek(s->pb, pos, SEEK_SET);
411     unsigned header;
412     MPADecodeHeader sd;
413     if (ret < 0)
414         return ret;
415     header = avio_rb32(s->pb);
416     if (ff_mpa_check_header(header) < 0)
417         return -1;
418     if (avpriv_mpegaudio_decode_header(&sd, header) == 1)
419         return -1;
420     return sd.frame_size;
421 }
422
423 static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
424                     int flags)
425 {
426     MP3DecContext *mp3 = s->priv_data;
427     AVIndexEntry *ie, ie1;
428     AVStream *st = s->streams[0];
429     int64_t ret  = av_index_search_timestamp(st, timestamp, flags);
430     int i, j;
431     int dir = (flags&AVSEEK_FLAG_BACKWARD) ? -1 : 1;
432     int64_t best_pos;
433     int best_score;
434
435     if (   mp3->is_cbr
436         && (mp3->usetoc <= 0 || !mp3->xing_toc)
437         && st->duration > 0
438         && mp3->header_filesize > s->internal->data_offset
439         && mp3->frames) {
440         ie = &ie1;
441         timestamp = av_clip64(timestamp, 0, st->duration);
442         ie->timestamp = timestamp;
443         ie->pos       = av_rescale(timestamp, mp3->header_filesize, st->duration) + s->internal->data_offset;
444     } else if (mp3->xing_toc) {
445         if (ret < 0)
446             return ret;
447
448         ie = &st->index_entries[ret];
449     } else {
450         st->skip_samples = timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;
451
452         return -1;
453     }
454
455     avio_seek(s->pb, FFMAX(ie->pos - 4096, 0), SEEK_SET);
456     ret = avio_seek(s->pb, ie->pos, SEEK_SET);
457     if (ret < 0)
458         return ret;
459
460 #define MIN_VALID 3
461     best_pos = ie->pos;
462     best_score = 999;
463     for(i=0; i<4096; i++) {
464         int64_t pos = ie->pos + (dir > 0 ? i - 1024 : -i);
465         int64_t candidate = -1;
466         int score = 999;
467
468         if (pos < 0)
469             continue;
470
471         for(j=0; j<MIN_VALID; j++) {
472             ret = check(s, pos);
473             if(ret < 0)
474                 break;
475             if ((ie->pos - pos)*dir <= 0 && abs(MIN_VALID/2-j) < score) {
476                 candidate = pos;
477                 score = abs(MIN_VALID/2-j);
478             }
479             pos += ret;
480         }
481         if (best_score > score && j == MIN_VALID) {
482             best_pos = candidate;
483             best_score = score;
484             if(score == 0)
485                 break;
486         }
487     }
488
489     ret = avio_seek(s->pb, best_pos, SEEK_SET);
490     if (ret < 0)
491         return ret;
492     ff_update_cur_dts(s, st, ie->timestamp);
493     st->skip_samples = ie->timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;
494     return 0;
495 }
496
497 static const AVOption options[] = {
498     { "usetoc", "use table of contents", offsetof(MP3DecContext, usetoc), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
499     { NULL },
500 };
501
502 static const AVClass demuxer_class = {
503     .class_name = "mp3",
504     .item_name  = av_default_item_name,
505     .option     = options,
506     .version    = LIBAVUTIL_VERSION_INT,
507     .category   = AV_CLASS_CATEGORY_DEMUXER,
508 };
509
510 AVInputFormat ff_mp3_demuxer = {
511     .name           = "mp3",
512     .long_name      = NULL_IF_CONFIG_SMALL("MP2/3 (MPEG audio layer 2/3)"),
513     .read_probe     = mp3_read_probe,
514     .read_header    = mp3_read_header,
515     .read_packet    = mp3_read_packet,
516     .read_seek      = mp3_seek,
517     .priv_data_size = sizeof(MP3DecContext),
518     .flags          = AVFMT_GENERIC_INDEX,
519     .extensions     = "mp2,mp3,m2a,mpa", /* XXX: use probe */
520     .priv_class     = &demuxer_class,
521 };