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.

412 lines
11KB

  1. /*
  2. * MP3 demuxer
  3. * Copyright (c) 2003 Fabrice Bellard
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/avstring.h"
  22. #include "libavutil/intreadwrite.h"
  23. #include "libavutil/crc.h"
  24. #include "libavutil/dict.h"
  25. #include "libavutil/mathematics.h"
  26. #include "avformat.h"
  27. #include "internal.h"
  28. #include "avio_internal.h"
  29. #include "id3v2.h"
  30. #include "id3v1.h"
  31. #include "replaygain.h"
  32. #include "libavcodec/avcodec.h"
  33. #include "libavcodec/mpegaudiodecheader.h"
  34. #define XING_FLAG_FRAMES 0x01
  35. #define XING_FLAG_SIZE 0x02
  36. #define XING_FLAG_TOC 0x04
  37. #define XING_FLAC_QSCALE 0x08
  38. #define XING_TOC_COUNT 100
  39. typedef struct MP3DecContext {
  40. int xing_toc;
  41. unsigned frames; /* Total number of frames in file */
  42. unsigned size; /* Total number of bytes in the stream */
  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. uint8_t *buf, *buf0, *buf2, *end;
  52. AVCodecContext *avctx = avcodec_alloc_context3(NULL);
  53. if (!avctx)
  54. return AVERROR(ENOMEM);
  55. buf0 = p->buf;
  56. end = p->buf + p->buf_size - sizeof(uint32_t);
  57. while(buf0 < end && !*buf0)
  58. buf0++;
  59. max_frames = 0;
  60. buf = buf0;
  61. for(; buf < end; buf= buf2+1) {
  62. buf2 = buf;
  63. for(frames = 0; buf2 < end; frames++) {
  64. header = AV_RB32(buf2);
  65. fsize = avpriv_mpa_decode_header(avctx, header, &sample_rate,
  66. &sample_rate, &sample_rate,
  67. &sample_rate);
  68. if(fsize < 0)
  69. break;
  70. buf2 += fsize;
  71. }
  72. max_frames = FFMAX(max_frames, frames);
  73. if(buf == buf0)
  74. first_frames= frames;
  75. }
  76. avcodec_free_context(&avctx);
  77. // keep this in sync with ac3 probe, both need to avoid
  78. // issues with MPEG-files!
  79. if (first_frames >= 10)
  80. return AVPROBE_SCORE_EXTENSION + 5;
  81. if (first_frames >= 4)
  82. return AVPROBE_SCORE_EXTENSION + 1;
  83. if (max_frames) {
  84. int pes = 0, i;
  85. unsigned int code = -1;
  86. #define VIDEO_ID 0x000001e0
  87. #define AUDIO_ID 0x000001c0
  88. /* do a search for mpegps headers to be able to properly bias
  89. * towards mpegps if we detect this stream as both. */
  90. for (i = 0; i<p->buf_size; i++) {
  91. code = (code << 8) + p->buf[i];
  92. if ((code & 0xffffff00) == 0x100) {
  93. if ((code & 0x1f0) == VIDEO_ID) pes++;
  94. else if((code & 0x1e0) == AUDIO_ID) pes++;
  95. }
  96. }
  97. if (pes)
  98. max_frames = (max_frames + pes - 1) / pes;
  99. }
  100. if (max_frames > 500) return AVPROBE_SCORE_EXTENSION;
  101. else if (max_frames >= 4) return AVPROBE_SCORE_EXTENSION / 2;
  102. else if (max_frames >= 1) return 1;
  103. else return 0;
  104. //mpegps_mp3_unrecognized_format.mpg has max_frames=3
  105. }
  106. static void read_xing_toc(AVFormatContext *s, int64_t filesize, int64_t duration)
  107. {
  108. int i;
  109. MP3DecContext *mp3 = s->priv_data;
  110. if (!filesize &&
  111. !(filesize = avio_size(s->pb))) {
  112. av_log(s, AV_LOG_WARNING, "Cannot determine file size, skipping TOC table.\n");
  113. return;
  114. }
  115. for (i = 0; i < XING_TOC_COUNT; i++) {
  116. uint8_t b = avio_r8(s->pb);
  117. av_add_index_entry(s->streams[0],
  118. av_rescale(b, filesize, 256),
  119. av_rescale(i, duration, XING_TOC_COUNT),
  120. 0, 0, AVINDEX_KEYFRAME);
  121. }
  122. mp3->xing_toc = 1;
  123. }
  124. static void mp3_parse_info_tag(AVFormatContext *s, AVStream *st,
  125. MPADecodeHeader *c, uint32_t spf)
  126. {
  127. #define LAST_BITS(k, n) ((k) & ((1 << (n)) - 1))
  128. #define MIDDLE_BITS(k, m, n) LAST_BITS((k) >> (m), ((n) - (m)))
  129. uint16_t crc;
  130. uint32_t v;
  131. char version[10];
  132. uint32_t peak = 0;
  133. int32_t r_gain = INT32_MIN, a_gain = INT32_MIN;
  134. MP3DecContext *mp3 = s->priv_data;
  135. const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
  136. /* Check for Xing / Info tag */
  137. avio_skip(s->pb, xing_offtbl[c->lsf == 1][c->nb_channels == 1]);
  138. v = avio_rb32(s->pb);
  139. mp3->is_cbr = v == MKBETAG('I', 'n', 'f', 'o');
  140. if (v != MKBETAG('X', 'i', 'n', 'g') && !mp3->is_cbr)
  141. return;
  142. v = avio_rb32(s->pb);
  143. if (v & XING_FLAG_FRAMES)
  144. mp3->frames = avio_rb32(s->pb);
  145. if (v & XING_FLAG_SIZE)
  146. mp3->size = avio_rb32(s->pb);
  147. if (v & XING_FLAG_TOC && mp3->frames)
  148. read_xing_toc(s, mp3->size, av_rescale_q(mp3->frames,
  149. (AVRational){spf, c->sample_rate},
  150. st->time_base));
  151. /* VBR quality */
  152. if (v & XING_FLAC_QSCALE)
  153. avio_rb32(s->pb);
  154. /* Encoder short version string */
  155. memset(version, 0, sizeof(version));
  156. avio_read(s->pb, version, 9);
  157. /* Info Tag revision + VBR method */
  158. avio_r8(s->pb);
  159. /* Lowpass filter value */
  160. avio_r8(s->pb);
  161. /* ReplayGain peak */
  162. v = avio_rb32(s->pb);
  163. peak = av_rescale(v, 100000, 1 << 23);
  164. /* Radio ReplayGain */
  165. v = avio_rb16(s->pb);
  166. if (MIDDLE_BITS(v, 13, 15) == 1) {
  167. r_gain = MIDDLE_BITS(v, 0, 8) * 10000;
  168. if (v & (1 << 9))
  169. r_gain *= -1;
  170. }
  171. /* Audiophile ReplayGain */
  172. v = avio_rb16(s->pb);
  173. if (MIDDLE_BITS(v, 13, 15) == 2) {
  174. a_gain = MIDDLE_BITS(v, 0, 8) * 10000;
  175. if (v & (1 << 9))
  176. a_gain *= -1;
  177. }
  178. /* Encoding flags + ATH Type */
  179. avio_r8(s->pb);
  180. /* if ABR {specified bitrate} else {minimal bitrate} */
  181. avio_r8(s->pb);
  182. /* Encoder delays */
  183. avio_rb24(s->pb);
  184. /* Misc */
  185. avio_r8(s->pb);
  186. /* MP3 gain */
  187. avio_r8(s->pb);
  188. /* Preset and surround info */
  189. avio_rb16(s->pb);
  190. /* Music length */
  191. avio_rb32(s->pb);
  192. /* Music CRC */
  193. avio_rb16(s->pb);
  194. /* Info Tag CRC */
  195. crc = ffio_get_checksum(s->pb);
  196. v = avio_rb16(s->pb);
  197. if (v == crc) {
  198. ff_replaygain_export_raw(st, r_gain, peak, a_gain, 0);
  199. av_dict_set(&st->metadata, "encoder", version, 0);
  200. }
  201. }
  202. static void mp3_parse_vbri_tag(AVFormatContext *s, AVStream *st, int64_t base)
  203. {
  204. uint32_t v;
  205. MP3DecContext *mp3 = s->priv_data;
  206. /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
  207. avio_seek(s->pb, base + 4 + 32, SEEK_SET);
  208. v = avio_rb32(s->pb);
  209. if (v == MKBETAG('V', 'B', 'R', 'I')) {
  210. /* Check tag version */
  211. if (avio_rb16(s->pb) == 1) {
  212. /* skip delay and quality */
  213. avio_skip(s->pb, 4);
  214. mp3->size = avio_rb32(s->pb);
  215. mp3->frames = avio_rb32(s->pb);
  216. }
  217. }
  218. }
  219. /**
  220. * Try to find Xing/Info/VBRI tags and compute duration from info therein
  221. */
  222. static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
  223. {
  224. uint32_t v, spf;
  225. MPADecodeHeader c;
  226. int vbrtag_size = 0;
  227. MP3DecContext *mp3 = s->priv_data;
  228. ffio_init_checksum(s->pb, ff_crcA001_update, 0);
  229. v = avio_rb32(s->pb);
  230. if(ff_mpa_check_header(v) < 0)
  231. return -1;
  232. if (avpriv_mpegaudio_decode_header(&c, v) == 0)
  233. vbrtag_size = c.frame_size;
  234. if(c.layer != 3)
  235. return -1;
  236. spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
  237. mp3->frames = 0;
  238. mp3->size = 0;
  239. mp3_parse_info_tag(s, st, &c, spf);
  240. mp3_parse_vbri_tag(s, st, base);
  241. if (!mp3->frames && !mp3->size)
  242. return -1;
  243. /* Skip the vbr tag frame */
  244. avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
  245. if (mp3->frames)
  246. st->duration = av_rescale_q(mp3->frames, (AVRational){spf, c.sample_rate},
  247. st->time_base);
  248. if (mp3->size && mp3->frames && !mp3->is_cbr)
  249. st->codec->bit_rate = av_rescale(mp3->size, 8 * c.sample_rate, mp3->frames * (int64_t)spf);
  250. return 0;
  251. }
  252. static int mp3_read_header(AVFormatContext *s)
  253. {
  254. AVStream *st;
  255. int64_t off;
  256. int ret;
  257. st = avformat_new_stream(s, NULL);
  258. if (!st)
  259. return AVERROR(ENOMEM);
  260. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  261. st->codec->codec_id = AV_CODEC_ID_MP3;
  262. st->need_parsing = AVSTREAM_PARSE_FULL;
  263. st->start_time = 0;
  264. // lcm of all mp3 sample rates
  265. avpriv_set_pts_info(st, 64, 1, 14112000);
  266. off = avio_tell(s->pb);
  267. if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
  268. ff_id3v1_read(s);
  269. if (mp3_parse_vbr_tags(s, st, off) < 0)
  270. avio_seek(s->pb, off, SEEK_SET);
  271. ret = ff_replaygain_export(st, s->metadata);
  272. if (ret < 0)
  273. return ret;
  274. /* the parameters will be extracted from the compressed bitstream */
  275. return 0;
  276. }
  277. #define MP3_PACKET_SIZE 1024
  278. static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
  279. {
  280. int ret;
  281. ret = av_get_packet(s->pb, pkt, MP3_PACKET_SIZE);
  282. if (ret < 0)
  283. return ret;
  284. pkt->stream_index = 0;
  285. if (ret > ID3v1_TAG_SIZE &&
  286. memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)
  287. ret -= ID3v1_TAG_SIZE;
  288. /* note: we need to modify the packet size here to handle the last
  289. packet */
  290. pkt->size = ret;
  291. return ret;
  292. }
  293. static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
  294. int flags)
  295. {
  296. MP3DecContext *mp3 = s->priv_data;
  297. AVIndexEntry *ie;
  298. AVStream *st = s->streams[0];
  299. int64_t ret = av_index_search_timestamp(st, timestamp, flags);
  300. uint32_t header = 0;
  301. if (!mp3->xing_toc)
  302. return AVERROR(ENOSYS);
  303. if (ret < 0)
  304. return ret;
  305. ie = &st->index_entries[ret];
  306. ret = avio_seek(s->pb, ie->pos, SEEK_SET);
  307. if (ret < 0)
  308. return ret;
  309. while (!s->pb->eof_reached) {
  310. header = (header << 8) + avio_r8(s->pb);
  311. if (ff_mpa_check_header(header) >= 0) {
  312. ff_update_cur_dts(s, st, ie->timestamp);
  313. ret = avio_seek(s->pb, -4, SEEK_CUR);
  314. return (ret >= 0) ? 0 : ret;
  315. }
  316. }
  317. return AVERROR_EOF;
  318. }
  319. AVInputFormat ff_mp3_demuxer = {
  320. .name = "mp3",
  321. .long_name = NULL_IF_CONFIG_SMALL("MP2/3 (MPEG audio layer 2/3)"),
  322. .read_probe = mp3_read_probe,
  323. .read_header = mp3_read_header,
  324. .read_packet = mp3_read_packet,
  325. .read_seek = mp3_seek,
  326. .priv_data_size = sizeof(MP3DecContext),
  327. .flags = AVFMT_GENERIC_INDEX,
  328. .extensions = "mp2,mp3,m2a,mpa", /* XXX: use probe */
  329. };