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 static 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} */
218 delays = avio_rb24(s->pb);
219 st->codecpar->initial_padding = delays >> 12;
220 st->codecpar->trailing_padding = delays & ((1 << 12) - 1);
228 /* Preset and surround info */
238 crc = ffio_get_checksum(s->pb);
239 v = avio_rb16(s->pb);
242 ff_replaygain_export_raw(st, r_gain, peak, a_gain, 0);
243 av_dict_set(&st->metadata, "encoder", version, 0);
247 static void mp3_parse_vbri_tag(AVFormatContext *s, AVStream *st, int64_t base)
250 MP3DecContext *mp3 = s->priv_data;
252 /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
253 avio_seek(s->pb, base + 4 + 32, SEEK_SET);
254 v = avio_rb32(s->pb);
255 if (v == MKBETAG('V', 'B', 'R', 'I')) {
256 /* Check tag version */
257 if (avio_rb16(s->pb) == 1) {
258 /* skip delay and quality */
260 mp3->size = avio_rb32(s->pb);
261 mp3->frames = avio_rb32(s->pb);
267 * Try to find Xing/Info/VBRI tags and compute duration from info therein
269 static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
274 MP3DecContext *mp3 = s->priv_data;
277 ffio_init_checksum(s->pb, ff_crcA001_update, 0);
279 v = avio_rb32(s->pb);
281 ret = avpriv_mpegaudio_decode_header(&c, v);
285 vbrtag_size = c.frame_size;
289 spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
294 mp3_parse_info_tag(s, st, &c, spf);
295 mp3_parse_vbri_tag(s, st, base);
297 if (!mp3->frames && !mp3->size)
300 /* Skip the vbr tag frame */
301 avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
304 st->duration = av_rescale_q(mp3->frames, (AVRational){spf, c.sample_rate},
306 if (mp3->size && mp3->frames && !mp3->is_cbr)
307 st->codecpar->bit_rate = av_rescale(mp3->size, 8 * c.sample_rate, mp3->frames * (int64_t)spf);
312 static int mp3_read_header(AVFormatContext *s)
318 st = avformat_new_stream(s, NULL);
320 return AVERROR(ENOMEM);
322 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
323 st->codecpar->codec_id = AV_CODEC_ID_MP3;
324 st->need_parsing = AVSTREAM_PARSE_FULL;
327 // lcm of all mp3 sample rates
328 avpriv_set_pts_info(st, 64, 1, 14112000);
330 off = avio_tell(s->pb);
332 if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
335 if (mp3_parse_vbr_tags(s, st, off) < 0)
336 avio_seek(s->pb, off, SEEK_SET);
338 ret = ff_replaygain_export(st, s->metadata);
342 /* the parameters will be extracted from the compressed bitstream */
346 #define MP3_PACKET_SIZE 1024
348 static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
352 ret = av_get_packet(s->pb, pkt, MP3_PACKET_SIZE);
356 pkt->stream_index = 0;
358 if (ret > ID3v1_TAG_SIZE &&
359 memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)
360 ret -= ID3v1_TAG_SIZE;
362 /* note: we need to modify the packet size here to handle the last
368 #define SEEK_PACKETS 4
369 #define SEEK_WINDOW (SEEK_PACKETS * MP3_PACKET_SIZE)
371 /* The toc entry can position to the wrong byte offset, try to pick
372 * the closest frame by probing the data in a window of 4 packets.
375 static int check(AVIOContext *pb, int64_t pos, int64_t *out_pos)
377 MPADecodeHeader mh = { 0 };
383 for (i = 0; i < SEEK_PACKETS; i++) {
384 off = avio_seek(pb, pos + mh.frame_size, SEEK_SET);
388 header = avio_rb32(pb);
391 if (avpriv_mpegaudio_decode_header(&mh, header))
399 static int reposition(AVFormatContext *s, int64_t pos)
401 int ret, best_valid = -1;
402 int64_t p, best_pos = -1;
404 for (p = FFMAX(pos - SEEK_WINDOW / 2, 0); p < pos + SEEK_WINDOW / 2; p++) {
405 int64_t out_pos[SEEK_PACKETS];
406 ret = check(s->pb, p, out_pos);
408 if (best_valid < ret) {
410 for (i = 0; i < ret; i++) {
411 if (llabs(best_pos - pos) > llabs(out_pos[i] - pos)) {
412 best_pos = out_pos[i];
416 if (best_pos == pos && best_valid == SEEK_PACKETS)
422 return AVERROR(ENOSYS);
424 p = avio_seek(s->pb, best_pos, SEEK_SET);
431 static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
434 MP3DecContext *mp3 = s->priv_data;
436 AVStream *st = s->streams[0];
437 int64_t ret = av_index_search_timestamp(st, timestamp, flags);
440 return AVERROR(ENOSYS);
445 ie = &st->index_entries[ret];
447 ret = reposition(s, ie->pos);
451 ff_update_cur_dts(s, st, ie->timestamp);
456 AVInputFormat ff_mp3_demuxer = {
458 .long_name = NULL_IF_CONFIG_SMALL("MP2/3 (MPEG audio layer 2/3)"),
459 .read_probe = mp3_read_probe,
460 .read_header = mp3_read_header,
461 .read_packet = mp3_read_packet,
462 .read_seek = mp3_seek,
463 .priv_data_size = sizeof(MP3DecContext),
464 .flags = AVFMT_GENERIC_INDEX,
465 .extensions = "mp2,mp3,m2a,mpa", /* XXX: use probe */