]> git.sesse.net Git - ffmpeg/blob - libavformat/mp3dec.c
avformat/rtpproto: Use av_freep() to avoid leaving stale pointers in memory
[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/opt.h"
23 #include "libavutil/avstring.h"
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/crc.h"
26 #include "libavutil/dict.h"
27 #include "libavutil/mathematics.h"
28 #include "avformat.h"
29 #include "internal.h"
30 #include "avio_internal.h"
31 #include "id3v2.h"
32 #include "id3v1.h"
33 #include "replaygain.h"
34
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 {
45     AVClass *class;
46     int64_t filesize;
47     int xing_toc;
48     int start_pad;
49     int end_pad;
50     int usetoc;
51     unsigned frames; /* Total number of frames in file */
52     unsigned header_filesize;   /* Total number of bytes in the stream */
53     int is_cbr;
54 } MP3DecContext;
55
56 /* mp3 read */
57
58 static int mp3_read_probe(AVProbeData *p)
59 {
60     int max_frames, first_frames = 0;
61     int fsize, frames;
62     uint32_t header;
63     const uint8_t *buf, *buf0, *buf2, *end;
64     AVCodecContext avctx;
65
66     buf0 = p->buf;
67     end = p->buf + p->buf_size - sizeof(uint32_t);
68     while(buf0 < end && !*buf0)
69         buf0++;
70
71     max_frames = 0;
72     buf = buf0;
73
74     for(; buf < end; buf= buf2+1) {
75         buf2 = buf;
76         if(ff_mpa_check_header(AV_RB32(buf2)))
77             continue;
78
79         for(frames = 0; buf2 < end; frames++) {
80             int dummy;
81             header = AV_RB32(buf2);
82             fsize = avpriv_mpa_decode_header(&avctx, header, &dummy, &dummy, &dummy, &dummy);
83             if(fsize < 0)
84                 break;
85             buf2 += fsize;
86         }
87         max_frames = FFMAX(max_frames, frames);
88         if(buf == buf0)
89             first_frames= frames;
90     }
91     // keep this in sync with ac3 probe, both need to avoid
92     // issues with MPEG-files!
93     if   (first_frames>=4) return AVPROBE_SCORE_EXTENSION + 1;
94     else if(max_frames>200)return AVPROBE_SCORE_EXTENSION;
95     else if(max_frames>=4 && max_frames >= p->buf_size/10000) return AVPROBE_SCORE_EXTENSION / 2;
96     else if(ff_id3v2_match(buf0, ID3v2_DEFAULT_MAGIC) && 2*ff_id3v2_tag_len(buf0) >= p->buf_size)
97                            return p->buf_size < PROBE_BUF_MAX ? AVPROBE_SCORE_EXTENSION / 4 : AVPROBE_SCORE_EXTENSION - 2;
98     else if(max_frames>=1 && max_frames >= p->buf_size/10000) return 1;
99     else                   return 0;
100 //mpegps_mp3_unrecognized_format.mpg has max_frames=3
101 }
102
103 static void read_xing_toc(AVFormatContext *s, int64_t filesize, int64_t duration)
104 {
105     int i;
106     MP3DecContext *mp3 = s->priv_data;
107     int fill_index = mp3->usetoc && duration > 0;
108
109     if (!filesize &&
110         !(filesize = avio_size(s->pb))) {
111         av_log(s, AV_LOG_WARNING, "Cannot determine file size, skipping TOC table.\n");
112         fill_index = 0;
113     }
114
115     for (i = 0; i < XING_TOC_COUNT; i++) {
116         uint8_t b = avio_r8(s->pb);
117         if (fill_index)
118             av_add_index_entry(s->streams[0],
119                            av_rescale(b, filesize, 256),
120                            av_rescale(i, duration, XING_TOC_COUNT),
121                            0, 0, AVINDEX_KEYFRAME);
122     }
123     if (fill_index)
124         mp3->xing_toc = 1;
125 }
126
127 static void mp3_parse_info_tag(AVFormatContext *s, AVStream *st,
128                                MPADecodeHeader *c, uint32_t spf)
129 {
130 #define LAST_BITS(k, n) ((k) & ((1 << (n)) - 1))
131 #define MIDDLE_BITS(k, m, n) LAST_BITS((k) >> (m), ((n) - (m)))
132
133     uint16_t crc;
134     uint32_t v;
135
136     char version[10];
137
138     uint32_t peak   = 0;
139     int32_t  r_gain = INT32_MIN, a_gain = INT32_MIN;
140
141     MP3DecContext *mp3 = s->priv_data;
142     static const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
143     uint64_t fsize = avio_size(s->pb);
144
145     /* Check for Xing / Info tag */
146     avio_skip(s->pb, xing_offtbl[c->lsf == 1][c->nb_channels == 1]);
147     v = avio_rb32(s->pb);
148     mp3->is_cbr = v == MKBETAG('I', 'n', 'f', 'o');
149     if (v != MKBETAG('X', 'i', 'n', 'g') && !mp3->is_cbr)
150         return;
151
152     v = avio_rb32(s->pb);
153     if (v & XING_FLAG_FRAMES)
154         mp3->frames = avio_rb32(s->pb);
155     if (v & XING_FLAG_SIZE)
156         mp3->header_filesize = avio_rb32(s->pb);
157     if (fsize && mp3->header_filesize) {
158         uint64_t min, delta;
159         min = FFMIN(fsize, mp3->header_filesize);
160         delta = FFMAX(fsize, mp3->header_filesize) - min;
161         if (fsize > mp3->header_filesize && delta > min >> 4) {
162             mp3->frames = 0;
163         } else if (delta > min >> 4) {
164             av_log(s, AV_LOG_WARNING,
165                    "filesize and duration do not match (growing file?)\n");
166         }
167     }
168     if (v & XING_FLAG_TOC)
169         read_xing_toc(s, mp3->header_filesize, av_rescale_q(mp3->frames,
170                                        (AVRational){spf, c->sample_rate},
171                                        st->time_base));
172     /* VBR quality */
173     if (v & XING_FLAC_QSCALE)
174         avio_rb32(s->pb);
175
176     /* Encoder short version string */
177     memset(version, 0, sizeof(version));
178     avio_read(s->pb, version, 9);
179
180     /* Info Tag revision + VBR method */
181     avio_r8(s->pb);
182
183     /* Lowpass filter value */
184     avio_r8(s->pb);
185
186     /* ReplayGain peak */
187     v    = avio_rb32(s->pb);
188     peak = av_rescale(v, 100000, 1 << 23);
189
190     /* Radio ReplayGain */
191     v = avio_rb16(s->pb);
192
193     if (MIDDLE_BITS(v, 13, 15) == 1) {
194         r_gain = MIDDLE_BITS(v, 0, 8) * 10000;
195
196         if (v & (1 << 9))
197             r_gain *= -1;
198     }
199
200     /* Audiophile ReplayGain */
201     v = avio_rb16(s->pb);
202
203     if (MIDDLE_BITS(v, 13, 15) == 2) {
204         a_gain = MIDDLE_BITS(v, 0, 8) * 10000;
205
206         if (v & (1 << 9))
207             a_gain *= -1;
208     }
209
210     /* Encoding flags + ATH Type */
211     avio_r8(s->pb);
212
213     /* if ABR {specified bitrate} else {minimal bitrate} */
214     avio_r8(s->pb);
215
216     /* Encoder delays */
217     v= avio_rb24(s->pb);
218     if(AV_RB32(version) == MKBETAG('L', 'A', 'M', 'E')
219         || AV_RB32(version) == MKBETAG('L', 'a', 'v', 'f')
220         || AV_RB32(version) == MKBETAG('L', 'a', 'v', 'c')
221     ) {
222
223         mp3->start_pad = v>>12;
224         mp3->  end_pad = v&4095;
225         st->skip_samples = mp3->start_pad + 528 + 1;
226         if (mp3->frames) {
227             st->first_discard_sample = -mp3->end_pad + 528 + 1 + mp3->frames * (int64_t)spf;
228             st->last_discard_sample = mp3->frames * (int64_t)spf;
229         }
230         if (!st->start_time)
231             st->start_time = av_rescale_q(st->skip_samples,
232                                             (AVRational){1, c->sample_rate},
233                                             st->time_base);
234         av_log(s, AV_LOG_DEBUG, "pad %d %d\n", mp3->start_pad, mp3->  end_pad);
235     }
236
237     /* Misc */
238     avio_r8(s->pb);
239
240     /* MP3 gain */
241     avio_r8(s->pb);
242
243     /* Preset and surround info */
244     avio_rb16(s->pb);
245
246     /* Music length */
247     avio_rb32(s->pb);
248
249     /* Music CRC */
250     avio_rb16(s->pb);
251
252     /* Info Tag CRC */
253     crc = ffio_get_checksum(s->pb);
254     v   = avio_rb16(s->pb);
255
256     if (v == crc) {
257         ff_replaygain_export_raw(st, r_gain, peak, a_gain, 0);
258         av_dict_set(&st->metadata, "encoder", version, 0);
259     }
260 }
261
262 static void mp3_parse_vbri_tag(AVFormatContext *s, AVStream *st, int64_t base)
263 {
264     uint32_t v;
265     MP3DecContext *mp3 = s->priv_data;
266
267     /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
268     avio_seek(s->pb, base + 4 + 32, SEEK_SET);
269     v = avio_rb32(s->pb);
270     if (v == MKBETAG('V', 'B', 'R', 'I')) {
271         /* Check tag version */
272         if (avio_rb16(s->pb) == 1) {
273             /* skip delay and quality */
274             avio_skip(s->pb, 4);
275             mp3->header_filesize = avio_rb32(s->pb);
276             mp3->frames = avio_rb32(s->pb);
277         }
278     }
279 }
280
281 /**
282  * Try to find Xing/Info/VBRI tags and compute duration from info therein
283  */
284 static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
285 {
286     uint32_t v, spf;
287     MPADecodeHeader c;
288     int vbrtag_size = 0;
289     MP3DecContext *mp3 = s->priv_data;
290
291     ffio_init_checksum(s->pb, ff_crcA001_update, 0);
292
293     v = avio_rb32(s->pb);
294     if(ff_mpa_check_header(v) < 0)
295       return -1;
296
297     if (avpriv_mpegaudio_decode_header(&c, v) == 0)
298         vbrtag_size = c.frame_size;
299     if(c.layer != 3)
300         return -1;
301
302     spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
303
304     mp3->frames = 0;
305     mp3->header_filesize   = 0;
306
307     mp3_parse_info_tag(s, st, &c, spf);
308     mp3_parse_vbri_tag(s, st, base);
309
310     if (!mp3->frames && !mp3->header_filesize)
311         return -1;
312
313     /* Skip the vbr tag frame */
314     avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
315
316     if (mp3->frames)
317         st->duration = av_rescale_q(mp3->frames, (AVRational){spf, c.sample_rate},
318                                     st->time_base);
319     if (mp3->header_filesize && mp3->frames && !mp3->is_cbr)
320         st->codec->bit_rate = av_rescale(mp3->header_filesize, 8 * c.sample_rate, mp3->frames * (int64_t)spf);
321
322     return 0;
323 }
324
325 static int mp3_read_header(AVFormatContext *s)
326 {
327     MP3DecContext *mp3 = s->priv_data;
328     AVStream *st;
329     int64_t off;
330     int ret;
331
332     st = avformat_new_stream(s, NULL);
333     if (!st)
334         return AVERROR(ENOMEM);
335
336     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
337     st->codec->codec_id = AV_CODEC_ID_MP3;
338     st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
339     st->start_time = 0;
340
341     // lcm of all mp3 sample rates
342     avpriv_set_pts_info(st, 64, 1, 14112000);
343
344     s->pb->maxsize = -1;
345     off = avio_tell(s->pb);
346
347     if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
348         ff_id3v1_read(s);
349
350     if(s->pb->seekable)
351         mp3->filesize = avio_size(s->pb);
352
353     if (mp3_parse_vbr_tags(s, st, off) < 0)
354         avio_seek(s->pb, off, SEEK_SET);
355
356     ret = ff_replaygain_export(st, s->metadata);
357     if (ret < 0)
358         return ret;
359
360     /* the parameters will be extracted from the compressed bitstream */
361     return 0;
362 }
363
364 #define MP3_PACKET_SIZE 1024
365
366 static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
367 {
368     MP3DecContext *mp3 = s->priv_data;
369     int ret, size;
370     int64_t pos;
371
372     size= MP3_PACKET_SIZE;
373     pos = avio_tell(s->pb);
374     if(mp3->filesize > ID3v1_TAG_SIZE && pos < mp3->filesize)
375         size= FFMIN(size, mp3->filesize - pos);
376
377     ret= av_get_packet(s->pb, pkt, size);
378     if (ret <= 0) {
379         if(ret<0)
380             return ret;
381         return AVERROR_EOF;
382     }
383
384     pkt->flags &= ~AV_PKT_FLAG_CORRUPT;
385     pkt->stream_index = 0;
386
387     if (ret >= ID3v1_TAG_SIZE &&
388         memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)
389         ret -= ID3v1_TAG_SIZE;
390
391     /* note: we need to modify the packet size here to handle the last
392        packet */
393     pkt->size = ret;
394     return ret;
395 }
396
397 static int check(AVFormatContext *s, int64_t pos)
398 {
399     int64_t ret = avio_seek(s->pb, pos, SEEK_SET);
400     unsigned header;
401     MPADecodeHeader sd;
402     if (ret < 0)
403         return ret;
404     header = avio_rb32(s->pb);
405     if (ff_mpa_check_header(header) < 0)
406         return -1;
407     if (avpriv_mpegaudio_decode_header(&sd, header) == 1)
408         return -1;
409     return sd.frame_size;
410 }
411
412 static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
413                     int flags)
414 {
415     MP3DecContext *mp3 = s->priv_data;
416     AVIndexEntry *ie, ie1;
417     AVStream *st = s->streams[0];
418     int64_t ret  = av_index_search_timestamp(st, timestamp, flags);
419     int i, j;
420     int dir = (flags&AVSEEK_FLAG_BACKWARD) ? -1 : 1;
421     int64_t best_pos;
422     int best_score;
423
424     if (   mp3->is_cbr
425         && st->duration > 0
426         && mp3->header_filesize > s->data_offset
427         && mp3->frames) {
428         int64_t filesize = avio_size(s->pb);
429         int64_t duration;
430         if (filesize <= s->data_offset)
431             filesize = mp3->header_filesize;
432         filesize -= s->data_offset;
433         duration = av_rescale(st->duration, filesize, mp3->header_filesize - s->data_offset);
434         ie = &ie1;
435         timestamp = av_clip64(timestamp, 0, duration);
436         ie->timestamp = timestamp;
437         ie->pos       = av_rescale(timestamp, filesize, duration) + s->data_offset;
438     } else if (mp3->xing_toc) {
439         if (ret < 0)
440             return ret;
441
442         ie = &st->index_entries[ret];
443     } else {
444         st->skip_samples = timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;
445
446         return -1;
447     }
448
449     avio_seek(s->pb, FFMAX(ie->pos - 4096, 0), SEEK_SET);
450     ret = avio_seek(s->pb, ie->pos, SEEK_SET);
451     if (ret < 0)
452         return ret;
453
454 #define MIN_VALID 3
455     best_pos = ie->pos;
456     best_score = 999;
457     for(i=0; i<4096; i++) {
458         int64_t pos = ie->pos + (dir > 0 ? i - 1024 : -i);
459         int64_t candidate = -1;
460         int score = 999;
461
462         if (pos < 0)
463             continue;
464
465         for(j=0; j<MIN_VALID; j++) {
466             ret = check(s, pos);
467             if(ret < 0)
468                 break;
469             if ((ie->pos - pos)*dir <= 0 && abs(MIN_VALID/2-j) < score) {
470                 candidate = pos;
471                 score = abs(MIN_VALID/2-j);
472             }
473             pos += ret;
474         }
475         if (best_score > score && j == MIN_VALID) {
476             best_pos = candidate;
477             best_score = score;
478             if(score == 0)
479                 break;
480         }
481     }
482
483     ret = avio_seek(s->pb, best_pos, SEEK_SET);
484     if (ret < 0)
485         return ret;
486     ff_update_cur_dts(s, st, ie->timestamp);
487     st->skip_samples = ie->timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;
488     return 0;
489 }
490
491 static const AVOption options[] = {
492     { "usetoc", "use table of contents", offsetof(MP3DecContext, usetoc), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
493     { NULL },
494 };
495
496 static const AVClass demuxer_class = {
497     .class_name = "mp3",
498     .item_name  = av_default_item_name,
499     .option     = options,
500     .version    = LIBAVUTIL_VERSION_INT,
501     .category   = AV_CLASS_CATEGORY_DEMUXER,
502 };
503
504 AVInputFormat ff_mp3_demuxer = {
505     .name           = "mp3",
506     .long_name      = NULL_IF_CONFIG_SMALL("MP2/3 (MPEG audio layer 2/3)"),
507     .read_probe     = mp3_read_probe,
508     .read_header    = mp3_read_header,
509     .read_packet    = mp3_read_packet,
510     .read_seek      = mp3_seek,
511     .priv_data_size = sizeof(MP3DecContext),
512     .flags          = AVFMT_GENERIC_INDEX,
513     .extensions     = "mp2,mp3,m2a,mpa", /* XXX: use probe */
514     .priv_class     = &demuxer_class,
515 };