]> git.sesse.net Git - ffmpeg/blob - libavformat/mp3dec.c
Merge commit '9c7d85b3b45a77742b1e69c48ab33f9c8a2e6f35'
[ffmpeg] / libavformat / mp3dec.c
1 /*
2  * MP3 demuxer
3  * Copyright (c) 2003 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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 "libavcodec/mpegaudiodecheader.h"
31
32 #define XING_FLAG_FRAMES 0x01
33 #define XING_FLAG_SIZE   0x02
34 #define XING_FLAG_TOC    0x04
35
36 #define XING_TOC_COUNT 100
37
38 typedef struct {
39     int64_t filesize;
40     int xing_toc;
41     int start_pad;
42     int end_pad;
43 } MP3Context;
44
45 /* mp3 read */
46
47 static int mp3_read_probe(AVProbeData *p)
48 {
49     int max_frames, first_frames = 0;
50     int fsize, frames, sample_rate;
51     uint32_t header;
52     const uint8_t *buf, *buf0, *buf2, *end;
53     AVCodecContext avctx;
54
55     buf0 = p->buf;
56     end = p->buf + p->buf_size - sizeof(uint32_t);
57     while(buf0 < end && !*buf0)
58         buf0++;
59
60     max_frames = 0;
61     buf = buf0;
62
63     for(; buf < end; buf= buf2+1) {
64         buf2 = buf;
65
66         for(frames = 0; buf2 < end; frames++) {
67             header = AV_RB32(buf2);
68             fsize = avpriv_mpa_decode_header(&avctx, header, &sample_rate, &sample_rate, &sample_rate, &sample_rate);
69             if(fsize < 0)
70                 break;
71             buf2 += fsize;
72         }
73         max_frames = FFMAX(max_frames, frames);
74         if(buf == buf0)
75             first_frames= frames;
76     }
77     // keep this in sync with ac3 probe, both need to avoid
78     // issues with MPEG-files!
79     if   (first_frames>=4) return AVPROBE_SCORE_MAX/2+1;
80     else if(max_frames>200)return AVPROBE_SCORE_MAX/2;
81     else if(max_frames>=4) return AVPROBE_SCORE_MAX/4;
82     else if(ff_id3v2_match(buf0, ID3v2_DEFAULT_MAGIC) && 2*ff_id3v2_tag_len(buf0) >= p->buf_size)
83                            return AVPROBE_SCORE_MAX/8;
84     else if(max_frames>=1) return 1;
85     else                   return 0;
86 //mpegps_mp3_unrecognized_format.mpg has max_frames=3
87 }
88
89 static void read_xing_toc(AVFormatContext *s, int64_t filesize, int64_t duration)
90 {
91     int i;
92     MP3Context *mp3 = s->priv_data;
93
94     if (!filesize &&
95         !(filesize = avio_size(s->pb))) {
96         av_log(s, AV_LOG_WARNING, "Cannot determine file size, skipping TOC table.\n");
97         return;
98     }
99
100     for (i = 0; i < XING_TOC_COUNT; i++) {
101         uint8_t b = avio_r8(s->pb);
102
103         av_add_index_entry(s->streams[0],
104                            av_rescale(b, filesize, 256),
105                            av_rescale(i, duration, XING_TOC_COUNT),
106                            0, 0, AVINDEX_KEYFRAME);
107     }
108     mp3->xing_toc = 1;
109 }
110
111 /**
112  * Try to find Xing/Info/VBRI tags and compute duration from info therein
113  */
114 static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
115 {
116     MP3Context *mp3 = s->priv_data;
117     uint32_t v, spf;
118     unsigned frames = 0; /* Total number of frames in file */
119     unsigned size = 0; /* Total number of bytes in the stream */
120     const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
121     MPADecodeHeader c;
122     int vbrtag_size = 0;
123
124     v = avio_rb32(s->pb);
125     if(ff_mpa_check_header(v) < 0)
126       return -1;
127
128     if (avpriv_mpegaudio_decode_header(&c, v) == 0)
129         vbrtag_size = c.frame_size;
130     if(c.layer != 3)
131         return -1;
132
133     spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
134
135     /* Check for Xing / Info tag */
136     avio_skip(s->pb, xing_offtbl[c.lsf == 1][c.nb_channels == 1]);
137     v = avio_rb32(s->pb);
138     if(v == MKBETAG('X', 'i', 'n', 'g') || v == MKBETAG('I', 'n', 'f', 'o')) {
139         v = avio_rb32(s->pb);
140         if(v & XING_FLAG_FRAMES)
141             frames = avio_rb32(s->pb);
142         if(v & XING_FLAG_SIZE)
143             size = avio_rb32(s->pb);
144         if (v & XING_FLAG_TOC && frames)
145             read_xing_toc(s, size, av_rescale_q(frames, (AVRational){spf, c.sample_rate},
146                                     st->time_base));
147         if(v & 8)
148             avio_skip(s->pb, 4);
149
150         v = avio_rb32(s->pb);
151         if(v == MKBETAG('L', 'A', 'M', 'E') || v == MKBETAG('L', 'a', 'v', 'f')) {
152             avio_skip(s->pb, 21-4);
153             v= avio_rb24(s->pb);
154             mp3->start_pad = v>>12;
155             mp3->  end_pad = v&4095;
156             st->skip_samples = mp3->start_pad + 528 + 1;
157             av_log(s, AV_LOG_DEBUG, "pad %d %d\n", mp3->start_pad, mp3->  end_pad);
158         }
159     }
160
161     /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
162     avio_seek(s->pb, base + 4 + 32, SEEK_SET);
163     v = avio_rb32(s->pb);
164     if(v == MKBETAG('V', 'B', 'R', 'I')) {
165         /* Check tag version */
166         if(avio_rb16(s->pb) == 1) {
167             /* skip delay and quality */
168             avio_skip(s->pb, 4);
169             size = avio_rb32(s->pb);
170             frames = avio_rb32(s->pb);
171         }
172     }
173
174     if(!frames && !size)
175         return -1;
176
177     /* Skip the vbr tag frame */
178     avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
179
180     if(frames)
181         st->duration = av_rescale_q(frames, (AVRational){spf, c.sample_rate},
182                                     st->time_base);
183     if(size && frames)
184         st->codec->bit_rate = av_rescale(size, 8 * c.sample_rate, frames * (int64_t)spf);
185
186     return 0;
187 }
188
189 static int mp3_read_header(AVFormatContext *s)
190 {
191     MP3Context *mp3 = s->priv_data;
192     AVStream *st;
193     int64_t off;
194
195     st = avformat_new_stream(s, NULL);
196     if (!st)
197         return AVERROR(ENOMEM);
198
199     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
200     st->codec->codec_id = AV_CODEC_ID_MP3;
201     st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
202     st->start_time = 0;
203
204     // lcm of all mp3 sample rates
205     avpriv_set_pts_info(st, 64, 1, 14112000);
206
207     s->pb->maxsize = -1;
208     off = avio_tell(s->pb);
209
210     if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
211         ff_id3v1_read(s);
212
213     if(s->pb->seekable)
214         mp3->filesize = avio_size(s->pb);
215
216     if (mp3_parse_vbr_tags(s, st, off) < 0)
217         avio_seek(s->pb, off, SEEK_SET);
218
219     /* the parameters will be extracted from the compressed bitstream */
220     return 0;
221 }
222
223 #define MP3_PACKET_SIZE 1024
224
225 static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
226 {
227     MP3Context *mp3 = s->priv_data;
228     int ret, size;
229     int64_t pos;
230
231     size= MP3_PACKET_SIZE;
232     pos = avio_tell(s->pb);
233     if(mp3->filesize > ID3v1_TAG_SIZE && pos < mp3->filesize)
234         size= FFMIN(size, mp3->filesize - pos);
235
236     ret= av_get_packet(s->pb, pkt, size);
237     if (ret <= 0) {
238         if(ret<0)
239             return ret;
240         return AVERROR_EOF;
241     }
242
243     pkt->flags &= ~AV_PKT_FLAG_CORRUPT;
244     pkt->stream_index = 0;
245
246     if (ret >= ID3v1_TAG_SIZE &&
247         memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)
248         ret -= ID3v1_TAG_SIZE;
249
250     /* note: we need to modify the packet size here to handle the last
251        packet */
252     pkt->size = ret;
253     return ret;
254 }
255
256 static int check(AVFormatContext *s, int64_t pos)
257 {
258     int64_t ret = avio_seek(s->pb, pos, SEEK_SET);
259     unsigned header;
260     MPADecodeHeader sd;
261     if (ret < 0)
262         return ret;
263     header = avio_rb32(s->pb);
264     if (ff_mpa_check_header(header) < 0)
265         return -1;
266     if (avpriv_mpegaudio_decode_header(&sd, header) == 1)
267         return -1;
268     return sd.frame_size;
269 }
270
271 static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
272                     int flags)
273 {
274     MP3Context *mp3 = s->priv_data;
275     AVIndexEntry *ie;
276     AVStream *st = s->streams[0];
277     int64_t ret  = av_index_search_timestamp(st, timestamp, flags);
278     int i, j;
279
280     if (!mp3->xing_toc) {
281         st->skip_samples = timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;
282
283         return -1;
284     }
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 #define MIN_VALID 3
295     for(i=0; i<4096; i++) {
296         int64_t pos = ie->pos + i;
297         for(j=0; j<MIN_VALID; j++) {
298             ret = check(s, pos);
299             if(ret < 0)
300                 break;
301             pos += ret;
302         }
303         if(j==MIN_VALID)
304             break;
305     }
306     if(j!=MIN_VALID)
307         i=0;
308
309     ret = avio_seek(s->pb, ie->pos + i, SEEK_SET);
310     if (ret < 0)
311         return ret;
312     ff_update_cur_dts(s, st, ie->timestamp);
313     st->skip_samples = ie->timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;
314     return 0;
315 }
316
317 AVInputFormat ff_mp3_demuxer = {
318     .name           = "mp3",
319     .long_name      = NULL_IF_CONFIG_SMALL("MP2/3 (MPEG audio layer 2/3)"),
320     .priv_data_size = sizeof(MP3Context),
321     .read_probe     = mp3_read_probe,
322     .read_header    = mp3_read_header,
323     .read_packet    = mp3_read_packet,
324     .read_seek      = mp3_seek,
325     .flags          = AVFMT_GENERIC_INDEX,
326     .extensions     = "mp2,mp3,m2a", /* XXX: use probe */
327 };