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.

369 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. av_log(s, AV_LOG_DEBUG, "pad %d %d\n", mp3->start_pad, mp3-> end_pad);
  150. }
  151. }
  152. /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
  153. avio_seek(s->pb, base + 4 + 32, SEEK_SET);
  154. v = avio_rb32(s->pb);
  155. if(v == MKBETAG('V', 'B', 'R', 'I')) {
  156. /* Check tag version */
  157. if(avio_rb16(s->pb) == 1) {
  158. /* skip delay and quality */
  159. avio_skip(s->pb, 4);
  160. size = avio_rb32(s->pb);
  161. frames = avio_rb32(s->pb);
  162. }
  163. }
  164. if(!frames && !size)
  165. return -1;
  166. /* Skip the vbr tag frame */
  167. avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
  168. if(frames)
  169. st->duration = av_rescale_q(frames, (AVRational){spf, c.sample_rate},
  170. st->time_base);
  171. if (size && frames && !is_cbr)
  172. st->codec->bit_rate = av_rescale(size, 8 * c.sample_rate, frames * (int64_t)spf);
  173. mp3->is_cbr = is_cbr;
  174. mp3->header_filesize = size;
  175. return 0;
  176. }
  177. static int mp3_read_header(AVFormatContext *s)
  178. {
  179. MP3DecContext *mp3 = s->priv_data;
  180. AVStream *st;
  181. int64_t off;
  182. st = avformat_new_stream(s, NULL);
  183. if (!st)
  184. return AVERROR(ENOMEM);
  185. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  186. st->codec->codec_id = AV_CODEC_ID_MP3;
  187. st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
  188. st->start_time = 0;
  189. // lcm of all mp3 sample rates
  190. avpriv_set_pts_info(st, 64, 1, 14112000);
  191. s->pb->maxsize = -1;
  192. off = avio_tell(s->pb);
  193. if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
  194. ff_id3v1_read(s);
  195. if(s->pb->seekable)
  196. mp3->filesize = avio_size(s->pb);
  197. if (mp3_parse_vbr_tags(s, st, off) < 0)
  198. avio_seek(s->pb, off, SEEK_SET);
  199. /* the parameters will be extracted from the compressed bitstream */
  200. return 0;
  201. }
  202. #define MP3_PACKET_SIZE 1024
  203. static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
  204. {
  205. MP3DecContext *mp3 = s->priv_data;
  206. int ret, size;
  207. int64_t pos;
  208. size= MP3_PACKET_SIZE;
  209. pos = avio_tell(s->pb);
  210. if(mp3->filesize > ID3v1_TAG_SIZE && pos < mp3->filesize)
  211. size= FFMIN(size, mp3->filesize - pos);
  212. ret= av_get_packet(s->pb, pkt, size);
  213. if (ret <= 0) {
  214. if(ret<0)
  215. return ret;
  216. return AVERROR_EOF;
  217. }
  218. pkt->flags &= ~AV_PKT_FLAG_CORRUPT;
  219. pkt->stream_index = 0;
  220. if (ret >= ID3v1_TAG_SIZE &&
  221. memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)
  222. ret -= ID3v1_TAG_SIZE;
  223. /* note: we need to modify the packet size here to handle the last
  224. packet */
  225. pkt->size = ret;
  226. return ret;
  227. }
  228. static int check(AVFormatContext *s, int64_t pos)
  229. {
  230. int64_t ret = avio_seek(s->pb, pos, SEEK_SET);
  231. unsigned header;
  232. MPADecodeHeader sd;
  233. if (ret < 0)
  234. return ret;
  235. header = avio_rb32(s->pb);
  236. if (ff_mpa_check_header(header) < 0)
  237. return -1;
  238. if (avpriv_mpegaudio_decode_header(&sd, header) == 1)
  239. return -1;
  240. return sd.frame_size;
  241. }
  242. static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
  243. int flags)
  244. {
  245. MP3DecContext *mp3 = s->priv_data;
  246. AVIndexEntry *ie, ie1;
  247. AVStream *st = s->streams[0];
  248. int64_t ret = av_index_search_timestamp(st, timestamp, flags);
  249. int i, j;
  250. int dir = (flags&AVSEEK_FLAG_BACKWARD) ? -1 : 1;
  251. if (mp3->is_cbr && st->duration > 0 && mp3->header_filesize > s->data_offset) {
  252. int64_t filesize = avio_size(s->pb);
  253. int64_t duration;
  254. if (filesize <= s->data_offset)
  255. filesize = mp3->header_filesize;
  256. filesize -= s->data_offset;
  257. duration = av_rescale(st->duration, filesize, mp3->header_filesize - s->data_offset);
  258. ie = &ie1;
  259. timestamp = av_clip64(timestamp, 0, duration);
  260. ie->timestamp = timestamp;
  261. ie->pos = av_rescale(timestamp, filesize, duration) + s->data_offset;
  262. } else if (mp3->xing_toc) {
  263. if (ret < 0)
  264. return ret;
  265. ie = &st->index_entries[ret];
  266. } else {
  267. st->skip_samples = timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;
  268. return -1;
  269. }
  270. ret = avio_seek(s->pb, ie->pos, SEEK_SET);
  271. if (ret < 0)
  272. return ret;
  273. #define MIN_VALID 3
  274. for(i=0; i<4096; i++) {
  275. int64_t pos = ie->pos + i*dir;
  276. for(j=0; j<MIN_VALID; j++) {
  277. ret = check(s, pos);
  278. if(ret < 0)
  279. break;
  280. pos += ret;
  281. }
  282. if(j==MIN_VALID)
  283. break;
  284. }
  285. if(j!=MIN_VALID)
  286. i=0;
  287. ret = avio_seek(s->pb, ie->pos + i*dir, SEEK_SET);
  288. if (ret < 0)
  289. return ret;
  290. ff_update_cur_dts(s, st, ie->timestamp);
  291. st->skip_samples = ie->timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;
  292. return 0;
  293. }
  294. static const AVOption options[] = {
  295. { "usetoc", "use table of contents", offsetof(MP3DecContext, usetoc), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
  296. { NULL },
  297. };
  298. static const AVClass demuxer_class = {
  299. .class_name = "mp3",
  300. .item_name = av_default_item_name,
  301. .option = options,
  302. .version = LIBAVUTIL_VERSION_INT,
  303. .category = AV_CLASS_CATEGORY_DEMUXER,
  304. };
  305. AVInputFormat ff_mp3_demuxer = {
  306. .name = "mp3",
  307. .long_name = NULL_IF_CONFIG_SMALL("MP2/3 (MPEG audio layer 2/3)"),
  308. .read_probe = mp3_read_probe,
  309. .read_header = mp3_read_header,
  310. .read_packet = mp3_read_packet,
  311. .read_seek = mp3_seek,
  312. .priv_data_size = sizeof(MP3DecContext),
  313. .flags = AVFMT_GENERIC_INDEX,
  314. .extensions = "mp2,mp3,m2a,mpa", /* XXX: use probe */
  315. .priv_class = &demuxer_class,
  316. };