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.

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