]> git.sesse.net Git - ffmpeg/blob - libavformat/mp3dec.c
mp3dec: fix reading the Xing tag
[ffmpeg] / 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/mpegaudiodecheader.h"
35
36 #define XING_FLAG_FRAMES 0x01
37 #define XING_FLAG_SIZE   0x02
38 #define XING_FLAG_TOC    0x04
39 #define XING_FLAC_QSCALE 0x08
40
41 #define XING_TOC_COUNT 100
42
43 typedef struct MP3DecContext {
44     int xing_toc;
45     unsigned frames; /* Total number of frames in file */
46     unsigned size;   /* Total number of bytes in the stream */
47     int is_cbr;
48 } MP3DecContext;
49
50 /* mp3 read */
51
52 static int mp3_read_probe(AVProbeData *p)
53 {
54     int max_frames, first_frames = 0;
55     int fsize, frames, sample_rate;
56     uint32_t header;
57     uint8_t *buf, *buf0, *buf2, *end;
58     AVCodecContext avctx;
59
60     buf0 = p->buf;
61     end = p->buf + p->buf_size - sizeof(uint32_t);
62     while(buf0 < end && !*buf0)
63         buf0++;
64
65     max_frames = 0;
66     buf = buf0;
67
68     for(; buf < end; buf= buf2+1) {
69         buf2 = buf;
70
71         for(frames = 0; buf2 < end; frames++) {
72             header = AV_RB32(buf2);
73             fsize = avpriv_mpa_decode_header(&avctx, header, &sample_rate, &sample_rate, &sample_rate, &sample_rate);
74             if(fsize < 0)
75                 break;
76             buf2 += fsize;
77         }
78         max_frames = FFMAX(max_frames, frames);
79         if(buf == buf0)
80             first_frames= frames;
81     }
82     // keep this in sync with ac3 probe, both need to avoid
83     // issues with MPEG-files!
84     if (first_frames >= 4) return AVPROBE_SCORE_EXTENSION + 1;
85
86     if (max_frames) {
87         int pes = 0, i;
88         unsigned int code = -1;
89
90 #define VIDEO_ID 0x000001e0
91 #define AUDIO_ID 0x000001c0
92         /* do a search for mpegps headers to be able to properly bias
93          * towards mpegps if we detect this stream as both. */
94         for (i = 0; i<p->buf_size; i++) {
95             code = (code << 8) + p->buf[i];
96             if ((code & 0xffffff00) == 0x100) {
97                 if     ((code & 0x1f0) == VIDEO_ID) pes++;
98                 else if((code & 0x1e0) == AUDIO_ID) pes++;
99             }
100         }
101
102         if (pes)
103             max_frames = (max_frames + pes - 1) / pes;
104     }
105     if      (max_frames >  500) return AVPROBE_SCORE_EXTENSION;
106     else if (max_frames >= 4)   return AVPROBE_SCORE_EXTENSION / 2;
107     else if (max_frames >= 1)   return 1;
108     else                        return 0;
109 //mpegps_mp3_unrecognized_format.mpg has max_frames=3
110 }
111
112 static void read_xing_toc(AVFormatContext *s, int64_t filesize, int64_t duration)
113 {
114     int i;
115     MP3DecContext *mp3 = s->priv_data;
116
117     if (!filesize &&
118         !(filesize = avio_size(s->pb))) {
119         av_log(s, AV_LOG_WARNING, "Cannot determine file size, skipping TOC table.\n");
120         return;
121     }
122
123     for (i = 0; i < XING_TOC_COUNT; i++) {
124         uint8_t b = avio_r8(s->pb);
125
126         av_add_index_entry(s->streams[0],
127                            av_rescale(b, filesize, 256),
128                            av_rescale(i, duration, XING_TOC_COUNT),
129                            0, 0, AVINDEX_KEYFRAME);
130     }
131     mp3->xing_toc = 1;
132 }
133
134 static void mp3_parse_info_tag(AVFormatContext *s, AVStream *st,
135                                MPADecodeHeader *c, uint32_t spf)
136 {
137 #define LAST_BITS(k, n) ((k) & ((1 << (n)) - 1))
138 #define MIDDLE_BITS(k, m, n) LAST_BITS((k) >> (m), ((n) - (m)))
139
140     uint16_t crc;
141     uint32_t v;
142
143     char version[10];
144
145     uint32_t peak   = 0;
146     int32_t  r_gain = INT32_MIN, a_gain = INT32_MIN;
147
148     MP3DecContext *mp3 = s->priv_data;
149     const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
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->size = avio_rb32(s->pb);
163     if (v & XING_FLAG_TOC && mp3->frames)
164         read_xing_toc(s, mp3->size, av_rescale_q(mp3->frames,
165                                        (AVRational){spf, c->sample_rate},
166                                        st->time_base));
167
168     /* VBR quality */
169     if (v & XING_FLAC_QSCALE)
170         avio_rb32(s->pb);
171
172     /* Encoder short version string */
173     memset(version, 0, sizeof(version));
174     avio_read(s->pb, version, 9);
175
176     /* Info Tag revision + VBR method */
177     avio_r8(s->pb);
178
179     /* Lowpass filter value */
180     avio_r8(s->pb);
181
182     /* ReplayGain peak */
183     v    = avio_rb32(s->pb);
184     peak = av_rescale(v, 100000, 1 << 23);
185
186     /* Radio ReplayGain */
187     v = avio_rb16(s->pb);
188
189     if (MIDDLE_BITS(v, 13, 15) == 1) {
190         r_gain = MIDDLE_BITS(v, 0, 8) * 10000;
191
192         if (v & (1 << 9))
193             r_gain *= -1;
194     }
195
196     /* Audiophile ReplayGain */
197     v = avio_rb16(s->pb);
198
199     if (MIDDLE_BITS(v, 13, 15) == 2) {
200         a_gain = MIDDLE_BITS(v, 0, 8) * 10000;
201
202         if (v & (1 << 9))
203             a_gain *= -1;
204     }
205
206     /* Encoding flags + ATH Type */
207     avio_r8(s->pb);
208
209     /* if ABR {specified bitrate} else {minimal bitrate} */
210     avio_r8(s->pb);
211
212     /* Encoder delays */
213     avio_rb24(s->pb);
214
215     /* Misc */
216     avio_r8(s->pb);
217
218     /* MP3 gain */
219     avio_r8(s->pb);
220
221     /* Preset and surround info */
222     avio_rb16(s->pb);
223
224     /* Music length */
225     avio_rb32(s->pb);
226
227     /* Music CRC */
228     avio_rb16(s->pb);
229
230     /* Info Tag CRC */
231     crc = ffio_get_checksum(s->pb);
232     v   = avio_rb16(s->pb);
233
234     if (v == crc) {
235         ff_replaygain_export_raw(st, r_gain, peak, a_gain, 0);
236         av_dict_set(&st->metadata, "encoder", version, 0);
237     }
238 }
239
240 static void mp3_parse_vbri_tag(AVFormatContext *s, AVStream *st, int64_t base)
241 {
242     uint32_t v;
243     MP3DecContext *mp3 = s->priv_data;
244
245     /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
246     avio_seek(s->pb, base + 4 + 32, SEEK_SET);
247     v = avio_rb32(s->pb);
248     if (v == MKBETAG('V', 'B', 'R', 'I')) {
249         /* Check tag version */
250         if (avio_rb16(s->pb) == 1) {
251             /* skip delay and quality */
252             avio_skip(s->pb, 4);
253             mp3->size = avio_rb32(s->pb);
254             mp3->frames = avio_rb32(s->pb);
255         }
256     }
257 }
258
259 /**
260  * Try to find Xing/Info/VBRI tags and compute duration from info therein
261  */
262 static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
263 {
264     uint32_t v, spf;
265     MPADecodeHeader c;
266     int vbrtag_size = 0;
267     MP3DecContext *mp3 = s->priv_data;
268
269     ffio_init_checksum(s->pb, ff_crcA001_update, 0);
270
271     v = avio_rb32(s->pb);
272     if(ff_mpa_check_header(v) < 0)
273       return -1;
274
275     if (avpriv_mpegaudio_decode_header(&c, v) == 0)
276         vbrtag_size = c.frame_size;
277     if(c.layer != 3)
278         return -1;
279
280     spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
281
282     mp3->frames = 0;
283     mp3->size   = 0;
284
285     mp3_parse_info_tag(s, st, &c, spf);
286     mp3_parse_vbri_tag(s, st, base);
287
288     if (!mp3->frames && !mp3->size)
289         return -1;
290
291     /* Skip the vbr tag frame */
292     avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
293
294     if (mp3->frames)
295         st->duration = av_rescale_q(mp3->frames, (AVRational){spf, c.sample_rate},
296                                     st->time_base);
297     if (mp3->size && mp3->frames && !mp3->is_cbr)
298         st->codec->bit_rate = av_rescale(mp3->size, 8 * c.sample_rate, mp3->frames * (int64_t)spf);
299
300     return 0;
301 }
302
303 static int mp3_read_header(AVFormatContext *s)
304 {
305     AVStream *st;
306     int64_t off;
307     int ret;
308
309     st = avformat_new_stream(s, NULL);
310     if (!st)
311         return AVERROR(ENOMEM);
312
313     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
314     st->codec->codec_id = AV_CODEC_ID_MP3;
315     st->need_parsing = AVSTREAM_PARSE_FULL;
316     st->start_time = 0;
317
318     // lcm of all mp3 sample rates
319     avpriv_set_pts_info(st, 64, 1, 14112000);
320
321     off = avio_tell(s->pb);
322
323     if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
324         ff_id3v1_read(s);
325
326     if (mp3_parse_vbr_tags(s, st, off) < 0)
327         avio_seek(s->pb, off, SEEK_SET);
328
329     ret = ff_replaygain_export(st, s->metadata);
330     if (ret < 0)
331         return ret;
332
333     /* the parameters will be extracted from the compressed bitstream */
334     return 0;
335 }
336
337 #define MP3_PACKET_SIZE 1024
338
339 static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
340 {
341     int ret;
342
343     ret = av_get_packet(s->pb, pkt, MP3_PACKET_SIZE);
344     if (ret < 0)
345         return ret;
346
347     pkt->stream_index = 0;
348
349     if (ret > ID3v1_TAG_SIZE &&
350         memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)
351         ret -= ID3v1_TAG_SIZE;
352
353     /* note: we need to modify the packet size here to handle the last
354        packet */
355     pkt->size = ret;
356     return ret;
357 }
358
359 static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
360                     int flags)
361 {
362     MP3DecContext *mp3 = s->priv_data;
363     AVIndexEntry *ie;
364     AVStream *st = s->streams[0];
365     int64_t ret  = av_index_search_timestamp(st, timestamp, flags);
366     uint32_t header = 0;
367
368     if (!mp3->xing_toc)
369         return AVERROR(ENOSYS);
370
371     if (ret < 0)
372         return ret;
373
374     ie = &st->index_entries[ret];
375     ret = avio_seek(s->pb, ie->pos, SEEK_SET);
376     if (ret < 0)
377         return ret;
378
379     while (!s->pb->eof_reached) {
380         header = (header << 8) + avio_r8(s->pb);
381         if (ff_mpa_check_header(header) >= 0) {
382             ff_update_cur_dts(s, st, ie->timestamp);
383             ret = avio_seek(s->pb, -4, SEEK_CUR);
384             return (ret >= 0) ? 0 : ret;
385         }
386     }
387
388     return AVERROR_EOF;
389 }
390
391 AVInputFormat ff_mp3_demuxer = {
392     .name           = "mp3",
393     .long_name      = NULL_IF_CONFIG_SMALL("MP2/3 (MPEG audio layer 2/3)"),
394     .read_probe     = mp3_read_probe,
395     .read_header    = mp3_read_header,
396     .read_packet    = mp3_read_packet,
397     .read_seek      = mp3_seek,
398     .priv_data_size = sizeof(MP3DecContext),
399     .flags          = AVFMT_GENERIC_INDEX,
400     .extensions     = "mp2,mp3,m2a,mpa", /* XXX: use probe */
401 };