You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

572 lines
17KB

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