FFmpeg
Loading...
Searching...
No Matches
mp3dec.c
Go to the documentation of this file.
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 <string.h>
23
24#include "libavutil/opt.h"
26#include "libavutil/dict.h"
28#include "libavutil/mem.h"
29#include "avformat.h"
30#include "internal.h"
31#include "avio_internal.h"
32#include "apetag.h"
33#include "demux.h"
34#include "id3v2.h"
35#include "id3v1.h"
36#include "replaygain.h"
37
38#include "libavcodec/codec_id.h"
41
42#define XING_FLAG_FRAMES 0x01
43#define XING_FLAG_SIZE 0x02
44#define XING_FLAG_TOC 0x04
45#define XING_FLAC_QSCALE 0x08
46
47#define XING_TOC_COUNT 100
48
49
50typedef struct {
51 AVClass *class;
56 int usetoc;
57 unsigned frames; /* Total number of frames in file */
58 unsigned header_filesize; /* Total number of bytes in the stream */
59 unsigned frame_duration; /* Frame duration in st->time_base */
60 int is_cbr;
62
67
68static int check(AVIOContext *pb, int64_t pos, uint32_t *header);
69
70/* mp3 read */
71
72static int mp3_read_probe(const AVProbeData *p)
73{
74 int max_frames, first_frames = 0;
75 int whole_used = 0;
76 int frames, ret;
77 int framesizes, max_framesizes;
78 uint32_t header;
79 const uint8_t *buf, *buf0, *buf2, *buf3, *end;
81
82 buf0 = p->buf;
83 end = p->buf + p->buf_size - sizeof(uint32_t);
84 while (buf0 < end && !*buf0)
85 buf0++;
86
87 max_frames = 0;
88 max_framesizes = 0;
89 buf = buf0;
90
91 for (; buf < end; buf = buf2+1) {
92 buf2 = buf;
93 for (framesizes = frames = 0; buf2 < end; frames++) {
94 int header_emu = 0;
95 int available;
96
97 header = AV_RB32(buf2);
99 if (ret != 0)
100 break;
101
102 available = FFMIN(h->frame_size, end - buf2);
103 for (buf3 = buf2 + 4; buf3 < buf2 + available; buf3++) {
104 uint32_t next_sync = AV_RB32(buf3);
105 header_emu += (next_sync & MP3_MASK) == (header & MP3_MASK);
106 }
107 if (header_emu > 2)
108 break;
109 framesizes += h->frame_size;
110 if (available < h->frame_size) {
111 frames++;
112 break;
113 }
114 buf2 += h->frame_size;
115 }
116 max_frames = FFMAX(max_frames, frames);
117 max_framesizes = FFMAX(max_framesizes, framesizes);
118 if (buf == buf0) {
119 first_frames= frames;
120 if (buf2 == end + sizeof(uint32_t))
121 whole_used = 1;
122 }
123 }
124 av_freep(&h);
125
126 // keep this in sync with ac3 probe, both need to avoid
127 // issues with MPEG-files!
128 if (first_frames>=7) return AVPROBE_SCORE_EXTENSION + 2;
129 else if (max_frames>200 && p->buf_size < 2*max_framesizes)return AVPROBE_SCORE_EXTENSION;
130 else if (max_frames>=4 && p->buf_size < 2*max_framesizes) return AVPROBE_SCORE_EXTENSION / 2;
131 else if (ff_id3v2_match(buf0, ID3v2_DEFAULT_MAGIC) && 2*ff_id3v2_tag_len(buf0) >= p->buf_size)
132 return p->buf_size < PROBE_BUF_MAX ? AVPROBE_SCORE_EXTENSION / 4 : AVPROBE_SCORE_EXTENSION - 2;
133 else if (first_frames > 1 && whole_used) return 5;
134 else if (max_frames>=1 && p->buf_size < 10*max_framesizes) return 1;
135 else return 0;
136 //mpegps_mp3_unrecognized_format.mpg has max_frames=3
137}
138
140{
141 int i;
142 MP3DecContext *mp3 = s->priv_data;
143 int fast_seek = s->flags & AVFMT_FLAG_FAST_SEEK;
144 int fill_index = (mp3->usetoc || fast_seek) && duration > 0;
145
146 if (!filesize &&
147 (filesize = avio_size(s->pb)) <= 0) {
148 av_log(s, AV_LOG_WARNING, "Cannot determine file size, skipping TOC table.\n");
149 fill_index = 0;
150 filesize = 0;
151 }
152
153 for (i = 0; i < XING_TOC_COUNT; i++) {
154 uint8_t b = avio_r8(s->pb);
155 if (fill_index)
156 av_add_index_entry(s->streams[0],
157 av_rescale(b, filesize, 256),
159 0, 0, AVINDEX_KEYFRAME);
160 }
161 if (fill_index)
162 mp3->xing_toc = 1;
163}
164
165/**
166 * Size of the ID3v1 and APEv2 tags at the end of the file. They are not part
167 * of the MPEG stream, so the Xing/Info byte count does not include them.
168 * The read position is restored.
169 *
170 * @return the size in bytes, or a negative AVERROR code if seeking failed
171 */
173{
174 AVIOContext *pb = s->pb;
175 int64_t pos = avio_tell(pb), size = 0, ret = 0;
176 uint8_t buf[3];
177
178 if (end > ID3v1_TAG_SIZE) {
179 ret = avio_seek(pb, end - ID3v1_TAG_SIZE, SEEK_SET);
180 if (ret >= 0 && avio_read(pb, buf, 3) == 3 && !memcmp(buf, "TAG", 3))
182 }
183 if (ret >= 0) {
184 ret = ff_ape_tag_size(s, end - size);
185 if (ret > 0)
186 size += ret;
187 }
188
189 pos = avio_seek(pb, pos, SEEK_SET);
190 if (ret < 0)
191 return ret;
192 return pos < 0 ? pos : size;
193}
194
196 MPADecodeHeader2 *c, uint32_t spf)
197{
198#define LAST_BITS(k, n) ((k) & ((1 << (n)) - 1))
199#define MIDDLE_BITS(k, m, n) LAST_BITS((k) >> (m), ((n) - (m) + 1))
200
201 FFStream *const sti = ffstream(st);
202 uint16_t crc;
203 uint32_t v;
204
205 char version[10];
206
207 uint32_t peak = 0;
208 int32_t r_gain = INT32_MIN, a_gain = INT32_MIN;
209
210 MP3DecContext *mp3 = s->priv_data;
211 static const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
212 uint64_t fsize = avio_size(s->pb);
213 int64_t pos = avio_tell(s->pb);
214 fsize = fsize >= pos ? fsize - pos : 0;
215
216 /* Check for Xing / Info tag */
217 avio_skip(s->pb, xing_offtbl[c->lsf == 1][c->nb_channels == 1]);
218 v = avio_rb32(s->pb);
219 mp3->is_cbr = v == MKBETAG('I', 'n', 'f', 'o');
220 if (v != MKBETAG('X', 'i', 'n', 'g') && !mp3->is_cbr)
221 return 0;
222
223 v = avio_rb32(s->pb);
224 if (v & XING_FLAG_FRAMES)
225 mp3->frames = avio_rb32(s->pb);
226 if (v & XING_FLAG_SIZE)
227 mp3->header_filesize = avio_rb32(s->pb);
228 if (fsize && mp3->header_filesize) {
229 uint64_t min, delta;
230
231 /* Avoid seeking to the end unless trailing tags could make us
232 * incorrectly reject the frame count. Preserve the Info tag CRC
233 * across the seek. */
234 if (fsize > mp3->header_filesize &&
235 fsize - mp3->header_filesize > mp3->header_filesize >> 4 &&
236 (s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
237 unsigned long checksum = ffio_get_checksum(s->pb);
238 int64_t trailing_tags_size = mp3_trailing_tags_size(s, mp3->filesize);
239
240 if (trailing_tags_size < 0) {
241 av_log(s, AV_LOG_ERROR, "Failed to read the trailing tags\n");
242 return trailing_tags_size;
243 }
244 ffio_init_checksum(s->pb, ff_crcA001_update, checksum);
245 fsize -= FFMIN(fsize, trailing_tags_size);
246 }
247
250 if (fsize > mp3->header_filesize && delta > min >> 4) {
251 mp3->frames = 0;
253 "invalid concatenated file detected - using bitrate for duration\n");
254 } else if (delta > min >> 4) {
256 "filesize and duration do not match (growing file?)\n");
257 }
258 }
259 if (v & XING_FLAG_TOC)
261 (AVRational){spf, c->sample_rate},
262 st->time_base));
263 /* VBR quality */
264 if (v & XING_FLAC_QSCALE)
265 avio_rb32(s->pb);
266
267 /* Encoder short version string */
268 memset(version, 0, sizeof(version));
269 avio_read(s->pb, version, 9);
270
271 /* Info Tag revision + VBR method */
272 avio_r8(s->pb);
273
274 /* Lowpass filter value */
275 avio_r8(s->pb);
276
277 /* ReplayGain peak */
278 v = avio_rb32(s->pb);
279 peak = av_rescale(v, 100000, 1 << 23);
280
281 /* Radio ReplayGain */
282 v = avio_rb16(s->pb);
283
284 if (MIDDLE_BITS(v, 13, 15) == 1) {
285 r_gain = MIDDLE_BITS(v, 0, 8) * 10000;
286
287 if (v & (1 << 9))
288 r_gain *= -1;
289 }
290
291 /* Audiophile ReplayGain */
292 v = avio_rb16(s->pb);
293
294 if (MIDDLE_BITS(v, 13, 15) == 2) {
295 a_gain = MIDDLE_BITS(v, 0, 8) * 10000;
296
297 if (v & (1 << 9))
298 a_gain *= -1;
299 }
300
301 /* Encoding flags + ATH Type */
302 avio_r8(s->pb);
303
304 /* if ABR {specified bitrate} else {minimal bitrate} */
305 avio_r8(s->pb);
306
307 /* Encoder delays */
308 v = avio_rb24(s->pb);
309 if (AV_RB32(version) == MKBETAG('L', 'A', 'M', 'E')
310 || AV_RB32(version) == MKBETAG('L', 'a', 'v', 'f')
311 || AV_RB32(version) == MKBETAG('L', 'a', 'v', 'c')
312 ) {
313
314 mp3->start_pad = v>>12;
315 mp3-> end_pad = v&4095;
317 if (mp3->frames) {
318 sti->first_discard_sample = -mp3->end_pad + MP3_DECODER_DELAY + mp3->frames * (int64_t)spf;
319 sti->last_discard_sample = mp3->frames * (int64_t)spf;
320 }
321 av_log(s, AV_LOG_DEBUG, "pad %d %d\n", mp3->start_pad, mp3-> end_pad);
322 }
323
324 /* Misc */
325 avio_r8(s->pb);
326
327 /* MP3 gain */
328 avio_r8(s->pb);
329
330 /* Preset and surround info */
331 avio_rb16(s->pb);
332
333 /* Music length */
334 avio_rb32(s->pb);
335
336 /* Music CRC */
337 avio_rb16(s->pb);
338
339 /* Info Tag CRC */
340 crc = ffio_get_checksum(s->pb);
341 v = avio_rb16(s->pb);
342
343 if (v == crc) {
344 ff_replaygain_export_raw(st, r_gain, peak, a_gain, 0);
345 av_dict_set(&st->metadata, "encoder", version, 0);
346 }
347 return 0;
348}
349
351{
352 uint32_t v;
353 MP3DecContext *mp3 = s->priv_data;
354
355 /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
356 avio_seek(s->pb, base + 4 + 32, SEEK_SET);
357 v = avio_rb32(s->pb);
358 if (v == MKBETAG('V', 'B', 'R', 'I')) {
359 /* Check tag version */
360 if (avio_rb16(s->pb) == 1) {
361 /* skip delay and quality */
362 avio_skip(s->pb, 4);
363 mp3->header_filesize = avio_rb32(s->pb);
364 mp3->frames = avio_rb32(s->pb);
365 }
366 }
367}
368
369/**
370 * Look the iTunSMPB tag up under every key it can land on. A COMM frame keeps
371 * its language in the key, and while Apple writes eng, anything that retags
372 * the file is free to write its own, valid or not.
373 *
374 * The bare key is for files remuxed by versions that exposed a COMM descriptor
375 * as a metadata key of its own: those wrote the tag back out as a TXXX frame,
376 * which carries no language and is keyed by its description alone.
377 */
379{
380 static const char comment[] = "comment-iTunSMPB";
381 const AVDictionaryEntry *de = NULL;
382
383 while ((de = av_dict_get(metadata, comment, de, AV_DICT_IGNORE_SUFFIX))) {
384 const char *lang = de->key + sizeof(comment) - 1;
385
386 /* und and xxx come without a suffix, the rest as a three letter one. */
387 if (!*lang || (*lang == '-' && strlen(lang + 1) == 3))
388 return de;
389 }
390
391 return av_dict_get(metadata, "iTunSMPB", NULL, 0);
392}
393
394/**
395 * Parse the gapless playback information Apple encoders store in an iTunSMPB
396 * comment instead of in the LAME extension of the Xing tag.
397 */
399 const MPADecodeHeader2 *c, uint32_t spf)
400{
401 FFStream *const sti = ffstream(st);
402 MP3DecContext *mp3 = s->priv_data;
403 const AVDictionaryEntry *de;
404 int64_t priming, remainder, samples;
405
406 /* A LAME tag, if any, already described the padding. */
407 if (sti->start_skip_samples)
408 return;
409
410 if (!(de = find_itunes_smpb(s->metadata)))
411 return;
412
413 if (ff_itunes_parse_smpb(de->value, &priming, &remainder, &samples) < 0)
414 return;
415
416 if (priming > 16384 || !samples)
417 return;
418
419 /* The three counts must add up to what the frames actually decode to. */
420 if (mp3->frames &&
421 priming + samples + remainder != mp3->frames * (int64_t)spf)
422 return;
423
424 /* As in the LAME tag, priming and remainder exclude the decoder delay:
425 * Core Audio (afconvert) outputs the sample count starting that far past
426 * the priming. */
427 sti->start_skip_samples = priming + MP3_DECODER_DELAY;
428 sti->first_discard_sample = priming + MP3_DECODER_DELAY + samples;
429 sti->last_discard_sample = priming + samples + remainder;
430
431 st->duration = av_rescale_q(samples, (AVRational){ 1, c->sample_rate },
432 st->time_base);
433}
434
435/**
436 * Try to find Xing/Info/VBRI tags and compute duration from info therein
437 */
439{
440 uint32_t v, spf;
442 int vbrtag_size = 0;
443 MP3DecContext *mp3 = s->priv_data;
444 int ret;
445
447
448 v = avio_rb32(s->pb);
449
451 if (ret < 0)
452 goto end;
453 else if (ret == 0)
454 vbrtag_size = c->frame_size;
455 if (c->layer != 3) {
456 ret = -1;
457 goto end;
458 }
459
460 spf = c->lsf ? 576 : 1152; /* Samples per frame, layer 3 */
461
462 mp3->frames = 0;
463 mp3->header_filesize = 0;
464 mp3->frame_duration = av_rescale_q(spf, (AVRational){1, c->sample_rate}, st->time_base);
465
466 ret = mp3_parse_info_tag(s, st, c, spf);
467 if (ret < 0) {
468 mp3->frames = 0;
469 mp3->header_filesize = 0;
470 goto end;
471 }
473 mp3_parse_itunes_smpb(s, st, c, spf);
474
475 /* Packets keep the skipped samples, so shift the timeline instead. */
476 if (ffstream(st)->start_skip_samples) {
478 st->start_time = av_rescale_q(ffstream(st)->start_skip_samples,
479 (AVRational){1, c->sample_rate},
480 st->time_base);
481 }
482
483 if (!mp3->frames && !mp3->header_filesize) {
484 ret = -1;
485 goto end;
486 }
487
488 /* Skip the vbr tag frame */
489 avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
490
491 if (mp3->frames) {
492 int64_t full_duration_samples;
493
494 full_duration_samples = mp3->frames * (int64_t)spf;
495 if (st->duration == AV_NOPTS_VALUE)
496 st->duration = av_rescale_q(full_duration_samples - mp3->start_pad - mp3->end_pad,
497 (AVRational){1, c->sample_rate},
498 st->time_base);
499
500 if (mp3->header_filesize && !mp3->is_cbr)
501 st->codecpar->bit_rate = av_rescale(mp3->header_filesize, 8 * c->sample_rate,
502 full_duration_samples);
503 }
504
505 ret = 0;
506
507end:
508 av_freep(&c);
509 return ret;
510}
511
513{
514 FFFormatContext *const si = ffformatcontext(s);
515 MP3DecContext *mp3 = s->priv_data;
516 AVStream *st;
517 FFStream *sti;
518 int64_t off;
519 int ret;
520 int i;
521
522 s->metadata = si->id3v2_meta;
523 si->id3v2_meta = NULL;
524
526 if (!st)
527 return AVERROR(ENOMEM);
528 sti = ffstream(st);
529
533 st->start_time = 0;
534
535 // lcm of all mp3 sample rates
536 avpriv_set_pts_info(st, 64, 1, 14112000);
537
538 ffiocontext(s->pb)->maxsize = -1;
539 off = avio_tell(s->pb);
540
541 if (!av_dict_count(s->metadata))
543
544 if (s->pb->seekable & AVIO_SEEKABLE_NORMAL)
545 mp3->filesize = avio_size(s->pb);
546
547 if (mp3_parse_vbr_tags(s, st, off) < 0)
548 avio_seek(s->pb, off, SEEK_SET);
549
550 ret = ff_replaygain_export(st, s->metadata);
551 if (ret < 0)
552 return ret;
553
554 ret = ffio_ensure_seekback(s->pb, 64 * 1024 + MPA_MAX_CODED_FRAME_SIZE + 4);
555 if (ret < 0)
556 return ret;
557
558 off = avio_tell(s->pb);
559 for (i = 0; i < 64 * 1024; i++) {
560 uint32_t header, header2;
561 int frame_size;
562 frame_size = check(s->pb, off + i, &header);
563 if (frame_size > 0) {
564 ret = check(s->pb, off + i + frame_size, &header2);
565 if (ret >= 0 && (header & MP3_MASK) == (header2 & MP3_MASK))
566 break;
567 } else if (frame_size == CHECK_SEEK_FAILED) {
568 av_log(s, AV_LOG_ERROR, "Failed to find two consecutive MPEG audio frames.\n");
569 return AVERROR_INVALIDDATA;
570 }
571 }
572 if (i == 64 * 1024) {
573 off = avio_seek(s->pb, off, SEEK_SET);
574 } else {
575 av_log(s, i > 0 ? AV_LOG_INFO : AV_LOG_VERBOSE, "Skipping %d bytes of junk at %"PRId64".\n", i, off);
576 off = avio_seek(s->pb, off + i, SEEK_SET);
577 }
578 if (off < 0)
579 return off;
580
581 // the seek index is relative to the end of the xing vbr headers
582 for (int i = 0; i < sti->nb_index_entries; i++)
583 sti->index_entries[i].pos += off;
584
585 /* the parameters will be extracted from the compressed bitstream */
586 return 0;
587}
588
589#define MP3_PACKET_SIZE 1024
590
592{
593 MP3DecContext *mp3 = s->priv_data;
594 int ret, size;
595 int64_t pos;
596
598 pos = avio_tell(s->pb);
600 size= FFMIN(size, mp3->filesize - pos);
601
602 ret = av_get_packet(s->pb, pkt, size);
603 if (ret <= 0) {
604 if(ret<0)
605 return ret;
606 return AVERROR_EOF;
607 }
608
609 pkt->flags &= ~AV_PKT_FLAG_CORRUPT;
610 pkt->stream_index = 0;
611
612 return ret;
613}
614
615#define SEEK_WINDOW 4096
616
617static int check(AVIOContext *pb, int64_t pos, uint32_t *ret_header)
618{
619 int64_t ret = avio_seek(pb, pos, SEEK_SET);
620 uint8_t header_buf[4];
621 unsigned header;
623 int frame_size;
624 if (ret < 0)
625 return CHECK_SEEK_FAILED;
626
627 ret = avio_read(pb, &header_buf[0], 4);
628 /* We should always find four bytes for a valid mpa header. */
629 if (ret < 4)
630 return CHECK_SEEK_FAILED;
631
632 header = AV_RB32(&header_buf[0]);
634 return CHECK_WRONG_HEADER;
636 av_freep(&sd);
637 return CHECK_WRONG_HEADER;
638 }
640 av_freep(&sd);
641
642 if (ret_header)
643 *ret_header = header;
644 return frame_size;
645}
646
648{
649 int dir = (flags&AVSEEK_FLAG_BACKWARD) ? -1 : 1;
650 int64_t best_pos;
651 int best_score, i, j;
652 int64_t ret;
653
654 avio_seek(s->pb, FFMAX(target_pos - SEEK_WINDOW, 0), SEEK_SET);
655 ret = avio_seek(s->pb, target_pos, SEEK_SET);
656 if (ret < 0)
657 return ret;
658
659#define MIN_VALID 3
660 best_pos = target_pos;
661 best_score = 999;
662 for (i = 0; i < SEEK_WINDOW; i++) {
663 int64_t pos = target_pos + (dir > 0 ? i - SEEK_WINDOW/4 : -i);
664 int64_t candidate = -1;
665 int score = 999;
666
667 if (pos < 0)
668 continue;
669
670 for (j = 0; j < MIN_VALID; j++) {
671 ret = check(s->pb, pos, NULL);
672 if (ret < 0) {
673 if (ret == CHECK_WRONG_HEADER) {
674 break;
675 } else if (ret == CHECK_SEEK_FAILED) {
676 av_log(s, AV_LOG_ERROR, "Could not seek to %"PRId64".\n", pos);
677 return AVERROR(EINVAL);
678 }
679 }
680 if ((target_pos - pos)*dir <= 0 && FFABS(MIN_VALID/2-j) < score) {
681 candidate = pos;
682 score = FFABS(MIN_VALID/2-j);
683 }
684 pos += ret;
685 }
686 if (best_score > score && j == MIN_VALID) {
687 best_pos = candidate;
688 best_score = score;
689 if(score == 0)
690 break;
691 }
692 }
693
694 return avio_seek(s->pb, best_pos, SEEK_SET);
695}
696
697static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
698 int flags)
699{
700 FFFormatContext *const si = ffformatcontext(s);
701 MP3DecContext *mp3 = s->priv_data;
702 AVIndexEntry *ie, ie1;
703 AVStream *st = s->streams[0];
704 FFStream *const sti = ffstream(st);
705 int64_t best_pos;
706 int fast_seek = s->flags & AVFMT_FLAG_FAST_SEEK;
708
709 if (filesize <= 0) {
710 int64_t size = avio_size(s->pb);
711 if (size > 0 && size > si->data_offset)
712 filesize = size - si->data_offset;
713 }
714
715 if (mp3->xing_toc && (mp3->usetoc || (fast_seek && !mp3->is_cbr))) {
716 int64_t ret = av_index_search_timestamp(st, timestamp, flags);
717
718 // NOTE: The MP3 TOC is not a precise lookup table. Accuracy is worse
719 // for bigger files.
720 av_log(s, AV_LOG_WARNING, "Using MP3 TOC to seek; may be imprecise.\n");
721
722 if (ret < 0)
723 return ret;
724
725 ie = &sti->index_entries[ret];
726 } else if (fast_seek && st->duration > 0 && filesize > 0) {
727 if (!mp3->is_cbr)
728 av_log(s, AV_LOG_WARNING, "Using scaling to seek VBR MP3; may be imprecise.\n");
729
730 ie = &ie1;
731 timestamp = av_clip64(timestamp, 0, st->duration);
732 ie->timestamp = timestamp;
733 ie->pos = av_rescale(timestamp, filesize, st->duration) + si->data_offset;
734 } else {
735 return -1; // generic index code
736 }
737
738 best_pos = mp3_sync(s, ie->pos, flags);
739 if (best_pos < 0)
740 return best_pos;
741
742 if (mp3->is_cbr && ie == &ie1 && mp3->frames && mp3->header_filesize > 0) {
743 ie1.timestamp = mp3->frame_duration * av_rescale(best_pos - si->data_offset, mp3->frames, mp3->header_filesize);
744 }
745
747 return 0;
748}
749
750static const AVOption options[] = {
751 { "usetoc", "use table of contents", offsetof(MP3DecContext, usetoc), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM},
752 { NULL },
753};
754
755static const AVClass demuxer_class = {
756 .class_name = "mp3",
757 .item_name = av_default_item_name,
758 .option = options,
759 .version = LIBAVUTIL_VERSION_INT,
760 .category = AV_CLASS_CATEGORY_DEMUXER,
761};
762
764 .p.name = "mp3",
765 .p.long_name = NULL_IF_CONFIG_SMALL("MP2/3 (MPEG audio layer 2/3)"),
766 .p.flags = AVFMT_GENERIC_INDEX,
767 .p.extensions = "mp2,mp3,m2a,mpa", /* XXX: use probe */
768 .p.priv_class = &demuxer_class,
769 .p.mime_type = "audio/mpeg",
770 .flags_internal = FF_INFMT_FLAG_ID3V2_AUTO,
771 .read_probe = mp3_read_probe,
772 .read_header = mp3_read_header,
773 .read_packet = mp3_read_packet,
774 .read_seek = mp3_seek,
775 .priv_data_size = sizeof(MP3DecContext),
776};
const FFInputFormat ff_mp3_demuxer
Definition mp3dec.c:763
int64_t ff_ape_tag_size(AVFormatContext *s, int64_t end)
Get the size of the APE tag that ends at end, without reading its items.
Definition apetag.c:197
static int frames
static const AVClass demuxer_class
Definition apngdec.c:478
int32_t
static int64_t fsize(FILE *f)
Definition audiomatch.c:29
void avpriv_set_pts_info(AVStream *st, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition avformat.c:865
Main libavformat public API header.
#define AVINDEX_KEYFRAME
Definition avformat.h:630
#define AVFMT_FLAG_FAST_SEEK
Enable fast, but inaccurate seeks for some formats.
Definition avformat.h:1572
#define AVPROBE_SCORE_EXTENSION
score for file extension
Definition avformat.h:483
int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
Allocate and read the payload of a packet and initialize its fields with default values.
Definition utils.c:98
#define AVSEEK_FLAG_BACKWARD
seek backward
Definition avformat.h:2747
#define AVFMT_GENERIC_INDEX
Use generic index building code.
Definition avformat.h:501
@ AVSTREAM_PARSE_FULL_RAW
full parsing and repack with timestamp and position generation by parser for raw this assumes that ea...
Definition avformat.h:617
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition aviobuf.c:236
#define AVIO_SEEKABLE_NORMAL
Seeking works like for a local file.
Definition avio.h:41
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition aviobuf.c:326
unsigned int avio_rb16(AVIOContext *s)
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition avio.h:507
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition aviobuf.c:321
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition aviobuf.c:620
unsigned int avio_rb24(AVIOContext *s)
unsigned int avio_rb32(AVIOContext *s)
int avio_r8(AVIOContext *s)
Definition aviobuf.c:611
void ffio_init_checksum(AVIOContext *s, unsigned long(*update_checksum)(unsigned long c, const uint8_t *p, unsigned int len), unsigned long checksum)
Definition aviobuf.c:599
unsigned long ff_crcA001_update(unsigned long checksum, const uint8_t *buf, unsigned int len)
Definition aviobuf.c:585
static av_always_inline FFIOContext * ffiocontext(AVIOContext *ctx)
unsigned long ffio_get_checksum(AVIOContext *s)
Definition aviobuf.c:591
int ffio_ensure_seekback(AVIOContext *s, int64_t buf_size)
Ensures that the requested seekback buffer size will be available.
Definition aviobuf.c:994
static int FUNC metadata(CodedBitstreamContext *ctx, RWContext *rw, APVRawMetadata *current)
#define flags(name, subs,...)
Definition cbs_h264.c:74
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
static int FUNC comment(CodedBitstreamContext *ctx, RWContext *rw, JPEGRawComment *current)
#define s(width, name)
Definition cbs_vp9.c:198
#define av_clip64
Definition common.h:103
#define FFABS(a)
Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they are not representable ...
Definition common.h:74
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
#define min(a, b)
#define FF_INFMT_FLAG_ID3V2_AUTO
Automatically parse ID3v2 metadata.
Definition demux.h:45
int ff_itunes_parse_smpb(const char *value, int64_t *priming, int64_t *remainder, int64_t *samples)
Parse the gapless playback information Apple encoders store in an iTunSMPB tag.
void avpriv_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
Update cur_dts of all streams based on the given timestamp and AVStream.
Definition seek.c:37
static AVPacket * pkt
Public dictionary API.
static int64_t filesize(AVIOContext *pb)
Definition ffmpeg_mux.c:52
static int64_t duration
Definition ffplay.c:359
int ret
Definition ffplay.c:391
static const uint8_t frame_size[4]
Definition g723_1.h:222
#define AV_OPT_FLAG_DECODING_PARAM
A generic parameter which can be set by the user for demuxing or decoding.
Definition opt.h:355
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
Definition opt.h:326
@ AV_CODEC_ID_MP3
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition codec_id.h:460
#define AV_PKT_FLAG_CORRUPT
The packet content is corrupted.
Definition packet.h:658
AVStream * avformat_new_stream(AVFormatContext *s, const struct AVCodec *c)
Add a new stream to a media file.
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.
Definition seek.c:122
int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags)
Get the index for a specific timestamp.
Definition seek.c:245
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition dict.c:61
#define AV_DICT_IGNORE_SUFFIX
Return first entry in a dictionary whose first part corresponds to the search key,...
Definition dict.h:75
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition dict.c:87
int av_dict_count(const AVDictionary *m)
Get number of entries in dictionary.
Definition dict.c:38
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR_EOF
End of file.
Definition error.h:57
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_VERBOSE
Detailed information.
Definition log.h:226
#define AV_LOG_INFO
Standard information.
Definition log.h:221
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:247
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition avutil.h:247
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
void ff_id3v1_read(AVFormatContext *s)
Read an ID3v1 tag.
Definition id3v1.c:278
#define ID3v1_TAG_SIZE
Definition id3v1.h:27
int ff_id3v2_tag_len(const uint8_t *buf)
Get the length of an ID3v2 tag.
Definition reader.c:165
int ff_id3v2_match(const uint8_t *buf, const char *magic)
Detect ID3v2 Header.
Definition reader.c:152
#define ID3v2_DEFAULT_MAGIC
Default magic bytes for ID3v2 header: "ID3".
Definition id3v2.h:35
#define b
Definition input.c:43
#define AV_RB32(p)
static av_always_inline FFStream * ffstream(AVStream *st)
Definition internal.h:392
#define PROBE_BUF_MAX
Definition internal.h:34
static av_always_inline FFFormatContext * ffformatcontext(AVFormatContext *s)
Definition internal.h:135
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition internal.h:97
version
Definition libkvazaar.c:313
@ AV_CLASS_CATEGORY_DEMUXER
Definition log.h:33
#define FFMIN(a, b)
Definition macros.h:49
#define MKBETAG(a, b, c, d)
Definition macros.h:56
#define FFMAX(a, b)
Definition macros.h:47
Memory handling functions.
#define check(x, y, S, v)
CheckRet
Definition mp3dec.c:63
@ CHECK_SEEK_FAILED
Definition mp3dec.c:65
@ CHECK_WRONG_HEADER
Definition mp3dec.c:64
static int mp3_read_header(AVFormatContext *s)
Definition mp3dec.c:512
#define XING_FLAC_QSCALE
Definition mp3dec.c:45
#define MIN_VALID
static int64_t mp3_trailing_tags_size(AVFormatContext *s, int64_t end)
Size of the ID3v1 and APEv2 tags at the end of the file.
Definition mp3dec.c:172
static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Definition mp3dec.c:697
#define MP3_PACKET_SIZE
Definition mp3dec.c:589
#define XING_FLAG_FRAMES
Definition mp3dec.c:42
static void mp3_parse_itunes_smpb(AVFormatContext *s, AVStream *st, const MPADecodeHeader2 *c, uint32_t spf)
Parse the gapless playback information Apple encoders store in an iTunSMPB comment instead of in the ...
Definition mp3dec.c:398
static int64_t mp3_sync(AVFormatContext *s, int64_t target_pos, int flags)
Definition mp3dec.c:647
static void mp3_parse_vbri_tag(AVFormatContext *s, AVStream *st, int64_t base)
Definition mp3dec.c:350
#define MIDDLE_BITS(k, m, n)
#define SEEK_WINDOW
Definition mp3dec.c:615
#define XING_TOC_COUNT
Definition mp3dec.c:47
static void read_xing_toc(AVFormatContext *s, int64_t filesize, int64_t duration)
Definition mp3dec.c:139
static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition mp3dec.c:591
static int mp3_parse_info_tag(AVFormatContext *s, AVStream *st, MPADecodeHeader2 *c, uint32_t spf)
Definition mp3dec.c:195
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.
Definition mp3dec.c:438
#define XING_FLAG_SIZE
Definition mp3dec.c:43
static int mp3_read_probe(const AVProbeData *p)
Definition mp3dec.c:72
#define XING_FLAG_TOC
Definition mp3dec.c:44
static const AVDictionaryEntry * find_itunes_smpb(const AVDictionary *metadata)
Look the iTunSMPB tag up under every key it can land on.
Definition mp3dec.c:378
static const uint8_t xing_offtbl[2][2]
Definition mp3enc.c:144
mpeg audio declarations for both encoder and decoder.
#define MP3_DECODER_DELAY
Delay of the layer III synthesis filterbank, in samples.
Definition mpegaudio.h:46
#define MPA_MAX_CODED_FRAME_SIZE
Definition mpegaudio.h:40
int avpriv_mpegaudio_decode_header2(MPADecodeHeader2 **phdr, uint32_t header)
Decode an MPEG audio header into *phdr, which is allocated if it is NULL.
MPEG Audio header decoder.
static int ff_mpa_check_header(uint32_t header)
#define MP3_MASK
AVOptions.
int ff_replaygain_export(AVStream *st, AVDictionary *metadata)
Parse replaygain tags and export them as per-stream side data.
Definition replaygain.c:94
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.
Definition replaygain.c:69
static const uint8_t header[24]
Definition sdr2.c:68
unsigned int pos
Definition spdifenc.c:431
Describe the class of an AVClass context structure.
Definition log.h:76
int64_t bit_rate
The average bitrate of the encoded data (in bits per second).
Definition codec_par.h:99
enum AVMediaType codec_type
General type of the encoded data.
Definition codec_par.h:53
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition codec_par.h:57
int initial_padding
Number of padding audio samples at the start.
Definition codec_par.h:239
char * key
Definition dict.h:91
char * value
Definition dict.h:92
Format I/O context.
Definition avformat.h:1401
Bytestream IO Context.
Definition avio.h:160
int64_t pos
Definition avformat.h:623
int64_t timestamp
Timestamp in AVStream.time_base units, preferably the time from which on correctly decoded frames are...
Definition avformat.h:624
AVOption.
Definition opt.h:428
This structure stores compressed data.
Definition packet.h:587
This structure contains the data a format has to probe a file.
Definition avformat.h:473
Rational number (pair of numerator and denominator).
Definition rational.h:58
Stream structure.
Definition avformat.h:768
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition avformat.h:791
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition avformat.h:827
AVDictionary * metadata
Definition avformat.h:848
int64_t start_time
Decoding: pts of the first frame of the stream in presentation order, in stream time base.
Definition avformat.h:817
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avformat.h:807
AVDictionary * id3v2_meta
ID3v2 tag useful for MP3 demuxing.
Definition internal.h:118
int64_t data_offset
offset of the first packet
Definition internal.h:89
int64_t maxsize
max filesize, used to limit allocations
int64_t last_discard_sample
The sample after last sample that is intended to be discarded after first_discard_sample.
Definition internal.h:244
int64_t start_skip_samples
If not 0, the number of samples that should be skipped from the start of the stream (the samples are ...
Definition internal.h:229
int64_t first_discard_sample
If not 0, the first audio sample that should be discarded from the stream.
Definition internal.h:237
int nb_index_entries
Definition internal.h:198
AVIndexEntry * index_entries
Only used if the format does not support seeking natively.
Definition internal.h:196
enum AVStreamParseType need_parsing
Definition internal.h:346
int end_pad
Definition mp3dec.c:55
int64_t filesize
Definition mp3dec.c:52
unsigned frames
Definition mp3dec.c:57
unsigned frame_duration
Definition mp3dec.c:59
unsigned header_filesize
Definition mp3dec.c:58
int start_pad
Definition mp3dec.c:54
int xing_toc
Definition mp3dec.c:53
Same as MPADecodeHeader, plus the header fields that carry no decoding information.
#define av_freep(p)
#define av_log(a,...)
int size
float delta
uint8_t base
Definition vp3data.h:128
static double c[64]