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.

465 lines
12KB

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