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.

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