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.

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