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.

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