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.

478 lines
13KB

  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. /* Check for Xing / Info tag */
  123. avio_skip(s->pb, xing_offtbl[c->lsf == 1][c->nb_channels == 1]);
  124. v = avio_rb32(s->pb);
  125. mp3->is_cbr = v == MKBETAG('I', 'n', 'f', 'o');
  126. if (v != MKBETAG('X', 'i', 'n', 'g') && !mp3->is_cbr)
  127. return;
  128. v = avio_rb32(s->pb);
  129. if (v & XING_FLAG_FRAMES)
  130. mp3->frames = avio_rb32(s->pb);
  131. if (v & XING_FLAG_SIZE)
  132. mp3->header_filesize = avio_rb32(s->pb);
  133. if (v & XING_FLAG_TOC)
  134. read_xing_toc(s, mp3->header_filesize, av_rescale_q(mp3->frames,
  135. (AVRational){spf, c->sample_rate},
  136. st->time_base));
  137. /* VBR quality */
  138. if(v & 8)
  139. avio_skip(s->pb, 4);
  140. /* Encoder short version string */
  141. memset(version, 0, sizeof(version));
  142. avio_read(s->pb, version, 9);
  143. /* Info Tag revision + VBR method */
  144. avio_r8(s->pb);
  145. /* Lowpass filter value */
  146. avio_r8(s->pb);
  147. /* ReplayGain peak */
  148. v = avio_rb32(s->pb);
  149. peak = av_rescale(v, 100000, 1 << 23);
  150. /* Radio ReplayGain */
  151. v = avio_rb16(s->pb);
  152. if (MIDDLE_BITS(v, 13, 15) == 1) {
  153. r_gain = MIDDLE_BITS(v, 0, 8) * 10000;
  154. if (v & (1 << 9))
  155. r_gain *= -1;
  156. }
  157. /* Audiophile ReplayGain */
  158. v = avio_rb16(s->pb);
  159. if (MIDDLE_BITS(v, 13, 15) == 2) {
  160. a_gain = MIDDLE_BITS(v, 0, 8) * 10000;
  161. if (v & (1 << 9))
  162. a_gain *= -1;
  163. }
  164. /* Encoding flags + ATH Type */
  165. avio_r8(s->pb);
  166. /* if ABR {specified bitrate} else {minimal bitrate} */
  167. avio_r8(s->pb);
  168. /* Encoder delays */
  169. v= avio_rb24(s->pb);
  170. if(AV_RB32(version) == MKBETAG('L', 'A', 'M', 'E')
  171. || AV_RB32(version) == MKBETAG('L', 'a', 'v', 'f')) {
  172. mp3->start_pad = v>>12;
  173. mp3-> end_pad = v&4095;
  174. st->skip_samples = mp3->start_pad + 528 + 1;
  175. if (!st->start_time)
  176. st->start_time = av_rescale_q(st->skip_samples,
  177. (AVRational){1, c->sample_rate},
  178. st->time_base);
  179. av_log(s, AV_LOG_DEBUG, "pad %d %d\n", mp3->start_pad, mp3-> end_pad);
  180. }
  181. /* Misc */
  182. avio_r8(s->pb);
  183. /* MP3 gain */
  184. avio_r8(s->pb);
  185. /* Preset and surround info */
  186. avio_rb16(s->pb);
  187. /* Music length */
  188. avio_rb32(s->pb);
  189. /* Music CRC */
  190. avio_rb16(s->pb);
  191. /* Info Tag CRC */
  192. crc = ffio_get_checksum(s->pb);
  193. v = avio_rb16(s->pb);
  194. if (v == crc) {
  195. ff_replaygain_export_raw(st, r_gain, peak, a_gain, 0);
  196. av_dict_set(&st->metadata, "encoder", version, 0);
  197. }
  198. }
  199. static void mp3_parse_vbri_tag(AVFormatContext *s, AVStream *st, int64_t base)
  200. {
  201. uint32_t v;
  202. MP3DecContext *mp3 = s->priv_data;
  203. /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
  204. avio_seek(s->pb, base + 4 + 32, SEEK_SET);
  205. v = avio_rb32(s->pb);
  206. if (v == MKBETAG('V', 'B', 'R', 'I')) {
  207. /* Check tag version */
  208. if (avio_rb16(s->pb) == 1) {
  209. /* skip delay and quality */
  210. avio_skip(s->pb, 4);
  211. mp3->header_filesize = avio_rb32(s->pb);
  212. mp3->frames = avio_rb32(s->pb);
  213. }
  214. }
  215. }
  216. /**
  217. * Try to find Xing/Info/VBRI tags and compute duration from info therein
  218. */
  219. static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
  220. {
  221. uint32_t v, spf;
  222. MPADecodeHeader c;
  223. int vbrtag_size = 0;
  224. MP3DecContext *mp3 = s->priv_data;
  225. ffio_init_checksum(s->pb, ff_crcA001_update, 0);
  226. v = avio_rb32(s->pb);
  227. if(ff_mpa_check_header(v) < 0)
  228. return -1;
  229. if (avpriv_mpegaudio_decode_header(&c, v) == 0)
  230. vbrtag_size = c.frame_size;
  231. if(c.layer != 3)
  232. return -1;
  233. spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
  234. mp3->frames = 0;
  235. mp3->header_filesize = 0;
  236. mp3_parse_info_tag(s, st, &c, spf);
  237. mp3_parse_vbri_tag(s, st, base);
  238. if (!mp3->frames && !mp3->header_filesize)
  239. return -1;
  240. /* Skip the vbr tag frame */
  241. avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
  242. if (mp3->frames)
  243. st->duration = av_rescale_q(mp3->frames, (AVRational){spf, c.sample_rate},
  244. st->time_base);
  245. if (mp3->header_filesize && mp3->frames && !mp3->is_cbr)
  246. st->codec->bit_rate = av_rescale(mp3->header_filesize, 8 * c.sample_rate, mp3->frames * (int64_t)spf);
  247. return 0;
  248. }
  249. static int mp3_read_header(AVFormatContext *s)
  250. {
  251. MP3DecContext *mp3 = s->priv_data;
  252. AVStream *st;
  253. int64_t off;
  254. int ret;
  255. st = avformat_new_stream(s, NULL);
  256. if (!st)
  257. return AVERROR(ENOMEM);
  258. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  259. st->codec->codec_id = AV_CODEC_ID_MP3;
  260. st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
  261. st->start_time = 0;
  262. // lcm of all mp3 sample rates
  263. avpriv_set_pts_info(st, 64, 1, 14112000);
  264. s->pb->maxsize = -1;
  265. off = avio_tell(s->pb);
  266. if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
  267. ff_id3v1_read(s);
  268. if(s->pb->seekable)
  269. mp3->filesize = avio_size(s->pb);
  270. if (mp3_parse_vbr_tags(s, st, off) < 0)
  271. avio_seek(s->pb, off, SEEK_SET);
  272. ret = ff_replaygain_export(st, s->metadata);
  273. if (ret < 0)
  274. return ret;
  275. /* the parameters will be extracted from the compressed bitstream */
  276. return 0;
  277. }
  278. #define MP3_PACKET_SIZE 1024
  279. static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
  280. {
  281. MP3DecContext *mp3 = s->priv_data;
  282. int ret, size;
  283. int64_t pos;
  284. size= MP3_PACKET_SIZE;
  285. pos = avio_tell(s->pb);
  286. if(mp3->filesize > ID3v1_TAG_SIZE && pos < mp3->filesize)
  287. size= FFMIN(size, mp3->filesize - pos);
  288. ret= av_get_packet(s->pb, pkt, size);
  289. if (ret <= 0) {
  290. if(ret<0)
  291. return ret;
  292. return AVERROR_EOF;
  293. }
  294. pkt->flags &= ~AV_PKT_FLAG_CORRUPT;
  295. pkt->stream_index = 0;
  296. if (ret >= ID3v1_TAG_SIZE &&
  297. memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)
  298. ret -= ID3v1_TAG_SIZE;
  299. /* note: we need to modify the packet size here to handle the last
  300. packet */
  301. pkt->size = ret;
  302. return ret;
  303. }
  304. static int check(AVFormatContext *s, int64_t pos)
  305. {
  306. int64_t ret = avio_seek(s->pb, pos, SEEK_SET);
  307. unsigned header;
  308. MPADecodeHeader sd;
  309. if (ret < 0)
  310. return ret;
  311. header = avio_rb32(s->pb);
  312. if (ff_mpa_check_header(header) < 0)
  313. return -1;
  314. if (avpriv_mpegaudio_decode_header(&sd, header) == 1)
  315. return -1;
  316. return sd.frame_size;
  317. }
  318. static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
  319. int flags)
  320. {
  321. MP3DecContext *mp3 = s->priv_data;
  322. AVIndexEntry *ie, ie1;
  323. AVStream *st = s->streams[0];
  324. int64_t ret = av_index_search_timestamp(st, timestamp, flags);
  325. int i, j;
  326. int dir = (flags&AVSEEK_FLAG_BACKWARD) ? -1 : 1;
  327. if (mp3->is_cbr && st->duration > 0 && mp3->header_filesize > s->data_offset) {
  328. int64_t filesize = avio_size(s->pb);
  329. int64_t duration;
  330. if (filesize <= s->data_offset)
  331. filesize = mp3->header_filesize;
  332. filesize -= s->data_offset;
  333. duration = av_rescale(st->duration, filesize, mp3->header_filesize - s->data_offset);
  334. ie = &ie1;
  335. timestamp = av_clip64(timestamp, 0, duration);
  336. ie->timestamp = timestamp;
  337. ie->pos = av_rescale(timestamp, filesize, duration) + s->data_offset;
  338. } else if (mp3->xing_toc) {
  339. if (ret < 0)
  340. return ret;
  341. ie = &st->index_entries[ret];
  342. } else {
  343. st->skip_samples = timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;
  344. return -1;
  345. }
  346. if (dir < 0)
  347. avio_seek(s->pb, FFMAX(ie->pos - 4096, 0), SEEK_SET);
  348. ret = avio_seek(s->pb, ie->pos, SEEK_SET);
  349. if (ret < 0)
  350. return ret;
  351. #define MIN_VALID 3
  352. for(i=0; i<4096; i++) {
  353. int64_t pos = ie->pos + i*dir;
  354. for(j=0; j<MIN_VALID; j++) {
  355. ret = check(s, pos);
  356. if(ret < 0)
  357. break;
  358. pos += ret;
  359. }
  360. if(j==MIN_VALID)
  361. break;
  362. }
  363. if(j!=MIN_VALID)
  364. i=0;
  365. ret = avio_seek(s->pb, ie->pos + i*dir, SEEK_SET);
  366. if (ret < 0)
  367. return ret;
  368. ff_update_cur_dts(s, st, ie->timestamp);
  369. st->skip_samples = ie->timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;
  370. return 0;
  371. }
  372. static const AVOption options[] = {
  373. { "usetoc", "use table of contents", offsetof(MP3DecContext, usetoc), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
  374. { NULL },
  375. };
  376. static const AVClass demuxer_class = {
  377. .class_name = "mp3",
  378. .item_name = av_default_item_name,
  379. .option = options,
  380. .version = LIBAVUTIL_VERSION_INT,
  381. .category = AV_CLASS_CATEGORY_DEMUXER,
  382. };
  383. AVInputFormat ff_mp3_demuxer = {
  384. .name = "mp3",
  385. .long_name = NULL_IF_CONFIG_SMALL("MP2/3 (MPEG audio layer 2/3)"),
  386. .read_probe = mp3_read_probe,
  387. .read_header = mp3_read_header,
  388. .read_packet = mp3_read_packet,
  389. .read_seek = mp3_seek,
  390. .priv_data_size = sizeof(MP3DecContext),
  391. .flags = AVFMT_GENERIC_INDEX,
  392. .extensions = "mp2,mp3,m2a,mpa", /* XXX: use probe */
  393. .priv_class = &demuxer_class,
  394. };