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.

552 lines
16KB

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