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
34
37
38 #define XING_FLAG_FRAMES 0x01
39 #define XING_FLAG_SIZE 0x02
40 #define XING_FLAG_TOC 0x04
41 #define XING_FLAC_QSCALE 0x08
42
43 #define XING_TOC_COUNT 100
44
45 #define SAME_HEADER_MASK \
46 (0xffe00000 | (3 << 17) | (3 << 10) | (3 << 19))
47
55 unsigned frames;
/* Total number of frames in file */
59
61
62 /* mp3 read */
63
65 {
66 int max_frames, first_frames = 0;
70
73 while(buf0 < end && !*buf0)
74 buf0++;
75
76 max_frames = 0;
77 buf = buf0;
78
79 for(; buf <
end; buf= buf2+1) {
81 for(frames = 0; buf2 <
end; frames++) {
83
86 if (ret != 0)
87 break;
88 buf2 += h.frame_size;
89 }
90 max_frames =
FFMAX(max_frames, frames);
91 if(buf == buf0)
93 }
94 // keep this in sync with ac3 probe, both need to avoid
95 // issues with MPEG-files!
101 else if(max_frames>=1 && max_frames >= p->
buf_size/10000)
return 1;
102 else return 0;
103 //mpegps_mp3_unrecognized_format.mpg has max_frames=3
104 }
105
107 {
108 int i;
111 int fill_index = (mp3->
usetoc || fast_seek) && duration > 0;
112
113 if (!filesize &&
116 fill_index = 0;
117 }
118
121 if (fill_index)
126 }
127 if (fill_index)
129 }
130
133 {
134 #define LAST_BITS(k, n) ((k) & ((1 << (n)) - 1))
135 #define MIDDLE_BITS(k, m, n) LAST_BITS((k) >> (m), ((n) - (m)))
136
137 uint16_t crc;
138 uint32_t v;
139
141
142 uint32_t peak = 0;
143 int32_t r_gain = INT32_MIN, a_gain = INT32_MIN;
144
146 static const int64_t
xing_offtbl[2][2] = {{32, 17}, {17,9}};
149
150 /* Check for Xing / Info tag */
151 avio_skip(s->
pb, xing_offtbl[c->lsf == 1][c->nb_channels == 1]);
155 return;
156
169 "invalid concatenated file detected - using bitrate for duration\n");
170 } else if (delta > min >> 4) {
172 "filesize and duration do not match (growing file?)\n");
173 }
174 }
178 st->time_base));
179 /* VBR quality */
182
183 /* Encoder short version string */
186
187 /* Info Tag revision + VBR method */
189
190 /* Lowpass filter value */
192
193 /* ReplayGain peak */
196
197 /* Radio ReplayGain */
199
202
203 if (v & (1 << 9))
204 r_gain *= -1;
205 }
206
207 /* Audiophile ReplayGain */
209
212
213 if (v & (1 << 9))
214 a_gain *= -1;
215 }
216
217 /* Encoding flags + ATH Type */
219
220 /* if ABR {specified bitrate} else {minimal bitrate} */
222
223 /* Encoder delays */
228 ) {
229
230 mp3->start_pad = v>>12;
231 mp3-> end_pad = v&4095;
232 st->start_skip_samples = mp3->start_pad + 528 + 1;
233 if (mp3->frames) {
234 st->first_discard_sample = -mp3->end_pad + 528 + 1 + mp3->frames * (int64_t)spf;
235 st->last_discard_sample = mp3->frames * (int64_t)spf;
236 }
237 if (!st->start_time)
240 st->time_base);
242 }
243
244 /* Misc */
246
247 /* MP3 gain */
249
250 /* Preset and surround info */
252
253 /* Music length */
255
256 /* Music CRC */
258
259 /* Info Tag CRC */
262
263 if (v == crc) {
266 }
267 }
268
270 {
271 uint32_t v;
273
274 /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
277 if (v ==
MKBETAG(
'V',
'B',
'R',
'I')) {
278 /* Check tag version */
280 /* skip delay and quality */
284 }
285 }
286 }
287
288 /**
289 * Try to find Xing/Info/VBRI tags and compute duration from info therein
290 */
292 {
293 uint32_t v, spf;
295 int vbrtag_size = 0;
297 int ret;
298
300
302
304 if (ret < 0)
305 return ret;
306 else if (ret == 0)
307 vbrtag_size = c.frame_size;
308 if(c.layer != 3)
309 return -1;
310
311 spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
312
315
318
320 return -1;
321
322 /* Skip the vbr tag frame */
324
327 st->time_base);
328 if (mp3->header_filesize && mp3->frames && !mp3->is_cbr)
329 st->codec->bit_rate =
av_rescale(mp3->header_filesize, 8 *
c.sample_rate, mp3->frames * (int64_t)spf);
330
331 return 0;
332 }
333
335 {
338 int64_t off;
339 int ret;
340 int i;
341
343 if (!st)
345
350
351 // lcm of all mp3 sample rates
353
356
359
362
365
367 if (ret < 0)
368 return ret;
369
371 for (i = 0; i < 64 * 1024; i++) {
374 if (!(i&1023))
376 frame_size =
check(s->
pb, off + i, &header);
377 if (frame_size > 0) {
380 if (
check(s->
pb, off + i + frame_size, &header2) >= 0 &&
382 {
385 break;
386 }
387 }
389 }
390
391 // the seek index is relative to the end of the xing vbr headers
394
395 /* the parameters will be extracted from the compressed bitstream */
396 return 0;
397 }
398
399 #define MP3_PACKET_SIZE 1024
400
402 {
405 int64_t pos;
406
411
413 if (ret <= 0) {
414 if(ret<0)
415 return ret;
417 }
418
421
422 return ret;
423 }
424
425 #define SEEK_WINDOW 4096
426
428 {
429 int64_t ret =
avio_seek(pb, pos, SEEK_SET);
432 if (ret < 0)
433 return ret;
434
437 return -1;
439 return -1;
440
441 if (ret_header)
443 return sd.frame_size;
444 }
445
447 {
449 int64_t best_pos;
450 int best_score, i, j;
451 int64_t ret;
452
455 if (ret < 0)
456 return ret;
457
458 #define MIN_VALID 3
459 best_pos = target_pos;
460 best_score = 999;
462 int64_t pos = target_pos + (dir > 0 ? i - SEEK_WINDOW/4 : -i);
463 int64_t candidate = -1;
464 int score = 999;
465
466 if (pos < 0)
467 continue;
468
471 if(ret < 0)
472 break;
473 if ((target_pos - pos)*dir <= 0 && abs(MIN_VALID/2-j) < score) {
474 candidate = pos;
475 score = abs(MIN_VALID/2-j);
476 }
477 pos += ret;
478 }
479 if (best_score > score && j == MIN_VALID) {
480 best_pos = candidate;
481 best_score = score;
482 if(score == 0)
483 break;
484 }
485 }
486
488 }
489
492 {
496 int64_t best_pos;
499
500 if (filesize <= 0) {
504 }
505
508
509 // NOTE: The MP3 TOC is not a precise lookup table. Accuracy is worse
510 // for bigger files.
512
513 if (ret < 0)
514 return ret;
515
517 }
else if (fast_seek && st->
duration > 0 && filesize > 0) {
520
521 ie = &ie1;
522 timestamp = av_clip64(timestamp, 0, st->
duration);
525 } else {
526 return -1; // generic index code
527 }
528
530 if (best_pos < 0)
531 return best_pos;
532
536 }
537
539 return 0;
540 }
541
545 };
546
553 };
554
564 .extensions = "mp2,mp3,m2a,mpa", /* XXX: use probe */
565 .priv_class = &demuxer_class,
566 };
int64_t avio_size(AVIOContext *s)
Get the filesize.
int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp, int size, int distance, int flags)
Add an index entry into a sorted list.
#define AV_LOG_WARNING
Something somehow does not look correct.
#define LIBAVUTIL_VERSION_INT
void ff_id3v1_read(AVFormatContext *s)
Read an ID3v1 tag.
#define ID3v2_DEFAULT_MAGIC
Default magic bytes for ID3v2 header: "ID3".
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
AVIndexEntry * index_entries
Only used if the format does not support seeking natively.
AVFormatInternal * internal
An opaque field for libavformat internal usage.
static void read_xing_toc(AVFormatContext *s, int64_t filesize, int64_t duration)
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
unsigned int avio_rb16(AVIOContext *s)
int64_t maxsize
max filesize, used to limit allocations This field is internal to libavformat and access from outside...
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
unsigned int avio_rb32(AVIOContext *s)
static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
static av_cold int end(AVCodecContext *avctx)
enum AVStreamParseType need_parsing
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_RB32
AVStream ** streams
A list of all streams in the file.
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
int flags
Flags modifying the (de)muxer behaviour.
static const uint8_t xing_offtbl[2][2]
#define AVERROR_EOF
End of file.
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
static const uint8_t header[24]
int ff_replaygain_export(AVStream *st, AVDictionary *metadata)
Parse replaygain tags and export them as per-stream side data.
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
AVDictionary * metadata
Metadata that applies to the whole file.
int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags)
Get the index for a specific timestamp.
int64_t timestamp
Timestamp in AVStream.time_base units, preferably the time from which on correctly decoded frames are...
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
static int mp3_read_header(AVFormatContext *s)
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
preferred ID for decoding MPEG audio layer 1, 2 or 3
int flags
A combination of AV_PKT_FLAG values.
int avio_r8(AVIOContext *s)
AVCodecContext * codec
Codec context associated with this stream.
int buf_size
Size of buf except extra allocated bytes.
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
void ffio_init_checksum(AVIOContext *s, unsigned long(*update_checksum)(unsigned long c, const uint8_t *p, unsigned int len), unsigned long checksum)
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
unsigned int avio_rb24(AVIOContext *s)
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
static int check(AVIOContext *pb, int64_t pos, uint32_t *header)
static void mp3_parse_info_tag(AVFormatContext *s, AVStream *st, MPADecodeHeader *c, uint32_t spf)
static int64_t mp3_sync(AVFormatContext *s, int64_t target_pos, int flags)
unsigned long ff_crcA001_update(unsigned long checksum, const uint8_t *buf, unsigned int len)
static void mp3_parse_vbri_tag(AVFormatContext *s, AVStream *st, int64_t base)
static int mp3_read_probe(AVProbeData *p)
#define AV_LOG_INFO
Standard information.
Libavcodec external API header.
enum AVMediaType codec_type
AVIOContext * pb
I/O context.
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Describe the class of an AVClass context structure.
static const AVOption options[]
rational number numerator/denominator
#define AV_OPT_FLAG_DECODING_PARAM
a generic parameter which can be set by the user for demuxing or decoding
unsigned long ffio_get_checksum(AVIOContext *s)
This structure contains the data a format has to probe a file.
int ffio_ensure_seekback(AVIOContext *s, int64_t buf_size)
Ensures that the requested seekback buffer size will be available.
int64_t duration
Decoding: duration of the stream, in stream time base.
static const AVClass demuxer_class
int ff_id3v2_match(const uint8_t *buf, const char *magic)
Detect ID3v2 Header.
int ff_replaygain_export_raw(AVStream *st, int32_t tg, uint32_t tp, int32_t ag, uint32_t ap)
Export already decoded replaygain values as per-stream side data.
int64_t start_time
Decoding: pts of the first frame of the stream in presentation order, in stream time base...
AVInputFormat ff_mp3_demuxer
#define AV_PKT_FLAG_CORRUPT
The packet content is corrupted.
#define MKBETAG(a, b, c, d)
#define MIDDLE_BITS(k, m, n)
int ff_id3v2_tag_len(const uint8_t *buf)
Get the length of an ID3v2 tag.
void * priv_data
Format private data.
static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
Try to find Xing/Info/VBRI tags and compute duration from info therein.
#define AV_DICT_IGNORE_SUFFIX
Return first entry in a dictionary whose first part corresponds to the search key, ignoring the suffix of the found key string.
This structure stores compressed data.