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.

505 lines
14KB

  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. mp3->start_pad = v>>12;
  186. mp3-> end_pad = v&4095;
  187. st->skip_samples = mp3->start_pad + 528 + 1;
  188. if (!st->start_time)
  189. st->start_time = av_rescale_q(st->skip_samples,
  190. (AVRational){1, c->sample_rate},
  191. st->time_base);
  192. av_log(s, AV_LOG_DEBUG, "pad %d %d\n", mp3->start_pad, mp3-> end_pad);
  193. }
  194. /* Misc */
  195. avio_r8(s->pb);
  196. /* MP3 gain */
  197. avio_r8(s->pb);
  198. /* Preset and surround info */
  199. avio_rb16(s->pb);
  200. /* Music length */
  201. avio_rb32(s->pb);
  202. /* Music CRC */
  203. avio_rb16(s->pb);
  204. /* Info Tag CRC */
  205. crc = ffio_get_checksum(s->pb);
  206. v = avio_rb16(s->pb);
  207. if (v == crc) {
  208. ff_replaygain_export_raw(st, r_gain, peak, a_gain, 0);
  209. av_dict_set(&st->metadata, "encoder", version, 0);
  210. }
  211. }
  212. static void mp3_parse_vbri_tag(AVFormatContext *s, AVStream *st, int64_t base)
  213. {
  214. uint32_t v;
  215. MP3DecContext *mp3 = s->priv_data;
  216. /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
  217. avio_seek(s->pb, base + 4 + 32, SEEK_SET);
  218. v = avio_rb32(s->pb);
  219. if (v == MKBETAG('V', 'B', 'R', 'I')) {
  220. /* Check tag version */
  221. if (avio_rb16(s->pb) == 1) {
  222. /* skip delay and quality */
  223. avio_skip(s->pb, 4);
  224. mp3->header_filesize = avio_rb32(s->pb);
  225. mp3->frames = avio_rb32(s->pb);
  226. }
  227. }
  228. }
  229. /**
  230. * Try to find Xing/Info/VBRI tags and compute duration from info therein
  231. */
  232. static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
  233. {
  234. uint32_t v, spf;
  235. MPADecodeHeader c;
  236. int vbrtag_size = 0;
  237. MP3DecContext *mp3 = s->priv_data;
  238. ffio_init_checksum(s->pb, ff_crcA001_update, 0);
  239. v = avio_rb32(s->pb);
  240. if(ff_mpa_check_header(v) < 0)
  241. return -1;
  242. if (avpriv_mpegaudio_decode_header(&c, v) == 0)
  243. vbrtag_size = c.frame_size;
  244. if(c.layer != 3)
  245. return -1;
  246. spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
  247. mp3->frames = 0;
  248. mp3->header_filesize = 0;
  249. mp3_parse_info_tag(s, st, &c, spf);
  250. mp3_parse_vbri_tag(s, st, base);
  251. if (!mp3->frames && !mp3->header_filesize)
  252. return -1;
  253. /* Skip the vbr tag frame */
  254. avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
  255. if (mp3->frames)
  256. st->duration = av_rescale_q(mp3->frames, (AVRational){spf, c.sample_rate},
  257. st->time_base);
  258. if (mp3->header_filesize && mp3->frames && !mp3->is_cbr)
  259. st->codec->bit_rate = av_rescale(mp3->header_filesize, 8 * c.sample_rate, mp3->frames * (int64_t)spf);
  260. return 0;
  261. }
  262. static int mp3_read_header(AVFormatContext *s)
  263. {
  264. MP3DecContext *mp3 = s->priv_data;
  265. AVStream *st;
  266. int64_t off;
  267. int ret;
  268. st = avformat_new_stream(s, NULL);
  269. if (!st)
  270. return AVERROR(ENOMEM);
  271. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  272. st->codec->codec_id = AV_CODEC_ID_MP3;
  273. st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
  274. st->start_time = 0;
  275. // lcm of all mp3 sample rates
  276. avpriv_set_pts_info(st, 64, 1, 14112000);
  277. s->pb->maxsize = -1;
  278. off = avio_tell(s->pb);
  279. if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
  280. ff_id3v1_read(s);
  281. if(s->pb->seekable)
  282. mp3->filesize = avio_size(s->pb);
  283. if (mp3_parse_vbr_tags(s, st, off) < 0)
  284. avio_seek(s->pb, off, SEEK_SET);
  285. ret = ff_replaygain_export(st, s->metadata);
  286. if (ret < 0)
  287. return ret;
  288. /* the parameters will be extracted from the compressed bitstream */
  289. return 0;
  290. }
  291. #define MP3_PACKET_SIZE 1024
  292. static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
  293. {
  294. MP3DecContext *mp3 = s->priv_data;
  295. int ret, size;
  296. int64_t pos;
  297. size= MP3_PACKET_SIZE;
  298. pos = avio_tell(s->pb);
  299. if(mp3->filesize > ID3v1_TAG_SIZE && pos < mp3->filesize)
  300. size= FFMIN(size, mp3->filesize - pos);
  301. ret= av_get_packet(s->pb, pkt, size);
  302. if (ret <= 0) {
  303. if(ret<0)
  304. return ret;
  305. return AVERROR_EOF;
  306. }
  307. pkt->flags &= ~AV_PKT_FLAG_CORRUPT;
  308. pkt->stream_index = 0;
  309. if (ret >= ID3v1_TAG_SIZE &&
  310. memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)
  311. ret -= ID3v1_TAG_SIZE;
  312. /* note: we need to modify the packet size here to handle the last
  313. packet */
  314. pkt->size = ret;
  315. return ret;
  316. }
  317. static int check(AVFormatContext *s, int64_t pos)
  318. {
  319. int64_t ret = avio_seek(s->pb, pos, SEEK_SET);
  320. unsigned header;
  321. MPADecodeHeader sd;
  322. if (ret < 0)
  323. return ret;
  324. header = avio_rb32(s->pb);
  325. if (ff_mpa_check_header(header) < 0)
  326. return -1;
  327. if (avpriv_mpegaudio_decode_header(&sd, header) == 1)
  328. return -1;
  329. return sd.frame_size;
  330. }
  331. static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
  332. int flags)
  333. {
  334. MP3DecContext *mp3 = s->priv_data;
  335. AVIndexEntry *ie, ie1;
  336. AVStream *st = s->streams[0];
  337. int64_t ret = av_index_search_timestamp(st, timestamp, flags);
  338. int i, j;
  339. int dir = (flags&AVSEEK_FLAG_BACKWARD) ? -1 : 1;
  340. int64_t best_pos;
  341. int best_score;
  342. if ( mp3->is_cbr
  343. && st->duration > 0
  344. && mp3->header_filesize > s->data_offset
  345. && mp3->frames) {
  346. int64_t filesize = avio_size(s->pb);
  347. int64_t duration;
  348. if (filesize <= s->data_offset)
  349. filesize = mp3->header_filesize;
  350. filesize -= s->data_offset;
  351. duration = av_rescale(st->duration, filesize, mp3->header_filesize - s->data_offset);
  352. ie = &ie1;
  353. timestamp = av_clip64(timestamp, 0, duration);
  354. ie->timestamp = timestamp;
  355. ie->pos = av_rescale(timestamp, filesize, duration) + s->data_offset;
  356. } else if (mp3->xing_toc) {
  357. if (ret < 0)
  358. return ret;
  359. ie = &st->index_entries[ret];
  360. } else {
  361. st->skip_samples = timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;
  362. return -1;
  363. }
  364. avio_seek(s->pb, FFMAX(ie->pos - 4096, 0), SEEK_SET);
  365. ret = avio_seek(s->pb, ie->pos, SEEK_SET);
  366. if (ret < 0)
  367. return ret;
  368. #define MIN_VALID 3
  369. best_pos = ie->pos;
  370. best_score = 999;
  371. for(i=0; i<4096; i++) {
  372. int64_t pos = ie->pos + (dir > 0 ? i - 1024 : -i);
  373. int64_t candidate = -1;
  374. int score = 999;
  375. for(j=0; j<MIN_VALID; j++) {
  376. ret = check(s, pos);
  377. if(ret < 0)
  378. break;
  379. if ((ie->pos - pos)*dir <= 0 && abs(MIN_VALID/2-j) < score) {
  380. candidate = pos;
  381. score = abs(MIN_VALID/2-j);
  382. }
  383. pos += ret;
  384. }
  385. if (best_score > score && j == MIN_VALID) {
  386. best_pos = candidate;
  387. best_score = score;
  388. if(score == 0)
  389. break;
  390. }
  391. }
  392. ret = avio_seek(s->pb, best_pos, SEEK_SET);
  393. if (ret < 0)
  394. return ret;
  395. ff_update_cur_dts(s, st, ie->timestamp);
  396. st->skip_samples = ie->timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;
  397. return 0;
  398. }
  399. static const AVOption options[] = {
  400. { "usetoc", "use table of contents", offsetof(MP3DecContext, usetoc), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
  401. { NULL },
  402. };
  403. static const AVClass demuxer_class = {
  404. .class_name = "mp3",
  405. .item_name = av_default_item_name,
  406. .option = options,
  407. .version = LIBAVUTIL_VERSION_INT,
  408. .category = AV_CLASS_CATEGORY_DEMUXER,
  409. };
  410. AVInputFormat ff_mp3_demuxer = {
  411. .name = "mp3",
  412. .long_name = NULL_IF_CONFIG_SMALL("MP2/3 (MPEG audio layer 2/3)"),
  413. .read_probe = mp3_read_probe,
  414. .read_header = mp3_read_header,
  415. .read_packet = mp3_read_packet,
  416. .read_seek = mp3_seek,
  417. .priv_data_size = sizeof(MP3DecContext),
  418. .flags = AVFMT_GENERIC_INDEX,
  419. .extensions = "mp2,mp3,m2a,mpa", /* XXX: use probe */
  420. .priv_class = &demuxer_class,
  421. };