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.

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