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.

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