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.

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