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.

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