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