mp3dec: move XING/Info and VBRI parsing into their own functions
[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/dict.h"
25 #include "libavutil/mathematics.h"
26 #include "avformat.h"
27 #include "internal.h"
28 #include "id3v2.h"
29 #include "id3v1.h"
30 #include "replaygain.h"
31
32 #include "libavcodec/mpegaudiodecheader.h"
33
34 #define XING_FLAG_FRAMES 0x01
35 #define XING_FLAG_SIZE 0x02
36 #define XING_FLAG_TOC 0x04
37
38 #define XING_TOC_COUNT 100
39
40 typedef struct MP3DecContext {
41 int xing_toc;
42 unsigned frames; /* Total number of frames in file */
43 unsigned size; /* Total number of bytes in the stream */
44 int is_cbr;
45 } MP3DecContext;
46
47 /* mp3 read */
48
49 static int mp3_read_probe(AVProbeData *p)
50 {
51 int max_frames, first_frames = 0;
52 int fsize, frames, sample_rate;
53 uint32_t header;
54 uint8_t *buf, *buf0, *buf2, *end;
55 AVCodecContext avctx;
56
57 buf0 = p->buf;
58 end = p->buf + p->buf_size - sizeof(uint32_t);
59 while(buf0 < end && !*buf0)
60 buf0++;
61
62 max_frames = 0;
63 buf = buf0;
64
65 for(; buf < end; buf= buf2+1) {
66 buf2 = buf;
67
68 for(frames = 0; buf2 < end; frames++) {
69 header = AV_RB32(buf2);
70 fsize = avpriv_mpa_decode_header(&avctx, header, &sample_rate, &sample_rate, &sample_rate, &sample_rate);
71 if(fsize < 0)
72 break;
73 buf2 += fsize;
74 }
75 max_frames = FFMAX(max_frames, frames);
76 if(buf == buf0)
77 first_frames= frames;
78 }
79 // keep this in sync with ac3 probe, both need to avoid
80 // issues with MPEG-files!
81 if (first_frames >= 4) return AVPROBE_SCORE_EXTENSION + 1;
82
83 if (max_frames) {
84 int pes = 0, i;
85 unsigned int code = -1;
86
87 #define VIDEO_ID 0x000001e0
88 #define AUDIO_ID 0x000001c0
89 /* do a search for mpegps headers to be able to properly bias
90 * towards mpegps if we detect this stream as both. */
91 for (i = 0; i<p->buf_size; i++) {
92 code = (code << 8) + p->buf[i];
93 if ((code & 0xffffff00) == 0x100) {
94 if ((code & 0x1f0) == VIDEO_ID) pes++;
95 else if((code & 0x1e0) == AUDIO_ID) pes++;
96 }
97 }
98
99 if (pes)
100 max_frames = (max_frames + pes - 1) / pes;
101 }
102 if (max_frames > 500) return AVPROBE_SCORE_EXTENSION;
103 else if (max_frames >= 4) return AVPROBE_SCORE_EXTENSION / 2;
104 else if (max_frames >= 1) 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
114 if (!filesize &&
115 !(filesize = avio_size(s->pb))) {
116 av_log(s, AV_LOG_WARNING, "Cannot determine file size, skipping TOC table.\n");
117 return;
118 }
119
120 for (i = 0; i < XING_TOC_COUNT; i++) {
121 uint8_t b = avio_r8(s->pb);
122
123 av_add_index_entry(s->streams[0],
124 av_rescale(b, filesize, 256),
125 av_rescale(i, duration, XING_TOC_COUNT),
126 0, 0, AVINDEX_KEYFRAME);
127 }
128 mp3->xing_toc = 1;
129 }
130
131
132 static void mp3_parse_info_tag(AVFormatContext *s, AVStream *st,
133 MPADecodeHeader *c, uint32_t spf)
134 {
135 uint32_t v;
136 MP3DecContext *mp3 = s->priv_data;
137 const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
138
139 /* Check for Xing / Info tag */
140 avio_skip(s->pb, xing_offtbl[c->lsf == 1][c->nb_channels == 1]);
141 v = avio_rb32(s->pb);
142 mp3->is_cbr = v == MKBETAG('I', 'n', 'f', 'o');
143 if (v == MKBETAG('X', 'i', 'n', 'g') || mp3->is_cbr) {
144 v = avio_rb32(s->pb);
145 if (v & XING_FLAG_FRAMES)
146 mp3->frames = avio_rb32(s->pb);
147 if (v & XING_FLAG_SIZE)
148 mp3->size = avio_rb32(s->pb);
149 if (v & XING_FLAG_TOC && mp3->frames)
150 read_xing_toc(s, mp3->size,
151 av_rescale_q(mp3->frames,
152 (AVRational){spf, c->sample_rate},
153 st->time_base));
154 }
155 }
156
157 static void mp3_parse_vbri_tag(AVFormatContext *s, AVStream *st, int64_t base)
158 {
159 uint32_t v;
160 MP3DecContext *mp3 = s->priv_data;
161
162 /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
163 avio_seek(s->pb, base + 4 + 32, SEEK_SET);
164 v = avio_rb32(s->pb);
165 if (v == MKBETAG('V', 'B', 'R', 'I')) {
166 /* Check tag version */
167 if (avio_rb16(s->pb) == 1) {
168 /* skip delay and quality */
169 avio_skip(s->pb, 4);
170 mp3->size = avio_rb32(s->pb);
171 mp3->frames = avio_rb32(s->pb);
172 }
173 }
174 }
175
176 /**
177 * Try to find Xing/Info/VBRI tags and compute duration from info therein
178 */
179 static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
180 {
181 uint32_t v, spf;
182 MPADecodeHeader c;
183 int vbrtag_size = 0;
184 MP3DecContext *mp3 = s->priv_data;
185
186 v = avio_rb32(s->pb);
187 if(ff_mpa_check_header(v) < 0)
188 return -1;
189
190 if (avpriv_mpegaudio_decode_header(&c, v) == 0)
191 vbrtag_size = c.frame_size;
192 if(c.layer != 3)
193 return -1;
194
195 spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
196
197 mp3->frames = 0;
198 mp3->size = 0;
199
200 mp3_parse_info_tag(s, st, &c, spf);
201 mp3_parse_vbri_tag(s, st, base);
202
203 if (!mp3->frames && !mp3->size)
204 return -1;
205
206 /* Skip the vbr tag frame */
207 avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
208
209 if (mp3->frames)
210 st->duration = av_rescale_q(mp3->frames, (AVRational){spf, c.sample_rate},
211 st->time_base);
212 if (mp3->size && mp3->frames && !mp3->is_cbr)
213 st->codec->bit_rate = av_rescale(mp3->size, 8 * c.sample_rate, mp3->frames * (int64_t)spf);
214
215 return 0;
216 }
217
218 static int mp3_read_header(AVFormatContext *s)
219 {
220 AVStream *st;
221 int64_t off;
222 int ret;
223
224 st = avformat_new_stream(s, NULL);
225 if (!st)
226 return AVERROR(ENOMEM);
227
228 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
229 st->codec->codec_id = AV_CODEC_ID_MP3;
230 st->need_parsing = AVSTREAM_PARSE_FULL;
231 st->start_time = 0;
232
233 // lcm of all mp3 sample rates
234 avpriv_set_pts_info(st, 64, 1, 14112000);
235
236 off = avio_tell(s->pb);
237
238 if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
239 ff_id3v1_read(s);
240
241 if (mp3_parse_vbr_tags(s, st, off) < 0)
242 avio_seek(s->pb, off, SEEK_SET);
243
244 ret = ff_replaygain_export(st, s->metadata);
245 if (ret < 0)
246 return ret;
247
248 /* the parameters will be extracted from the compressed bitstream */
249 return 0;
250 }
251
252 #define MP3_PACKET_SIZE 1024
253
254 static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
255 {
256 int ret;
257
258 ret = av_get_packet(s->pb, pkt, MP3_PACKET_SIZE);
259 if (ret < 0)
260 return ret;
261
262 pkt->stream_index = 0;
263
264 if (ret > ID3v1_TAG_SIZE &&
265 memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)
266 ret -= ID3v1_TAG_SIZE;
267
268 /* note: we need to modify the packet size here to handle the last
269 packet */
270 pkt->size = ret;
271 return ret;
272 }
273
274 static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
275 int flags)
276 {
277 MP3DecContext *mp3 = s->priv_data;
278 AVIndexEntry *ie;
279 AVStream *st = s->streams[0];
280 int64_t ret = av_index_search_timestamp(st, timestamp, flags);
281 uint32_t header = 0;
282
283 if (!mp3->xing_toc)
284 return AVERROR(ENOSYS);
285
286 if (ret < 0)
287 return ret;
288
289 ie = &st->index_entries[ret];
290 ret = avio_seek(s->pb, ie->pos, SEEK_SET);
291 if (ret < 0)
292 return ret;
293
294 while (!s->pb->eof_reached) {
295 header = (header << 8) + avio_r8(s->pb);
296 if (ff_mpa_check_header(header) >= 0) {
297 ff_update_cur_dts(s, st, ie->timestamp);
298 ret = avio_seek(s->pb, -4, SEEK_CUR);
299 return (ret >= 0) ? 0 : ret;
300 }
301 }
302
303 return AVERROR_EOF;
304 }
305
306 AVInputFormat ff_mp3_demuxer = {
307 .name = "mp3",
308 .long_name = NULL_IF_CONFIG_SMALL("MP2/3 (MPEG audio layer 2/3)"),
309 .read_probe = mp3_read_probe,
310 .read_header = mp3_read_header,
311 .read_packet = mp3_read_packet,
312 .read_seek = mp3_seek,
313 .priv_data_size = sizeof(MP3DecContext),
314 .flags = AVFMT_GENERIC_INDEX,
315 .extensions = "mp2,mp3,m2a,mpa", /* XXX: use probe */
316 };