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.

467 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, delays;
  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. static 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. delays = avio_rb24(s->pb);
  179. st->codecpar->initial_padding = delays >> 12;
  180. st->codecpar->trailing_padding = delays & ((1 << 12) - 1);
  181. /* Misc */
  182. avio_r8(s->pb);
  183. /* MP3 gain */
  184. avio_r8(s->pb);
  185. /* Preset and surround info */
  186. avio_rb16(s->pb);
  187. /* Music length */
  188. avio_rb32(s->pb);
  189. /* Music CRC */
  190. avio_rb16(s->pb);
  191. /* Info Tag CRC */
  192. crc = ffio_get_checksum(s->pb);
  193. v = avio_rb16(s->pb);
  194. if (v == crc) {
  195. ff_replaygain_export_raw(st, r_gain, peak, a_gain, 0);
  196. av_dict_set(&st->metadata, "encoder", version, 0);
  197. }
  198. }
  199. static void mp3_parse_vbri_tag(AVFormatContext *s, AVStream *st, int64_t base)
  200. {
  201. uint32_t v;
  202. MP3DecContext *mp3 = s->priv_data;
  203. /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
  204. avio_seek(s->pb, base + 4 + 32, SEEK_SET);
  205. v = avio_rb32(s->pb);
  206. if (v == MKBETAG('V', 'B', 'R', 'I')) {
  207. /* Check tag version */
  208. if (avio_rb16(s->pb) == 1) {
  209. /* skip delay and quality */
  210. avio_skip(s->pb, 4);
  211. mp3->size = avio_rb32(s->pb);
  212. mp3->frames = avio_rb32(s->pb);
  213. }
  214. }
  215. }
  216. /**
  217. * Try to find Xing/Info/VBRI tags and compute duration from info therein
  218. */
  219. static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
  220. {
  221. uint32_t v, spf;
  222. MPADecodeHeader c;
  223. int vbrtag_size = 0;
  224. MP3DecContext *mp3 = s->priv_data;
  225. int ret;
  226. ffio_init_checksum(s->pb, ff_crcA001_update, 0);
  227. v = avio_rb32(s->pb);
  228. ret = avpriv_mpegaudio_decode_header(&c, v);
  229. if (ret < 0)
  230. return ret;
  231. else if (ret == 0)
  232. vbrtag_size = c.frame_size;
  233. if(c.layer != 3)
  234. return -1;
  235. spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
  236. mp3->frames = 0;
  237. mp3->size = 0;
  238. mp3_parse_info_tag(s, st, &c, spf);
  239. mp3_parse_vbri_tag(s, st, base);
  240. if (!mp3->frames && !mp3->size)
  241. return -1;
  242. /* Skip the vbr tag frame */
  243. avio_seek(s->pb, base + vbrtag_size, SEEK_SET);
  244. if (mp3->frames)
  245. st->duration = av_rescale_q(mp3->frames, (AVRational){spf, c.sample_rate},
  246. st->time_base);
  247. if (mp3->size && mp3->frames && !mp3->is_cbr)
  248. st->codecpar->bit_rate = av_rescale(mp3->size, 8 * c.sample_rate, mp3->frames * (int64_t)spf);
  249. return 0;
  250. }
  251. static int mp3_read_header(AVFormatContext *s)
  252. {
  253. AVStream *st;
  254. int64_t off;
  255. int ret;
  256. st = avformat_new_stream(s, NULL);
  257. if (!st)
  258. return AVERROR(ENOMEM);
  259. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  260. st->codecpar->codec_id = AV_CODEC_ID_MP3;
  261. st->need_parsing = AVSTREAM_PARSE_FULL;
  262. st->start_time = 0;
  263. // lcm of all mp3 sample rates
  264. avpriv_set_pts_info(st, 64, 1, 14112000);
  265. off = avio_tell(s->pb);
  266. if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))
  267. ff_id3v1_read(s);
  268. if (mp3_parse_vbr_tags(s, st, off) < 0)
  269. avio_seek(s->pb, off, SEEK_SET);
  270. ret = ff_replaygain_export(st, s->metadata);
  271. if (ret < 0)
  272. return ret;
  273. /* the parameters will be extracted from the compressed bitstream */
  274. return 0;
  275. }
  276. #define MP3_PACKET_SIZE 1024
  277. static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
  278. {
  279. int ret;
  280. ret = av_get_packet(s->pb, pkt, MP3_PACKET_SIZE);
  281. if (ret < 0)
  282. return ret;
  283. pkt->stream_index = 0;
  284. if (ret > ID3v1_TAG_SIZE &&
  285. memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)
  286. ret -= ID3v1_TAG_SIZE;
  287. /* note: we need to modify the packet size here to handle the last
  288. packet */
  289. pkt->size = ret;
  290. return ret;
  291. }
  292. #define SEEK_PACKETS 4
  293. #define SEEK_WINDOW (SEEK_PACKETS * MP3_PACKET_SIZE)
  294. /* The toc entry can position to the wrong byte offset, try to pick
  295. * the closest frame by probing the data in a window of 4 packets.
  296. */
  297. static int check(AVIOContext *pb, int64_t pos, int64_t *out_pos)
  298. {
  299. MPADecodeHeader mh = { 0 };
  300. int i;
  301. uint32_t header;
  302. int64_t off = 0;
  303. for (i = 0; i < SEEK_PACKETS; i++) {
  304. off = avio_seek(pb, pos + mh.frame_size, SEEK_SET);
  305. if (off < 0)
  306. break;
  307. header = avio_rb32(pb);
  308. if (avpriv_mpegaudio_decode_header(&mh, header))
  309. break;
  310. out_pos[i] = off;
  311. }
  312. return i;
  313. }
  314. static int reposition(AVFormatContext *s, int64_t pos)
  315. {
  316. int ret, best_valid = -1;
  317. int64_t p, best_pos = -1;
  318. for (p = FFMAX(pos - SEEK_WINDOW / 2, 0); p < pos + SEEK_WINDOW / 2; p++) {
  319. int64_t out_pos[SEEK_PACKETS];
  320. ret = check(s->pb, p, out_pos);
  321. if (best_valid < ret) {
  322. int i;
  323. for (i = 0; i < ret; i++) {
  324. if (llabs(best_pos - pos) > llabs(out_pos[i] - pos)) {
  325. best_pos = out_pos[i];
  326. best_valid = ret;
  327. }
  328. }
  329. if (best_pos == pos && best_valid == SEEK_PACKETS)
  330. break;
  331. }
  332. }
  333. if (best_valid <= 0)
  334. return AVERROR(ENOSYS);
  335. p = avio_seek(s->pb, best_pos, SEEK_SET);
  336. if (p < 0)
  337. return p;
  338. return 0;
  339. }
  340. static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,
  341. int flags)
  342. {
  343. MP3DecContext *mp3 = s->priv_data;
  344. AVIndexEntry *ie;
  345. AVStream *st = s->streams[0];
  346. int64_t ret = av_index_search_timestamp(st, timestamp, flags);
  347. if (!mp3->xing_toc)
  348. return AVERROR(ENOSYS);
  349. if (ret < 0)
  350. return ret;
  351. ie = &st->index_entries[ret];
  352. ret = reposition(s, ie->pos);
  353. if (ret < 0)
  354. return ret;
  355. ff_update_cur_dts(s, st, ie->timestamp);
  356. return 0;
  357. }
  358. AVInputFormat ff_mp3_demuxer = {
  359. .name = "mp3",
  360. .long_name = NULL_IF_CONFIG_SMALL("MP2/3 (MPEG audio layer 2/3)"),
  361. .read_probe = mp3_read_probe,
  362. .read_header = mp3_read_header,
  363. .read_packet = mp3_read_packet,
  364. .read_seek = mp3_seek,
  365. .priv_data_size = sizeof(MP3DecContext),
  366. .flags = AVFMT_GENERIC_INDEX,
  367. .extensions = "mp2,mp3,m2a,mpa", /* XXX: use probe */
  368. };