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.

520 lines
15KB

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