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.

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