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.

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