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.

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