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.

349 lines
10.0KB

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