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.

382 lines
11KB

  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/dict.h"
  25. #include "libavutil/mathematics.h"
  26. #include "avformat.h"
  27. #include "internal.h"
  28. #include "id3v2.h"
  29. #include "id3v1.h"
  30. #include "replaygain.h"
  31. #include "libavcodec/mpegaudiodecheader.h"
  32. #define XING_FLAG_FRAMES 0x01
  33. #define XING_FLAG_SIZE 0x02
  34. #define XING_FLAG_TOC 0x04
  35. #define XING_TOC_COUNT 100
  36. typedef struct {
  37. AVClass *class;
  38. int64_t filesize;
  39. int64_t header_filesize;
  40. int xing_toc;
  41. int start_pad;
  42. int end_pad;
  43. int usetoc;
  44. int is_cbr;
  45. } MP3DecContext;
  46. /* mp3 read */
  47. static int mp3_read_probe(AVProbeData *p)
  48. {
  49. int max_frames, first_frames = 0;
  50. int fsize, frames, sample_rate;
  51. uint32_t header;
  52. const uint8_t *buf, *buf0, *buf2, *end;
  53. AVCodecContext avctx;
  54. buf0 = p->buf;
  55. end = p->buf + p->buf_size - sizeof(uint32_t);
  56. while(buf0 < end && !*buf0)
  57. buf0++;
  58. max_frames = 0;
  59. buf = buf0;
  60. for(; buf < end; buf= buf2+1) {
  61. buf2 = buf;
  62. if(ff_mpa_check_header(AV_RB32(buf2)))
  63. continue;
  64. for(frames = 0; buf2 < end; frames++) {
  65. header = AV_RB32(buf2);
  66. fsize = avpriv_mpa_decode_header(&avctx, header, &sample_rate, &sample_rate, &sample_rate, &sample_rate);
  67. if(fsize < 0)
  68. break;
  69. buf2 += fsize;
  70. }
  71. max_frames = FFMAX(max_frames, frames);
  72. if(buf == buf0)
  73. first_frames= frames;
  74. }
  75. // keep this in sync with ac3 probe, both need to avoid
  76. // issues with MPEG-files!
  77. if (first_frames>=4) return AVPROBE_SCORE_EXTENSION + 1;
  78. else if(max_frames>200)return AVPROBE_SCORE_EXTENSION;
  79. else if(max_frames>=4) return AVPROBE_SCORE_EXTENSION / 2;
  80. else if(ff_id3v2_match(buf0, ID3v2_DEFAULT_MAGIC) && 2*ff_id3v2_tag_len(buf0) >= p->buf_size)
  81. return p->buf_size < PROBE_BUF_MAX ? AVPROBE_SCORE_EXTENSION / 4 : AVPROBE_SCORE_EXTENSION - 2;
  82. else if(max_frames>=1) return 1;
  83. else return 0;
  84. //mpegps_mp3_unrecognized_format.mpg has max_frames=3
  85. }
  86. static void read_xing_toc(AVFormatContext *s, int64_t filesize, int64_t duration)
  87. {
  88. int i;
  89. MP3DecContext *mp3 = s->priv_data;
  90. int fill_index = mp3->usetoc && duration > 0;
  91. if (!filesize &&
  92. !(filesize = avio_size(s->pb))) {
  93. av_log(s, AV_LOG_WARNING, "Cannot determine file size, skipping TOC table.\n");
  94. fill_index = 0;
  95. }
  96. for (i = 0; i < XING_TOC_COUNT; i++) {
  97. uint8_t b = avio_r8(s->pb);
  98. if (fill_index)
  99. av_add_index_entry(s->streams[0],
  100. av_rescale(b, filesize, 256),
  101. av_rescale(i, duration, XING_TOC_COUNT),
  102. 0, 0, AVINDEX_KEYFRAME);
  103. }
  104. if (fill_index)
  105. mp3->xing_toc = 1;
  106. }
  107. /**
  108. * Try to find Xing/Info/VBRI tags and compute duration from info therein
  109. */
  110. static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
  111. {
  112. MP3DecContext *mp3 = s->priv_data;
  113. uint32_t v, spf;
  114. unsigned frames = 0; /* Total number of frames in file */
  115. unsigned size = 0; /* Total number of bytes in the stream */
  116. static const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
  117. MPADecodeHeader c;
  118. int vbrtag_size = 0;
  119. int is_cbr;
  120. v = avio_rb32(s->pb);
  121. if(ff_mpa_check_header(v) < 0)
  122. return -1;
  123. if (avpriv_mpegaudio_decode_header(&c, v) == 0)
  124. vbrtag_size = c.frame_size;
  125. if(c.layer != 3)
  126. return -1;
  127. spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
  128. /* Check for Xing / Info tag */
  129. avio_skip(s->pb, xing_offtbl[c.lsf == 1][c.nb_channels == 1]);
  130. v = avio_rb32(s->pb);
  131. is_cbr = v == MKBETAG('I', 'n', 'f', 'o');
  132. if (v == MKBETAG('X', 'i', 'n', 'g') || is_cbr) {
  133. v = avio_rb32(s->pb);
  134. if(v & XING_FLAG_FRAMES)
  135. frames = avio_rb32(s->pb);
  136. if(v & XING_FLAG_SIZE)
  137. size = avio_rb32(s->pb);
  138. if (v & XING_FLAG_TOC)
  139. read_xing_toc(s, size, av_rescale_q(frames, (AVRational){spf, c.sample_rate},
  140. st->time_base));
  141. if(v & 8)
  142. avio_skip(s->pb, 4);
  143. v = avio_rb32(s->pb);
  144. if(v == MKBETAG('L', 'A', 'M', 'E') || v == MKBETAG('L', 'a', 'v', 'f')) {
  145. avio_skip(s->pb, 21-4);
  146. v= avio_rb24(s->pb);
  147. mp3->start_pad = v>>12;
  148. mp3-> end_pad = v&4095;
  149. st->skip_samples = mp3->start_pad + 528 + 1;
  150. if (!st->start_time)
  151. st->start_time = av_rescale_q(st->skip_samples,
  152. (AVRational){1, c.sample_rate},
  153. st->time_base);
  154. av_log(s, AV_LOG_DEBUG, "pad %d %d\n", mp3->start_pad, mp3-> end_pad);
  155. }
  156. }
  157. /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
  158. avio_seek(s->pb, base + 4 + 32, SEEK_SET);
  159. v = avio_rb32(s->pb);
  160. if(v == MKBETAG('V', 'B', 'R', 'I')) {
  161. /* Check tag version */
  162. if(avio_rb16(s->pb) == 1) {
  163. /* skip delay and quality */
  164. avio_skip(s->pb, 4);
  165. size = avio_rb32(s->pb);
  166. frames = avio_rb32(s->pb);
  167. }
  168. }
  169. if(!frames && !size)
  170. return -1;
  171. /* Skip the vbr tag frame */
  172. avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
  173. if(frames)
  174. st->duration = av_rescale_q(frames, (AVRational){spf, c.sample_rate},
  175. st->time_base);
  176. if (size && frames && !is_cbr)
  177. st->codec->bit_rate = av_rescale(size, 8 * c.sample_rate, frames * (int64_t)spf);
  178. mp3->is_cbr = is_cbr;
  179. mp3->header_filesize = size;
  180. return 0;
  181. }
  182. static int mp3_read_header(AVFormatContext *s)
  183. {
  184. MP3DecContext *mp3 = s->priv_data;
  185. AVStream *st;
  186. int64_t off;
  187. int ret;
  188. st = avformat_new_stream(s, NULL);
  189. if (!st)
  190. return AVERROR(ENOMEM);
  191. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  192. st->codec->codec_id = AV_CODEC_ID_MP3;
  193. st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
  194. st->start_time = 0;
  195. // lcm of all mp3 sample rates
  196. avpriv_set_pts_info(st, 64, 1, 14112000);
  197. s->pb->maxsize = -1;
  198. off = avio_tell(s->pb);
  199. if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
  200. ff_id3v1_read(s);
  201. if(s->pb->seekable)
  202. mp3->filesize = avio_size(s->pb);
  203. if (mp3_parse_vbr_tags(s, st, off) < 0)
  204. avio_seek(s->pb, off, SEEK_SET);
  205. ret = ff_replaygain_export(st, s->metadata);
  206. if (ret < 0)
  207. return ret;
  208. /* the parameters will be extracted from the compressed bitstream */
  209. return 0;
  210. }
  211. #define MP3_PACKET_SIZE 1024
  212. static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
  213. {
  214. MP3DecContext *mp3 = s->priv_data;
  215. int ret, size;
  216. int64_t pos;
  217. size= MP3_PACKET_SIZE;
  218. pos = avio_tell(s->pb);
  219. if(mp3->filesize > ID3v1_TAG_SIZE && pos < mp3->filesize)
  220. size= FFMIN(size, mp3->filesize - pos);
  221. ret= av_get_packet(s->pb, pkt, size);
  222. if (ret <= 0) {
  223. if(ret<0)
  224. return ret;
  225. return AVERROR_EOF;
  226. }
  227. pkt->flags &= ~AV_PKT_FLAG_CORRUPT;
  228. pkt->stream_index = 0;
  229. if (ret >= ID3v1_TAG_SIZE &&
  230. memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)
  231. ret -= ID3v1_TAG_SIZE;
  232. /* note: we need to modify the packet size here to handle the last
  233. packet */
  234. pkt->size = ret;
  235. return ret;
  236. }
  237. static int check(AVFormatContext *s, int64_t pos)
  238. {
  239. int64_t ret = avio_seek(s->pb, pos, SEEK_SET);
  240. unsigned header;
  241. MPADecodeHeader sd;
  242. if (ret < 0)
  243. return ret;
  244. header = avio_rb32(s->pb);
  245. if (ff_mpa_check_header(header) < 0)
  246. return -1;
  247. if (avpriv_mpegaudio_decode_header(&sd, header) == 1)
  248. return -1;
  249. return sd.frame_size;
  250. }
  251. static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
  252. int flags)
  253. {
  254. MP3DecContext *mp3 = s->priv_data;
  255. AVIndexEntry *ie, ie1;
  256. AVStream *st = s->streams[0];
  257. int64_t ret = av_index_search_timestamp(st, timestamp, flags);
  258. int i, j;
  259. int dir = (flags&AVSEEK_FLAG_BACKWARD) ? -1 : 1;
  260. if (mp3->is_cbr && st->duration > 0 && mp3->header_filesize > s->data_offset) {
  261. int64_t filesize = avio_size(s->pb);
  262. int64_t duration;
  263. if (filesize <= s->data_offset)
  264. filesize = mp3->header_filesize;
  265. filesize -= s->data_offset;
  266. duration = av_rescale(st->duration, filesize, mp3->header_filesize - s->data_offset);
  267. ie = &ie1;
  268. timestamp = av_clip64(timestamp, 0, duration);
  269. ie->timestamp = timestamp;
  270. ie->pos = av_rescale(timestamp, filesize, duration) + s->data_offset;
  271. } else if (mp3->xing_toc) {
  272. if (ret < 0)
  273. return ret;
  274. ie = &st->index_entries[ret];
  275. } else {
  276. st->skip_samples = timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;
  277. return -1;
  278. }
  279. if (dir < 0)
  280. avio_seek(s->pb, FFMAX(ie->pos - 4096, 0), SEEK_SET);
  281. ret = avio_seek(s->pb, ie->pos, SEEK_SET);
  282. if (ret < 0)
  283. return ret;
  284. #define MIN_VALID 3
  285. for(i=0; i<4096; i++) {
  286. int64_t pos = ie->pos + i*dir;
  287. for(j=0; j<MIN_VALID; j++) {
  288. ret = check(s, pos);
  289. if(ret < 0)
  290. break;
  291. pos += ret;
  292. }
  293. if(j==MIN_VALID)
  294. break;
  295. }
  296. if(j!=MIN_VALID)
  297. i=0;
  298. ret = avio_seek(s->pb, ie->pos + i*dir, SEEK_SET);
  299. if (ret < 0)
  300. return ret;
  301. ff_update_cur_dts(s, st, ie->timestamp);
  302. st->skip_samples = ie->timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;
  303. return 0;
  304. }
  305. static const AVOption options[] = {
  306. { "usetoc", "use table of contents", offsetof(MP3DecContext, usetoc), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
  307. { NULL },
  308. };
  309. static const AVClass demuxer_class = {
  310. .class_name = "mp3",
  311. .item_name = av_default_item_name,
  312. .option = options,
  313. .version = LIBAVUTIL_VERSION_INT,
  314. .category = AV_CLASS_CATEGORY_DEMUXER,
  315. };
  316. AVInputFormat ff_mp3_demuxer = {
  317. .name = "mp3",
  318. .long_name = NULL_IF_CONFIG_SMALL("MP2/3 (MPEG audio layer 2/3)"),
  319. .read_probe = mp3_read_probe,
  320. .read_header = mp3_read_header,
  321. .read_packet = mp3_read_packet,
  322. .read_seek = mp3_seek,
  323. .priv_data_size = sizeof(MP3DecContext),
  324. .flags = AVFMT_GENERIC_INDEX,
  325. .extensions = "mp2,mp3,m2a,mpa", /* XXX: use probe */
  326. .priv_class = &demuxer_class,
  327. };