3 * Copyright (c) 2003 Fabrice Bellard
5 * This file is part of Libav.
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.
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.
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
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"
29 #include "avio_internal.h"
32 #include "replaygain.h"
34 #include "libavcodec/avcodec.h"
35 #include "libavcodec/mpegaudiodecheader.h"
37 #define XING_FLAG_FRAMES 0x01
38 #define XING_FLAG_SIZE 0x02
39 #define XING_FLAG_TOC 0x04
40 #define XING_FLAC_QSCALE 0x08
42 #define XING_TOC_COUNT 100
44 typedef struct MP3DecContext {
46 unsigned frames; /* Total number of frames in file */
47 unsigned size; /* Total number of bytes in the stream */
53 static int mp3_read_probe(AVProbeData *p)
55 int max_frames, first_frames = 0;
58 uint8_t *buf, *buf0, *buf2, *end;
61 end = p->buf + p->buf_size - sizeof(uint32_t);
62 while(buf0 < end && !*buf0)
68 for(; buf < end; buf= buf2+1) {
71 for(frames = 0; buf2 < end; frames++) {
74 header = AV_RB32(buf2);
75 ret = avpriv_mpegaudio_decode_header(&h, header);
80 max_frames = FFMAX(max_frames, frames);
84 // keep this in sync with ac3 probe, both need to avoid
85 // issues with MPEG-files!
86 if (first_frames >= 10)
87 return AVPROBE_SCORE_EXTENSION + 5;
88 if (first_frames >= 4)
89 return AVPROBE_SCORE_EXTENSION + 1;
93 unsigned int code = -1;
95 #define VIDEO_ID 0x000001e0
96 #define AUDIO_ID 0x000001c0
97 /* do a search for mpegps headers to be able to properly bias
98 * towards mpegps if we detect this stream as both. */
99 for (i = 0; i<p->buf_size; i++) {
100 code = (code << 8) + p->buf[i];
101 if ((code & 0xffffff00) == 0x100) {
102 if ((code & 0x1f0) == VIDEO_ID) pes++;
103 else if((code & 0x1e0) == AUDIO_ID) pes++;
108 max_frames = (max_frames + pes - 1) / pes;
110 if (max_frames > 500) return AVPROBE_SCORE_EXTENSION;
111 else if (max_frames >= 4) return AVPROBE_SCORE_EXTENSION / 2;
112 else if (max_frames >= 1) return 1;
114 //mpegps_mp3_unrecognized_format.mpg has max_frames=3
117 static void read_xing_toc(AVFormatContext *s, int64_t filesize, int64_t duration)
120 MP3DecContext *mp3 = s->priv_data;
123 !(filesize = avio_size(s->pb))) {
124 av_log(s, AV_LOG_WARNING, "Cannot determine file size, skipping TOC table.\n");
128 for (i = 0; i < XING_TOC_COUNT; i++) {
129 uint8_t b = avio_r8(s->pb);
131 av_add_index_entry(s->streams[0],
132 av_rescale(b, filesize, 256),
133 av_rescale(i, duration, XING_TOC_COUNT),
134 0, 0, AVINDEX_KEYFRAME);
139 static void mp3_parse_info_tag(AVFormatContext *s, AVStream *st,
140 MPADecodeHeader *c, uint32_t spf)
142 #define LAST_BITS(k, n) ((k) & ((1 << (n)) - 1))
143 #define MIDDLE_BITS(k, m, n) LAST_BITS((k) >> (m), ((n) - (m)))
151 int32_t r_gain = INT32_MIN, a_gain = INT32_MIN;
153 MP3DecContext *mp3 = s->priv_data;
154 const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
156 /* Check for Xing / Info tag */
157 avio_skip(s->pb, xing_offtbl[c->lsf == 1][c->nb_channels == 1]);
158 v = avio_rb32(s->pb);
159 mp3->is_cbr = v == MKBETAG('I', 'n', 'f', 'o');
160 if (v != MKBETAG('X', 'i', 'n', 'g') && !mp3->is_cbr)
163 v = avio_rb32(s->pb);
164 if (v & XING_FLAG_FRAMES)
165 mp3->frames = avio_rb32(s->pb);
166 if (v & XING_FLAG_SIZE)
167 mp3->size = avio_rb32(s->pb);
168 if (v & XING_FLAG_TOC && mp3->frames)
169 read_xing_toc(s, mp3->size, av_rescale_q(mp3->frames,
170 (AVRational){spf, c->sample_rate},
174 if (v & XING_FLAC_QSCALE)
177 /* Encoder short version string */
178 memset(version, 0, sizeof(version));
179 avio_read(s->pb, version, 9);
181 /* Info Tag revision + VBR method */
184 /* Lowpass filter value */
187 /* ReplayGain peak */
188 v = avio_rb32(s->pb);
189 peak = av_rescale(v, 100000, 1 << 23);
191 /* Radio ReplayGain */
192 v = avio_rb16(s->pb);
194 if (MIDDLE_BITS(v, 13, 15) == 1) {
195 r_gain = MIDDLE_BITS(v, 0, 8) * 10000;
201 /* Audiophile ReplayGain */
202 v = avio_rb16(s->pb);
204 if (MIDDLE_BITS(v, 13, 15) == 2) {
205 a_gain = MIDDLE_BITS(v, 0, 8) * 10000;
211 /* Encoding flags + ATH Type */
214 /* if ABR {specified bitrate} else {minimal bitrate} */
226 /* Preset and surround info */
236 crc = ffio_get_checksum(s->pb);
237 v = avio_rb16(s->pb);
240 ff_replaygain_export_raw(st, r_gain, peak, a_gain, 0);
241 av_dict_set(&st->metadata, "encoder", version, 0);
245 static void mp3_parse_vbri_tag(AVFormatContext *s, AVStream *st, int64_t base)
248 MP3DecContext *mp3 = s->priv_data;
250 /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
251 avio_seek(s->pb, base + 4 + 32, SEEK_SET);
252 v = avio_rb32(s->pb);
253 if (v == MKBETAG('V', 'B', 'R', 'I')) {
254 /* Check tag version */
255 if (avio_rb16(s->pb) == 1) {
256 /* skip delay and quality */
258 mp3->size = avio_rb32(s->pb);
259 mp3->frames = avio_rb32(s->pb);
265 * Try to find Xing/Info/VBRI tags and compute duration from info therein
267 static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
272 MP3DecContext *mp3 = s->priv_data;
275 ffio_init_checksum(s->pb, ff_crcA001_update, 0);
277 v = avio_rb32(s->pb);
279 ret = avpriv_mpegaudio_decode_header(&c, v);
283 vbrtag_size = c.frame_size;
287 spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
292 mp3_parse_info_tag(s, st, &c, spf);
293 mp3_parse_vbri_tag(s, st, base);
295 if (!mp3->frames && !mp3->size)
298 /* Skip the vbr tag frame */
299 avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
302 st->duration = av_rescale_q(mp3->frames, (AVRational){spf, c.sample_rate},
304 if (mp3->size && mp3->frames && !mp3->is_cbr)
305 st->codecpar->bit_rate = av_rescale(mp3->size, 8 * c.sample_rate, mp3->frames * (int64_t)spf);
310 static int mp3_read_header(AVFormatContext *s)
316 st = avformat_new_stream(s, NULL);
318 return AVERROR(ENOMEM);
320 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
321 st->codecpar->codec_id = AV_CODEC_ID_MP3;
322 st->need_parsing = AVSTREAM_PARSE_FULL;
325 // lcm of all mp3 sample rates
326 avpriv_set_pts_info(st, 64, 1, 14112000);
328 off = avio_tell(s->pb);
330 if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
333 if (mp3_parse_vbr_tags(s, st, off) < 0)
334 avio_seek(s->pb, off, SEEK_SET);
336 ret = ff_replaygain_export(st, s->metadata);
340 /* the parameters will be extracted from the compressed bitstream */
344 #define MP3_PACKET_SIZE 1024
346 static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
350 ret = av_get_packet(s->pb, pkt, MP3_PACKET_SIZE);
354 pkt->stream_index = 0;
356 if (ret > ID3v1_TAG_SIZE &&
357 memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)
358 ret -= ID3v1_TAG_SIZE;
360 /* note: we need to modify the packet size here to handle the last
366 #define SEEK_PACKETS 4
367 #define SEEK_WINDOW (SEEK_PACKETS * MP3_PACKET_SIZE)
369 /* The toc entry can position to the wrong byte offset, try to pick
370 * the closest frame by probing the data in a window of 4 packets.
373 static int check(AVIOContext *pb, int64_t pos, int64_t *out_pos)
375 MPADecodeHeader mh = { 0 };
381 for (i = 0; i < SEEK_PACKETS; i++) {
382 off = avio_seek(pb, pos + mh.frame_size, SEEK_SET);
386 header = avio_rb32(pb);
389 if (avpriv_mpegaudio_decode_header(&mh, header))
397 static int reposition(AVFormatContext *s, int64_t pos)
399 int ret, best_valid = -1;
400 int64_t p, best_pos = -1;
402 for (p = FFMAX(pos - SEEK_WINDOW / 2, 0); p < pos + SEEK_WINDOW / 2; p++) {
403 int64_t out_pos[SEEK_PACKETS];
404 ret = check(s->pb, p, out_pos);
406 if (best_valid < ret) {
408 for (i = 0; i < ret; i++) {
409 if (llabs(best_pos - pos) > llabs(out_pos[i] - pos)) {
410 best_pos = out_pos[i];
414 if (best_pos == pos && best_valid == SEEK_PACKETS)
420 return AVERROR(ENOSYS);
422 p = avio_seek(s->pb, best_pos, SEEK_SET);
429 static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
432 MP3DecContext *mp3 = s->priv_data;
434 AVStream *st = s->streams[0];
435 int64_t ret = av_index_search_timestamp(st, timestamp, flags);
438 return AVERROR(ENOSYS);
443 ie = &st->index_entries[ret];
445 ret = reposition(s, ie->pos);
449 ff_update_cur_dts(s, st, ie->timestamp);
454 AVInputFormat ff_mp3_demuxer = {
456 .long_name = NULL_IF_CONFIG_SMALL("MP2/3 (MPEG audio layer 2/3)"),
457 .read_probe = mp3_read_probe,
458 .read_header = mp3_read_header,
459 .read_packet = mp3_read_packet,
460 .read_seek = mp3_seek,
461 .priv_data_size = sizeof(MP3DecContext),
462 .flags = AVFMT_GENERIC_INDEX,
463 .extensions = "mp2,mp3,m2a,mpa", /* XXX: use probe */