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.

528 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 && 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. /* Check for Xing / Info tag */
  131. avio_skip(s->pb, xing_offtbl[c->lsf == 1][c->nb_channels == 1]);
  132. v = avio_rb32(s->pb);
  133. mp3->is_cbr = v == MKBETAG('I', 'n', 'f', 'o');
  134. if (v != MKBETAG('X', 'i', 'n', 'g') && !mp3->is_cbr)
  135. return;
  136. v = avio_rb32(s->pb);
  137. if (v & XING_FLAG_FRAMES)
  138. mp3->frames = avio_rb32(s->pb);
  139. if (v & XING_FLAG_SIZE)
  140. mp3->header_filesize = avio_rb32(s->pb);
  141. if (fsize && mp3->header_filesize) {
  142. uint64_t min, delta;
  143. min = FFMIN(fsize, mp3->header_filesize);
  144. delta = FFMAX(fsize, mp3->header_filesize) - min;
  145. if (fsize > mp3->header_filesize && delta > min >> 4) {
  146. mp3->frames = 0;
  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->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->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. ffio_init_checksum(s->pb, ff_crcA001_update, 0);
  251. v = avio_rb32(s->pb);
  252. if(ff_mpa_check_header(v) < 0)
  253. return -1;
  254. if (avpriv_mpegaudio_decode_header(&c, v) == 0)
  255. vbrtag_size = c.frame_size;
  256. if(c.layer != 3)
  257. return -1;
  258. spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
  259. mp3->frames = 0;
  260. mp3->header_filesize = 0;
  261. mp3_parse_info_tag(s, st, &c, spf);
  262. mp3_parse_vbri_tag(s, st, base);
  263. if (!mp3->frames && !mp3->header_filesize)
  264. return -1;
  265. /* Skip the vbr tag frame */
  266. avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
  267. if (mp3->frames)
  268. st->duration = av_rescale_q(mp3->frames, (AVRational){spf, c.sample_rate},
  269. st->time_base);
  270. if (mp3->header_filesize && mp3->frames && !mp3->is_cbr)
  271. st->codec->bit_rate = av_rescale(mp3->header_filesize, 8 * c.sample_rate, mp3->frames * (int64_t)spf);
  272. return 0;
  273. }
  274. static int mp3_read_header(AVFormatContext *s)
  275. {
  276. MP3DecContext *mp3 = s->priv_data;
  277. AVStream *st;
  278. int64_t off;
  279. int ret;
  280. int i;
  281. st = avformat_new_stream(s, NULL);
  282. if (!st)
  283. return AVERROR(ENOMEM);
  284. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  285. st->codec->codec_id = AV_CODEC_ID_MP3;
  286. st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
  287. st->start_time = 0;
  288. // lcm of all mp3 sample rates
  289. avpriv_set_pts_info(st, 64, 1, 14112000);
  290. s->pb->maxsize = -1;
  291. off = avio_tell(s->pb);
  292. if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
  293. ff_id3v1_read(s);
  294. if(s->pb->seekable)
  295. mp3->filesize = avio_size(s->pb);
  296. if (mp3_parse_vbr_tags(s, st, off) < 0)
  297. avio_seek(s->pb, off, SEEK_SET);
  298. ret = ff_replaygain_export(st, s->metadata);
  299. if (ret < 0)
  300. return ret;
  301. // the seek index is relative to the end of the xing vbr headers
  302. for (i = 0; i < st->nb_index_entries; i++)
  303. st->index_entries[i].pos += avio_tell(s->pb);
  304. /* the parameters will be extracted from the compressed bitstream */
  305. return 0;
  306. }
  307. #define MP3_PACKET_SIZE 1024
  308. static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
  309. {
  310. MP3DecContext *mp3 = s->priv_data;
  311. int ret, size;
  312. int64_t pos;
  313. size= MP3_PACKET_SIZE;
  314. pos = avio_tell(s->pb);
  315. if(mp3->filesize > ID3v1_TAG_SIZE && pos < mp3->filesize)
  316. size= FFMIN(size, mp3->filesize - pos);
  317. ret= av_get_packet(s->pb, pkt, size);
  318. if (ret <= 0) {
  319. if(ret<0)
  320. return ret;
  321. return AVERROR_EOF;
  322. }
  323. pkt->flags &= ~AV_PKT_FLAG_CORRUPT;
  324. pkt->stream_index = 0;
  325. if (ret >= ID3v1_TAG_SIZE &&
  326. memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)
  327. ret -= ID3v1_TAG_SIZE;
  328. /* note: we need to modify the packet size here to handle the last
  329. packet */
  330. pkt->size = ret;
  331. return ret;
  332. }
  333. static int check(AVFormatContext *s, int64_t pos)
  334. {
  335. int64_t ret = avio_seek(s->pb, pos, SEEK_SET);
  336. unsigned header;
  337. MPADecodeHeader sd;
  338. if (ret < 0)
  339. return ret;
  340. header = avio_rb32(s->pb);
  341. if (ff_mpa_check_header(header) < 0)
  342. return -1;
  343. if (avpriv_mpegaudio_decode_header(&sd, header) == 1)
  344. return -1;
  345. return sd.frame_size;
  346. }
  347. static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
  348. int flags)
  349. {
  350. MP3DecContext *mp3 = s->priv_data;
  351. AVIndexEntry *ie, ie1;
  352. AVStream *st = s->streams[0];
  353. int64_t ret = av_index_search_timestamp(st, timestamp, flags);
  354. int i, j;
  355. int dir = (flags&AVSEEK_FLAG_BACKWARD) ? -1 : 1;
  356. int64_t best_pos;
  357. int best_score;
  358. if ( mp3->is_cbr
  359. && (mp3->usetoc <= 0 || !mp3->xing_toc)
  360. && st->duration > 0
  361. && mp3->header_filesize > s->internal->data_offset
  362. && mp3->frames) {
  363. ie = &ie1;
  364. timestamp = av_clip64(timestamp, 0, st->duration);
  365. ie->timestamp = timestamp;
  366. ie->pos = av_rescale(timestamp, mp3->header_filesize, st->duration) + s->internal->data_offset;
  367. } else if (mp3->xing_toc) {
  368. if (ret < 0)
  369. return ret;
  370. ie = &st->index_entries[ret];
  371. } else {
  372. st->skip_samples = timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;
  373. return -1;
  374. }
  375. avio_seek(s->pb, FFMAX(ie->pos - 4096, 0), SEEK_SET);
  376. ret = avio_seek(s->pb, ie->pos, SEEK_SET);
  377. if (ret < 0)
  378. return ret;
  379. #define MIN_VALID 3
  380. best_pos = ie->pos;
  381. best_score = 999;
  382. for(i=0; i<4096; i++) {
  383. int64_t pos = ie->pos + (dir > 0 ? i - 1024 : -i);
  384. int64_t candidate = -1;
  385. int score = 999;
  386. if (pos < 0)
  387. continue;
  388. for(j=0; j<MIN_VALID; j++) {
  389. ret = check(s, pos);
  390. if(ret < 0)
  391. break;
  392. if ((ie->pos - pos)*dir <= 0 && abs(MIN_VALID/2-j) < score) {
  393. candidate = pos;
  394. score = abs(MIN_VALID/2-j);
  395. }
  396. pos += ret;
  397. }
  398. if (best_score > score && j == MIN_VALID) {
  399. best_pos = candidate;
  400. best_score = score;
  401. if(score == 0)
  402. break;
  403. }
  404. }
  405. ret = avio_seek(s->pb, best_pos, SEEK_SET);
  406. if (ret < 0)
  407. return ret;
  408. if (mp3->is_cbr && ie == &ie1) {
  409. int frame_duration = av_rescale(st->duration, 1, mp3->frames);
  410. ie1.timestamp = frame_duration * av_rescale(best_pos - s->internal->data_offset, mp3->frames, mp3->header_filesize);
  411. }
  412. ff_update_cur_dts(s, st, ie->timestamp);
  413. st->skip_samples = ie->timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;
  414. return 0;
  415. }
  416. static const AVOption options[] = {
  417. { "usetoc", "use table of contents", offsetof(MP3DecContext, usetoc), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
  418. { NULL },
  419. };
  420. static const AVClass demuxer_class = {
  421. .class_name = "mp3",
  422. .item_name = av_default_item_name,
  423. .option = options,
  424. .version = LIBAVUTIL_VERSION_INT,
  425. .category = AV_CLASS_CATEGORY_DEMUXER,
  426. };
  427. AVInputFormat ff_mp3_demuxer = {
  428. .name = "mp3",
  429. .long_name = NULL_IF_CONFIG_SMALL("MP2/3 (MPEG audio layer 2/3)"),
  430. .read_probe = mp3_read_probe,
  431. .read_header = mp3_read_header,
  432. .read_packet = mp3_read_packet,
  433. .read_seek = mp3_seek,
  434. .priv_data_size = sizeof(MP3DecContext),
  435. .flags = AVFMT_GENERIC_INDEX,
  436. .extensions = "mp2,mp3,m2a,mpa", /* XXX: use probe */
  437. .priv_class = &demuxer_class,
  438. };