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.

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