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.

602 lines
18KB

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