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.

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