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.

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