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.

578 lines
18KB

  1. /*
  2. * MP3 muxer
  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 "avformat.h"
  22. #include "avio_internal.h"
  23. #include "id3v1.h"
  24. #include "id3v2.h"
  25. #include "rawenc.h"
  26. #include "libavutil/avstring.h"
  27. #include "libavcodec/mpegaudio.h"
  28. #include "libavcodec/mpegaudiodata.h"
  29. #include "libavcodec/mpegaudiodecheader.h"
  30. #include "libavutil/intreadwrite.h"
  31. #include "libavutil/opt.h"
  32. #include "libavutil/dict.h"
  33. #include "libavutil/avassert.h"
  34. #include "libavutil/crc.h"
  35. #include "libavutil/mathematics.h"
  36. #include "libavutil/replaygain.h"
  37. static int id3v1_set_string(AVFormatContext *s, const char *key,
  38. uint8_t *buf, int buf_size)
  39. {
  40. AVDictionaryEntry *tag;
  41. if ((tag = av_dict_get(s->metadata, key, NULL, 0)))
  42. av_strlcpy(buf, tag->value, buf_size);
  43. return !!tag;
  44. }
  45. static int id3v1_create_tag(AVFormatContext *s, uint8_t *buf)
  46. {
  47. AVDictionaryEntry *tag;
  48. int i, count = 0;
  49. memset(buf, 0, ID3v1_TAG_SIZE); /* fail safe */
  50. buf[0] = 'T';
  51. buf[1] = 'A';
  52. buf[2] = 'G';
  53. count += id3v1_set_string(s, "TIT2", buf + 3, 30); //title
  54. count += id3v1_set_string(s, "TPE1", buf + 33, 30); //author|artist
  55. count += id3v1_set_string(s, "TALB", buf + 63, 30); //album
  56. count += id3v1_set_string(s, "TDRL", buf + 93, 4); //date
  57. count += id3v1_set_string(s, "comment", buf + 97, 30);
  58. if ((tag = av_dict_get(s->metadata, "TRCK", NULL, 0))) { //track
  59. buf[125] = 0;
  60. buf[126] = atoi(tag->value);
  61. count++;
  62. }
  63. buf[127] = 0xFF; /* default to unknown genre */
  64. if ((tag = av_dict_get(s->metadata, "TCON", NULL, 0))) { //genre
  65. for(i = 0; i <= ID3v1_GENRE_MAX; i++) {
  66. if (!av_strcasecmp(tag->value, ff_id3v1_genre_str[i])) {
  67. buf[127] = i;
  68. count++;
  69. break;
  70. }
  71. }
  72. }
  73. return count;
  74. }
  75. #define XING_NUM_BAGS 400
  76. #define XING_TOC_SIZE 100
  77. // size of the XING/LAME data, starting from the Xing tag
  78. #define XING_SIZE 156
  79. typedef struct MP3Context {
  80. const AVClass *class;
  81. ID3v2EncContext id3;
  82. int id3v2_version;
  83. int write_id3v1;
  84. int write_xing;
  85. /* xing header */
  86. // a buffer containing the whole XING/LAME frame
  87. uint8_t *xing_frame;
  88. int xing_frame_size;
  89. AVCRC audio_crc; // CRC of the audio data
  90. uint32_t audio_size; // total size of the audio data
  91. // offset of the XING/LAME frame in the file
  92. int64_t xing_frame_offset;
  93. // offset of the XING/INFO tag in the frame
  94. int xing_offset;
  95. int32_t frames;
  96. int32_t size;
  97. uint32_t want;
  98. uint32_t seen;
  99. uint32_t pos;
  100. uint64_t bag[XING_NUM_BAGS];
  101. int initial_bitrate;
  102. int has_variable_bitrate;
  103. /* index of the audio stream */
  104. int audio_stream_idx;
  105. /* number of attached pictures we still need to write */
  106. int pics_to_write;
  107. /* audio packets are queued here until we get all the attached pictures */
  108. AVPacketList *queue, *queue_end;
  109. } MP3Context;
  110. static const uint8_t xing_offtbl[2][2] = {{32, 17}, {17, 9}};
  111. /*
  112. * Write an empty XING header and initialize respective data.
  113. */
  114. static void mp3_write_xing(AVFormatContext *s)
  115. {
  116. MP3Context *mp3 = s->priv_data;
  117. AVCodecParameters *par = s->streams[mp3->audio_stream_idx]->codecpar;
  118. AVDictionaryEntry *enc = av_dict_get(s->streams[mp3->audio_stream_idx]->metadata, "encoder", NULL, 0);
  119. AVIOContext *dyn_ctx;
  120. int32_t header;
  121. MPADecodeHeader mpah;
  122. int srate_idx, i, channels;
  123. int bitrate_idx;
  124. int best_bitrate_idx;
  125. int best_bitrate_error = INT_MAX;
  126. int ret;
  127. int ver = 0;
  128. int lsf, bytes_needed;
  129. if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) || !mp3->write_xing)
  130. return;
  131. for (i = 0; i < FF_ARRAY_ELEMS(avpriv_mpa_freq_tab); i++) {
  132. const uint16_t base_freq = avpriv_mpa_freq_tab[i];
  133. if (par->sample_rate == base_freq) ver = 0x3; // MPEG 1
  134. else if (par->sample_rate == base_freq / 2) ver = 0x2; // MPEG 2
  135. else if (par->sample_rate == base_freq / 4) ver = 0x0; // MPEG 2.5
  136. else continue;
  137. srate_idx = i;
  138. break;
  139. }
  140. if (i == FF_ARRAY_ELEMS(avpriv_mpa_freq_tab)) {
  141. av_log(s, AV_LOG_WARNING, "Unsupported sample rate, not writing Xing "
  142. "header.\n");
  143. return;
  144. }
  145. switch (par->channels) {
  146. case 1: channels = MPA_MONO; break;
  147. case 2: channels = MPA_STEREO; break;
  148. default: av_log(s, AV_LOG_WARNING, "Unsupported number of channels, "
  149. "not writing Xing header.\n");
  150. return;
  151. }
  152. /* dummy MPEG audio header */
  153. header = 0xff << 24; // sync
  154. header |= (0x7 << 5 | ver << 3 | 0x1 << 1 | 0x1) << 16; // sync/audio-version/layer 3/no crc*/
  155. header |= (srate_idx << 2) << 8;
  156. header |= channels << 6;
  157. lsf = !((header & (1 << 20) && header & (1 << 19)));
  158. mp3->xing_offset = xing_offtbl[ver != 3][channels == 1] + 4;
  159. bytes_needed = mp3->xing_offset + XING_SIZE;
  160. for (bitrate_idx = 1; bitrate_idx < 15; bitrate_idx++) {
  161. int bit_rate = 1000 * avpriv_mpa_bitrate_tab[lsf][3 - 1][bitrate_idx];
  162. int error = FFABS(bit_rate - par->bit_rate);
  163. if (error < best_bitrate_error){
  164. best_bitrate_error = error;
  165. best_bitrate_idx = bitrate_idx;
  166. }
  167. }
  168. for (bitrate_idx = best_bitrate_idx; bitrate_idx < 15; bitrate_idx++) {
  169. int32_t mask = bitrate_idx << (4 + 8);
  170. header |= mask;
  171. avpriv_mpegaudio_decode_header(&mpah, header);
  172. if (bytes_needed <= mpah.frame_size)
  173. break;
  174. header &= ~mask;
  175. }
  176. ret = avio_open_dyn_buf(&dyn_ctx);
  177. if (ret < 0)
  178. return;
  179. avio_wb32(dyn_ctx, header);
  180. avpriv_mpegaudio_decode_header(&mpah, header);
  181. av_assert0(mpah.frame_size >= bytes_needed);
  182. ffio_fill(dyn_ctx, 0, mp3->xing_offset - 4);
  183. ffio_wfourcc(dyn_ctx, "Xing");
  184. avio_wb32(dyn_ctx, 0x01 | 0x02 | 0x04 | 0x08); // frames / size / TOC / vbr scale
  185. mp3->size = mpah.frame_size;
  186. mp3->want = 1;
  187. avio_wb32(dyn_ctx, 0); // frames
  188. avio_wb32(dyn_ctx, 0); // size
  189. // TOC
  190. for (i = 0; i < XING_TOC_SIZE; i++)
  191. avio_w8(dyn_ctx, 255 * i / XING_TOC_SIZE);
  192. // vbr quality
  193. // we write it, because some (broken) tools always expect it to be present
  194. avio_wb32(dyn_ctx, 0);
  195. // encoder short version string
  196. if (enc) {
  197. uint8_t encoder_str[9] = { 0 };
  198. memcpy(encoder_str, enc->value, FFMIN(strlen(enc->value), sizeof(encoder_str)));
  199. avio_write(dyn_ctx, encoder_str, sizeof(encoder_str));
  200. } else
  201. ffio_fill(dyn_ctx, 0, 9);
  202. avio_w8(dyn_ctx, 0); // tag revision 0 / unknown vbr method
  203. avio_w8(dyn_ctx, 0); // unknown lowpass filter value
  204. ffio_fill(dyn_ctx, 0, 8); // empty replaygain fields
  205. avio_w8(dyn_ctx, 0); // unknown encoding flags
  206. avio_w8(dyn_ctx, 0); // unknown abr/minimal bitrate
  207. // encoder delay
  208. if (par->initial_padding >= 1 << 12 ||
  209. par->trailing_padding >= 1 << 12) {
  210. av_log(s, AV_LOG_WARNING, "Too many samples of padding.\n");
  211. avio_wb24(dyn_ctx, 0);
  212. } else {
  213. avio_wb24(dyn_ctx, par->initial_padding << 12 | par->trailing_padding);
  214. }
  215. avio_w8(dyn_ctx, 0); // misc
  216. avio_w8(dyn_ctx, 0); // mp3gain
  217. avio_wb16(dyn_ctx, 0); // preset
  218. // audio length and CRCs (will be updated later)
  219. avio_wb32(dyn_ctx, 0); // music length
  220. avio_wb16(dyn_ctx, 0); // music crc
  221. avio_wb16(dyn_ctx, 0); // tag crc
  222. ffio_fill(dyn_ctx, 0, mpah.frame_size - bytes_needed);
  223. mp3->xing_frame_size = avio_close_dyn_buf(dyn_ctx, &mp3->xing_frame);
  224. mp3->xing_frame_offset = avio_tell(s->pb);
  225. avio_write(s->pb, mp3->xing_frame, mp3->xing_frame_size);
  226. mp3->audio_size = mp3->xing_frame_size;
  227. }
  228. /*
  229. * Add a frame to XING data.
  230. * Following lame's "VbrTag.c".
  231. */
  232. static void mp3_xing_add_frame(MP3Context *mp3, AVPacket *pkt)
  233. {
  234. int i;
  235. mp3->frames++;
  236. mp3->seen++;
  237. mp3->size += pkt->size;
  238. if (mp3->want == mp3->seen) {
  239. mp3->bag[mp3->pos] = mp3->size;
  240. if (XING_NUM_BAGS == ++mp3->pos) {
  241. /* shrink table to half size by throwing away each second bag. */
  242. for (i = 1; i < XING_NUM_BAGS; i += 2)
  243. mp3->bag[i / 2] = mp3->bag[i];
  244. /* double wanted amount per bag. */
  245. mp3->want *= 2;
  246. /* adjust current position to half of table size. */
  247. mp3->pos = XING_NUM_BAGS / 2;
  248. }
  249. mp3->seen = 0;
  250. }
  251. }
  252. static int mp3_write_audio_packet(AVFormatContext *s, AVPacket *pkt)
  253. {
  254. MP3Context *mp3 = s->priv_data;
  255. if (mp3->xing_offset && pkt->size >= 4) {
  256. MPADecodeHeader c;
  257. int ret;
  258. uint32_t h;
  259. h = AV_RB32(pkt->data);
  260. ret = avpriv_mpegaudio_decode_header(&c, h);
  261. if (ret >= 0) {
  262. if (!mp3->initial_bitrate)
  263. mp3->initial_bitrate = c.bit_rate;
  264. if ((c.bit_rate == 0) || (mp3->initial_bitrate != c.bit_rate))
  265. mp3->has_variable_bitrate = 1;
  266. }
  267. mp3_xing_add_frame(mp3, pkt);
  268. if (mp3->xing_offset) {
  269. mp3->audio_size += pkt->size;
  270. mp3->audio_crc = av_crc(av_crc_get_table(AV_CRC_16_ANSI_LE),
  271. mp3->audio_crc, pkt->data, pkt->size);
  272. }
  273. }
  274. return ff_raw_write_packet(s, pkt);
  275. }
  276. static int mp3_queue_flush(AVFormatContext *s)
  277. {
  278. MP3Context *mp3 = s->priv_data;
  279. AVPacketList *pktl;
  280. int ret = 0, write = 1;
  281. ff_id3v2_finish(&mp3->id3, s->pb);
  282. mp3_write_xing(s);
  283. while ((pktl = mp3->queue)) {
  284. if (write && (ret = mp3_write_audio_packet(s, &pktl->pkt)) < 0)
  285. write = 0;
  286. av_packet_unref(&pktl->pkt);
  287. mp3->queue = pktl->next;
  288. av_freep(&pktl);
  289. }
  290. mp3->queue_end = NULL;
  291. return ret;
  292. }
  293. static void mp3_update_xing(AVFormatContext *s)
  294. {
  295. MP3Context *mp3 = s->priv_data;
  296. AVReplayGain *rg;
  297. uint16_t tag_crc;
  298. uint8_t *toc;
  299. int i, rg_size;
  300. /* replace "Xing" identification string with "Info" for CBR files. */
  301. if (!mp3->has_variable_bitrate)
  302. AV_WL32(mp3->xing_frame + mp3->xing_offset, MKTAG('I', 'n', 'f', 'o'));
  303. AV_WB32(mp3->xing_frame + mp3->xing_offset + 8, mp3->frames);
  304. AV_WB32(mp3->xing_frame + mp3->xing_offset + 12, mp3->size);
  305. toc = mp3->xing_frame + mp3->xing_offset + 16;
  306. toc[0] = 0; // first toc entry has to be zero.
  307. for (i = 1; i < XING_TOC_SIZE; ++i) {
  308. int j = i * mp3->pos / XING_TOC_SIZE;
  309. int seek_point = 256LL * mp3->bag[j] / mp3->size;
  310. toc[i] = FFMIN(seek_point, 255);
  311. }
  312. /* write replaygain */
  313. rg = (AVReplayGain*)av_stream_get_side_data(s->streams[0], AV_PKT_DATA_REPLAYGAIN,
  314. &rg_size);
  315. if (rg && rg_size >= sizeof(*rg)) {
  316. uint16_t val;
  317. AV_WB32(mp3->xing_frame + mp3->xing_offset + 131,
  318. av_rescale(rg->track_peak, 1 << 23, 100000));
  319. if (rg->track_gain != INT32_MIN) {
  320. val = FFABS(rg->track_gain / 10000) & ((1 << 9) - 1);
  321. val |= (rg->track_gain < 0) << 9;
  322. val |= 1 << 13;
  323. AV_WB16(mp3->xing_frame + mp3->xing_offset + 135, val);
  324. }
  325. if (rg->album_gain != INT32_MIN) {
  326. val = FFABS(rg->album_gain / 10000) & ((1 << 9) - 1);
  327. val |= (rg->album_gain < 0) << 9;
  328. val |= 1 << 14;
  329. AV_WB16(mp3->xing_frame + mp3->xing_offset + 137, val);
  330. }
  331. }
  332. AV_WB32(mp3->xing_frame + mp3->xing_offset + XING_SIZE - 8, mp3->audio_size);
  333. AV_WB16(mp3->xing_frame + mp3->xing_offset + XING_SIZE - 4, mp3->audio_crc);
  334. tag_crc = av_crc(av_crc_get_table(AV_CRC_16_ANSI_LE), 0, mp3->xing_frame, 190);
  335. AV_WB16(mp3->xing_frame + mp3->xing_offset + XING_SIZE - 2, tag_crc);
  336. avio_seek(s->pb, mp3->xing_frame_offset, SEEK_SET);
  337. avio_write(s->pb, mp3->xing_frame, mp3->xing_frame_size);
  338. avio_seek(s->pb, 0, SEEK_END);
  339. }
  340. static int mp3_write_trailer(struct AVFormatContext *s)
  341. {
  342. uint8_t buf[ID3v1_TAG_SIZE];
  343. MP3Context *mp3 = s->priv_data;
  344. if (mp3->pics_to_write) {
  345. av_log(s, AV_LOG_WARNING, "No packets were sent for some of the "
  346. "attached pictures.\n");
  347. mp3_queue_flush(s);
  348. }
  349. /* write the id3v1 tag */
  350. if (mp3->write_id3v1 && id3v1_create_tag(s, buf) > 0) {
  351. avio_write(s->pb, buf, ID3v1_TAG_SIZE);
  352. }
  353. if (mp3->xing_offset)
  354. mp3_update_xing(s);
  355. av_freep(&mp3->xing_frame);
  356. return 0;
  357. }
  358. static const AVOption options[] = {
  359. { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
  360. offsetof(MP3Context, id3v2_version), AV_OPT_TYPE_INT, {.i64 = 4}, 0, 4, AV_OPT_FLAG_ENCODING_PARAM},
  361. { "write_id3v1", "Enable ID3v1 writing. ID3v1 tags are written in UTF-8 which may not be supported by most software.",
  362. offsetof(MP3Context, write_id3v1), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  363. { "write_xing", "Write the Xing header containing file duration.",
  364. offsetof(MP3Context, write_xing), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  365. { NULL },
  366. };
  367. static const AVClass mp3_muxer_class = {
  368. .class_name = "MP3 muxer",
  369. .item_name = av_default_item_name,
  370. .option = options,
  371. .version = LIBAVUTIL_VERSION_INT,
  372. };
  373. static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
  374. {
  375. MP3Context *mp3 = s->priv_data;
  376. if (pkt->stream_index == mp3->audio_stream_idx) {
  377. if (mp3->pics_to_write) {
  378. /* buffer audio packets until we get all the pictures */
  379. AVPacketList *pktl = av_mallocz(sizeof(*pktl));
  380. if (!pktl)
  381. return AVERROR(ENOMEM);
  382. pktl->pkt = *pkt;
  383. pktl->pkt.buf = av_buffer_ref(pkt->buf);
  384. if (!pktl->pkt.buf) {
  385. av_freep(&pktl);
  386. return AVERROR(ENOMEM);
  387. }
  388. if (mp3->queue_end)
  389. mp3->queue_end->next = pktl;
  390. else
  391. mp3->queue = pktl;
  392. mp3->queue_end = pktl;
  393. } else
  394. return mp3_write_audio_packet(s, pkt);
  395. } else {
  396. int ret;
  397. /* warn only once for each stream */
  398. if (s->streams[pkt->stream_index]->nb_frames == 1) {
  399. av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
  400. " ignoring.\n", pkt->stream_index);
  401. }
  402. if (!mp3->pics_to_write || s->streams[pkt->stream_index]->nb_frames >= 1)
  403. return 0;
  404. if ((ret = ff_id3v2_write_apic(s, &mp3->id3, pkt)) < 0)
  405. return ret;
  406. mp3->pics_to_write--;
  407. /* flush the buffered audio packets */
  408. if (!mp3->pics_to_write &&
  409. (ret = mp3_queue_flush(s)) < 0)
  410. return ret;
  411. }
  412. return 0;
  413. }
  414. /**
  415. * Write an ID3v2 header at beginning of stream
  416. */
  417. static int mp3_write_header(struct AVFormatContext *s)
  418. {
  419. MP3Context *mp3 = s->priv_data;
  420. int ret, i;
  421. if (mp3->id3v2_version &&
  422. mp3->id3v2_version != 3 &&
  423. mp3->id3v2_version != 4) {
  424. av_log(s, AV_LOG_ERROR, "Invalid ID3v2 version requested: %d. Only "
  425. "3, 4 or 0 (disabled) are allowed.\n", mp3->id3v2_version);
  426. return AVERROR(EINVAL);
  427. }
  428. /* check the streams -- we want exactly one audio and arbitrary number of
  429. * video (attached pictures) */
  430. mp3->audio_stream_idx = -1;
  431. for (i = 0; i < s->nb_streams; i++) {
  432. AVStream *st = s->streams[i];
  433. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  434. if (mp3->audio_stream_idx >= 0 || st->codecpar->codec_id != AV_CODEC_ID_MP3) {
  435. av_log(s, AV_LOG_ERROR, "Invalid audio stream. Exactly one MP3 "
  436. "audio stream is required.\n");
  437. return AVERROR(EINVAL);
  438. }
  439. mp3->audio_stream_idx = i;
  440. } else if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO) {
  441. av_log(s, AV_LOG_ERROR, "Only audio streams and pictures are allowed in MP3.\n");
  442. return AVERROR(EINVAL);
  443. }
  444. }
  445. if (mp3->audio_stream_idx < 0) {
  446. av_log(s, AV_LOG_ERROR, "No audio stream present.\n");
  447. return AVERROR(EINVAL);
  448. }
  449. mp3->pics_to_write = s->nb_streams - 1;
  450. if (mp3->pics_to_write && !mp3->id3v2_version) {
  451. av_log(s, AV_LOG_ERROR, "Attached pictures were requested, but the "
  452. "ID3v2 header is disabled.\n");
  453. return AVERROR(EINVAL);
  454. }
  455. if (mp3->id3v2_version) {
  456. ff_id3v2_start(&mp3->id3, s->pb, mp3->id3v2_version, ID3v2_DEFAULT_MAGIC);
  457. ret = ff_id3v2_write_metadata(s, &mp3->id3);
  458. if (ret < 0)
  459. return ret;
  460. }
  461. if (!mp3->pics_to_write) {
  462. if (mp3->id3v2_version)
  463. ff_id3v2_finish(&mp3->id3, s->pb);
  464. mp3_write_xing(s);
  465. }
  466. return 0;
  467. }
  468. AVOutputFormat ff_mp3_muxer = {
  469. .name = "mp3",
  470. .long_name = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
  471. .mime_type = "audio/mpeg",
  472. .extensions = "mp3",
  473. .priv_data_size = sizeof(MP3Context),
  474. .audio_codec = AV_CODEC_ID_MP3,
  475. .video_codec = AV_CODEC_ID_PNG,
  476. .write_header = mp3_write_header,
  477. .write_packet = mp3_write_packet,
  478. .write_trailer = mp3_write_trailer,
  479. .flags = AVFMT_NOTIMESTAMPS,
  480. .priv_class = &mp3_muxer_class,
  481. };