]> git.sesse.net Git - ffmpeg/blob - libavformat/mp3dec.c
Mark read-only tables as static
[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/avcodec.h"
35 #include "libavcodec/mpegaudiodecheader.h"
36
37 #define XING_FLAG_FRAMES 0x01
38 #define XING_FLAG_SIZE   0x02
39 #define XING_FLAG_TOC    0x04
40 #define XING_FLAC_QSCALE 0x08
41
42 #define XING_TOC_COUNT 100
43
44 typedef struct MP3DecContext {
45     int xing_toc;
46     unsigned frames; /* Total number of frames in file */
47     unsigned size;   /* Total number of bytes in the stream */
48     int is_cbr;
49 } MP3DecContext;
50
51 /* mp3 read */
52
53 static int mp3_read_probe(AVProbeData *p)
54 {
55     int max_frames, first_frames = 0;
56     int frames, ret;
57     uint32_t header;
58     uint8_t *buf, *buf0, *buf2, *end;
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             MPADecodeHeader h;
73
74             header = AV_RB32(buf2);
75             ret = avpriv_mpegaudio_decode_header(&h, header);
76             if (ret != 0)
77                 break;
78             buf2 += h.frame_size;
79         }
80         max_frames = FFMAX(max_frames, frames);
81         if(buf == buf0)
82             first_frames= frames;
83     }
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;
90
91     if (max_frames) {
92         int pes = 0, i;
93         unsigned int code = -1;
94
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++;
104             }
105         }
106
107         if (pes)
108             max_frames = (max_frames + pes - 1) / pes;
109     }
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;
113     else                        return 0;
114 //mpegps_mp3_unrecognized_format.mpg has max_frames=3
115 }
116
117 static void read_xing_toc(AVFormatContext *s, int64_t filesize, int64_t duration)
118 {
119     int i;
120     MP3DecContext *mp3 = s->priv_data;
121
122     if (!filesize &&
123         !(filesize = avio_size(s->pb))) {
124         av_log(s, AV_LOG_WARNING, "Cannot determine file size, skipping TOC table.\n");
125         return;
126     }
127
128     for (i = 0; i < XING_TOC_COUNT; i++) {
129         uint8_t b = avio_r8(s->pb);
130
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);
135     }
136     mp3->xing_toc = 1;
137 }
138
139 static void mp3_parse_info_tag(AVFormatContext *s, AVStream *st,
140                                MPADecodeHeader *c, uint32_t spf)
141 {
142 #define LAST_BITS(k, n) ((k) & ((1 << (n)) - 1))
143 #define MIDDLE_BITS(k, m, n) LAST_BITS((k) >> (m), ((n) - (m)))
144
145     uint16_t crc;
146     uint32_t v;
147
148     char version[10];
149
150     uint32_t peak   = 0;
151     int32_t  r_gain = INT32_MIN, a_gain = INT32_MIN;
152
153     MP3DecContext *mp3 = s->priv_data;
154     static const int64_t xing_offtbl[2][2] = { { 32, 17 }, { 17, 9 } };
155
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)
161         return;
162
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},
171                                        st->time_base));
172
173     /* VBR quality */
174     if (v & XING_FLAC_QSCALE)
175         avio_rb32(s->pb);
176
177     /* Encoder short version string */
178     memset(version, 0, sizeof(version));
179     avio_read(s->pb, version, 9);
180
181     /* Info Tag revision + VBR method */
182     avio_r8(s->pb);
183
184     /* Lowpass filter value */
185     avio_r8(s->pb);
186
187     /* ReplayGain peak */
188     v    = avio_rb32(s->pb);
189     peak = av_rescale(v, 100000, 1 << 23);
190
191     /* Radio ReplayGain */
192     v = avio_rb16(s->pb);
193
194     if (MIDDLE_BITS(v, 13, 15) == 1) {
195         r_gain = MIDDLE_BITS(v, 0, 8) * 10000;
196
197         if (v & (1 << 9))
198             r_gain *= -1;
199     }
200
201     /* Audiophile ReplayGain */
202     v = avio_rb16(s->pb);
203
204     if (MIDDLE_BITS(v, 13, 15) == 2) {
205         a_gain = MIDDLE_BITS(v, 0, 8) * 10000;
206
207         if (v & (1 << 9))
208             a_gain *= -1;
209     }
210
211     /* Encoding flags + ATH Type */
212     avio_r8(s->pb);
213
214     /* if ABR {specified bitrate} else {minimal bitrate} */
215     avio_r8(s->pb);
216
217     /* Encoder delays */
218     avio_rb24(s->pb);
219
220     /* Misc */
221     avio_r8(s->pb);
222
223     /* MP3 gain */
224     avio_r8(s->pb);
225
226     /* Preset and surround info */
227     avio_rb16(s->pb);
228
229     /* Music length */
230     avio_rb32(s->pb);
231
232     /* Music CRC */
233     avio_rb16(s->pb);
234
235     /* Info Tag CRC */
236     crc = ffio_get_checksum(s->pb);
237     v   = avio_rb16(s->pb);
238
239     if (v == crc) {
240         ff_replaygain_export_raw(st, r_gain, peak, a_gain, 0);
241         av_dict_set(&st->metadata, "encoder", version, 0);
242     }
243 }
244
245 static void mp3_parse_vbri_tag(AVFormatContext *s, AVStream *st, int64_t base)
246 {
247     uint32_t v;
248     MP3DecContext *mp3 = s->priv_data;
249
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 */
257             avio_skip(s->pb, 4);
258             mp3->size = avio_rb32(s->pb);
259             mp3->frames = avio_rb32(s->pb);
260         }
261     }
262 }
263
264 /**
265  * Try to find Xing/Info/VBRI tags and compute duration from info therein
266  */
267 static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
268 {
269     uint32_t v, spf;
270     MPADecodeHeader c;
271     int vbrtag_size = 0;
272     MP3DecContext *mp3 = s->priv_data;
273     int ret;
274
275     ffio_init_checksum(s->pb, ff_crcA001_update, 0);
276
277     v = avio_rb32(s->pb);
278
279     ret = avpriv_mpegaudio_decode_header(&c, v);
280     if (ret < 0)
281         return ret;
282     else if (ret == 0)
283         vbrtag_size = c.frame_size;
284     if(c.layer != 3)
285         return -1;
286
287     spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
288
289     mp3->frames = 0;
290     mp3->size   = 0;
291
292     mp3_parse_info_tag(s, st, &c, spf);
293     mp3_parse_vbri_tag(s, st, base);
294
295     if (!mp3->frames && !mp3->size)
296         return -1;
297
298     /* Skip the vbr tag frame */
299     avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
300
301     if (mp3->frames)
302         st->duration = av_rescale_q(mp3->frames, (AVRational){spf, c.sample_rate},
303                                     st->time_base);
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);
306
307     return 0;
308 }
309
310 static int mp3_read_header(AVFormatContext *s)
311 {
312     AVStream *st;
313     int64_t off;
314     int ret;
315
316     st = avformat_new_stream(s, NULL);
317     if (!st)
318         return AVERROR(ENOMEM);
319
320     st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
321     st->codecpar->codec_id = AV_CODEC_ID_MP3;
322     st->need_parsing = AVSTREAM_PARSE_FULL;
323     st->start_time = 0;
324
325     // lcm of all mp3 sample rates
326     avpriv_set_pts_info(st, 64, 1, 14112000);
327
328     off = avio_tell(s->pb);
329
330     if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
331         ff_id3v1_read(s);
332
333     if (mp3_parse_vbr_tags(s, st, off) < 0)
334         avio_seek(s->pb, off, SEEK_SET);
335
336     ret = ff_replaygain_export(st, s->metadata);
337     if (ret < 0)
338         return ret;
339
340     /* the parameters will be extracted from the compressed bitstream */
341     return 0;
342 }
343
344 #define MP3_PACKET_SIZE 1024
345
346 static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
347 {
348     int ret;
349
350     ret = av_get_packet(s->pb, pkt, MP3_PACKET_SIZE);
351     if (ret < 0)
352         return ret;
353
354     pkt->stream_index = 0;
355
356     if (ret > ID3v1_TAG_SIZE &&
357         memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)
358         ret -= ID3v1_TAG_SIZE;
359
360     /* note: we need to modify the packet size here to handle the last
361        packet */
362     pkt->size = ret;
363     return ret;
364 }
365
366 #define SEEK_PACKETS 4
367 #define SEEK_WINDOW (SEEK_PACKETS * MP3_PACKET_SIZE)
368
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.
371  */
372
373 static int check(AVIOContext *pb, int64_t pos, int64_t *out_pos)
374 {
375     MPADecodeHeader mh = { 0 };
376     int i;
377     uint32_t header;
378     int64_t off = 0;
379
380
381     for (i = 0; i < SEEK_PACKETS; i++) {
382         off = avio_seek(pb, pos + mh.frame_size, SEEK_SET);
383         if (off < 0)
384             break;
385
386         header = avio_rb32(pb);
387
388
389         if (avpriv_mpegaudio_decode_header(&mh, header))
390             break;
391         out_pos[i] = off;
392     }
393
394     return i;
395 }
396
397 static int reposition(AVFormatContext *s, int64_t pos)
398 {
399     int ret, best_valid = -1;
400     int64_t p, best_pos = -1;
401
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);
405
406         if (best_valid < ret) {
407             int i;
408             for (i = 0; i < ret; i++) {
409                 if (llabs(best_pos - pos) > llabs(out_pos[i] - pos)) {
410                     best_pos   = out_pos[i];
411                     best_valid = ret;
412                 }
413             }
414             if (best_pos == pos && best_valid == SEEK_PACKETS)
415                 break;
416         }
417     }
418
419     if (best_valid <= 0)
420         return AVERROR(ENOSYS);
421
422     p = avio_seek(s->pb, best_pos, SEEK_SET);
423     if (p < 0)
424         return p;
425
426     return 0;
427 }
428
429 static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
430                     int flags)
431 {
432     MP3DecContext *mp3 = s->priv_data;
433     AVIndexEntry *ie;
434     AVStream *st = s->streams[0];
435     int64_t ret  = av_index_search_timestamp(st, timestamp, flags);
436
437     if (!mp3->xing_toc)
438         return AVERROR(ENOSYS);
439
440     if (ret < 0)
441         return ret;
442
443     ie = &st->index_entries[ret];
444
445     ret = reposition(s, ie->pos);
446     if (ret < 0)
447         return ret;
448
449     ff_update_cur_dts(s, st, ie->timestamp);
450
451     return 0;
452 }
453
454 AVInputFormat ff_mp3_demuxer = {
455     .name           = "mp3",
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 */
464 };