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.

593 lines
19KB

  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. AVCodecContext *codec = s->streams[mp3->audio_stream_idx]->codec;
  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 || !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 (codec->sample_rate == base_freq) ver = 0x3; // MPEG 1
  134. else if (codec->sample_rate == base_freq / 2) ver = 0x2; // MPEG 2
  135. else if (codec->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 (codec->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 - codec->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 (codec->initial_padding >= 1 << 12) {
  209. av_log(s, AV_LOG_WARNING, "Too many samples of initial padding.\n");
  210. avio_wb24(dyn_ctx, 0);
  211. } else {
  212. avio_wb24(dyn_ctx, codec->initial_padding << 12);
  213. }
  214. avio_w8(dyn_ctx, 0); // misc
  215. avio_w8(dyn_ctx, 0); // mp3gain
  216. avio_wb16(dyn_ctx, 0); // preset
  217. // audio length and CRCs (will be updated later)
  218. avio_wb32(dyn_ctx, 0); // music length
  219. avio_wb16(dyn_ctx, 0); // music crc
  220. avio_wb16(dyn_ctx, 0); // tag crc
  221. ffio_fill(dyn_ctx, 0, mpah.frame_size - bytes_needed);
  222. mp3->xing_frame_size = avio_close_dyn_buf(dyn_ctx, &mp3->xing_frame);
  223. mp3->xing_frame_offset = avio_tell(s->pb);
  224. avio_write(s->pb, mp3->xing_frame, mp3->xing_frame_size);
  225. mp3->audio_size = mp3->xing_frame_size;
  226. }
  227. /*
  228. * Add a frame to XING data.
  229. * Following lame's "VbrTag.c".
  230. */
  231. static void mp3_xing_add_frame(MP3Context *mp3, AVPacket *pkt)
  232. {
  233. int i;
  234. mp3->frames++;
  235. mp3->seen++;
  236. mp3->size += pkt->size;
  237. if (mp3->want == mp3->seen) {
  238. mp3->bag[mp3->pos] = mp3->size;
  239. if (XING_NUM_BAGS == ++mp3->pos) {
  240. /* shrink table to half size by throwing away each second bag. */
  241. for (i = 1; i < XING_NUM_BAGS; i += 2)
  242. mp3->bag[i / 2] = mp3->bag[i];
  243. /* double wanted amount per bag. */
  244. mp3->want *= 2;
  245. /* adjust current position to half of table size. */
  246. mp3->pos = XING_NUM_BAGS / 2;
  247. }
  248. mp3->seen = 0;
  249. }
  250. }
  251. static int mp3_write_audio_packet(AVFormatContext *s, AVPacket *pkt)
  252. {
  253. MP3Context *mp3 = s->priv_data;
  254. if (mp3->xing_offset && pkt->size >= 4) {
  255. MPADecodeHeader c;
  256. int ret;
  257. uint32_t h;
  258. h = AV_RB32(pkt->data);
  259. ret = avpriv_mpegaudio_decode_header(&c, h);
  260. if (ret >= 0) {
  261. if (!mp3->initial_bitrate)
  262. mp3->initial_bitrate = c.bit_rate;
  263. if ((c.bit_rate == 0) || (mp3->initial_bitrate != c.bit_rate))
  264. mp3->has_variable_bitrate = 1;
  265. }
  266. mp3_xing_add_frame(mp3, pkt);
  267. if (mp3->xing_offset) {
  268. mp3->audio_size += pkt->size;
  269. mp3->audio_crc = av_crc(av_crc_get_table(AV_CRC_16_ANSI_LE),
  270. mp3->audio_crc, pkt->data, pkt->size);
  271. }
  272. }
  273. return ff_raw_write_packet(s, pkt);
  274. }
  275. static int mp3_queue_flush(AVFormatContext *s)
  276. {
  277. MP3Context *mp3 = s->priv_data;
  278. AVPacketList *pktl;
  279. int ret = 0, write = 1;
  280. ff_id3v2_finish(&mp3->id3, s->pb);
  281. mp3_write_xing(s);
  282. while ((pktl = mp3->queue)) {
  283. if (write && (ret = mp3_write_audio_packet(s, &pktl->pkt)) < 0)
  284. write = 0;
  285. av_packet_unref(&pktl->pkt);
  286. mp3->queue = pktl->next;
  287. av_freep(&pktl);
  288. }
  289. mp3->queue_end = NULL;
  290. return ret;
  291. }
  292. static void mp3_update_xing(AVFormatContext *s)
  293. {
  294. MP3Context *mp3 = s->priv_data;
  295. AVReplayGain *rg;
  296. uint16_t tag_crc;
  297. uint8_t *toc;
  298. int i, rg_size;
  299. /* replace "Xing" identification string with "Info" for CBR files. */
  300. if (!mp3->has_variable_bitrate)
  301. AV_WL32(mp3->xing_frame + mp3->xing_offset, MKTAG('I', 'n', 'f', 'o'));
  302. AV_WB32(mp3->xing_frame + mp3->xing_offset + 8, mp3->frames);
  303. AV_WB32(mp3->xing_frame + mp3->xing_offset + 12, mp3->size);
  304. toc = mp3->xing_frame + mp3->xing_offset + 16;
  305. toc[0] = 0; // first toc entry has to be zero.
  306. for (i = 1; i < XING_TOC_SIZE; ++i) {
  307. int j = i * mp3->pos / XING_TOC_SIZE;
  308. int seek_point = 256LL * mp3->bag[j] / mp3->size;
  309. toc[i] = FFMIN(seek_point, 255);
  310. }
  311. /* write replaygain */
  312. rg = (AVReplayGain*)av_stream_get_side_data(s->streams[0], AV_PKT_DATA_REPLAYGAIN,
  313. &rg_size);
  314. if (rg && rg_size >= sizeof(*rg)) {
  315. uint16_t val;
  316. AV_WB32(mp3->xing_frame + mp3->xing_offset + 131,
  317. av_rescale(rg->track_peak, 1 << 23, 100000));
  318. if (rg->track_gain != INT32_MIN) {
  319. val = FFABS(rg->track_gain / 10000) & ((1 << 9) - 1);
  320. val |= (rg->track_gain < 0) << 9;
  321. val |= 1 << 13;
  322. AV_WB16(mp3->xing_frame + mp3->xing_offset + 135, val);
  323. }
  324. if (rg->album_gain != INT32_MIN) {
  325. val = FFABS(rg->album_gain / 10000) & ((1 << 9) - 1);
  326. val |= (rg->album_gain < 0) << 9;
  327. val |= 1 << 14;
  328. AV_WB16(mp3->xing_frame + mp3->xing_offset + 137, val);
  329. }
  330. }
  331. AV_WB32(mp3->xing_frame + mp3->xing_offset + XING_SIZE - 8, mp3->audio_size);
  332. AV_WB16(mp3->xing_frame + mp3->xing_offset + XING_SIZE - 4, mp3->audio_crc);
  333. tag_crc = av_crc(av_crc_get_table(AV_CRC_16_ANSI_LE), 0, mp3->xing_frame, 190);
  334. AV_WB16(mp3->xing_frame + mp3->xing_offset + XING_SIZE - 2, tag_crc);
  335. avio_seek(s->pb, mp3->xing_frame_offset, SEEK_SET);
  336. avio_write(s->pb, mp3->xing_frame, mp3->xing_frame_size);
  337. avio_seek(s->pb, 0, SEEK_END);
  338. }
  339. static int mp3_write_trailer(struct AVFormatContext *s)
  340. {
  341. uint8_t buf[ID3v1_TAG_SIZE];
  342. MP3Context *mp3 = s->priv_data;
  343. if (mp3->pics_to_write) {
  344. av_log(s, AV_LOG_WARNING, "No packets were sent for some of the "
  345. "attached pictures.\n");
  346. mp3_queue_flush(s);
  347. }
  348. /* write the id3v1 tag */
  349. if (mp3->write_id3v1 && id3v1_create_tag(s, buf) > 0) {
  350. avio_write(s->pb, buf, ID3v1_TAG_SIZE);
  351. }
  352. if (mp3->xing_offset)
  353. mp3_update_xing(s);
  354. av_freep(&mp3->xing_frame);
  355. return 0;
  356. }
  357. #if CONFIG_MP2_MUXER
  358. AVOutputFormat ff_mp2_muxer = {
  359. .name = "mp2",
  360. .long_name = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
  361. .mime_type = "audio/mpeg",
  362. .extensions = "mp2,m2a,mpa",
  363. .audio_codec = AV_CODEC_ID_MP2,
  364. .video_codec = AV_CODEC_ID_NONE,
  365. .write_packet = ff_raw_write_packet,
  366. .flags = AVFMT_NOTIMESTAMPS,
  367. };
  368. #endif
  369. #if CONFIG_MP3_MUXER
  370. static const AVOption options[] = {
  371. { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
  372. offsetof(MP3Context, id3v2_version), AV_OPT_TYPE_INT, {.i64 = 4}, 0, 4, AV_OPT_FLAG_ENCODING_PARAM},
  373. { "write_id3v1", "Enable ID3v1 writing. ID3v1 tags are written in UTF-8 which may not be supported by most software.",
  374. offsetof(MP3Context, write_id3v1), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  375. { "write_xing", "Write the Xing header containing file duration.",
  376. offsetof(MP3Context, write_xing), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  377. { NULL },
  378. };
  379. static const AVClass mp3_muxer_class = {
  380. .class_name = "MP3 muxer",
  381. .item_name = av_default_item_name,
  382. .option = options,
  383. .version = LIBAVUTIL_VERSION_INT,
  384. };
  385. static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
  386. {
  387. MP3Context *mp3 = s->priv_data;
  388. if (pkt->stream_index == mp3->audio_stream_idx) {
  389. if (mp3->pics_to_write) {
  390. /* buffer audio packets until we get all the pictures */
  391. AVPacketList *pktl = av_mallocz(sizeof(*pktl));
  392. if (!pktl)
  393. return AVERROR(ENOMEM);
  394. pktl->pkt = *pkt;
  395. pktl->pkt.buf = av_buffer_ref(pkt->buf);
  396. if (!pktl->pkt.buf) {
  397. av_freep(&pktl);
  398. return AVERROR(ENOMEM);
  399. }
  400. if (mp3->queue_end)
  401. mp3->queue_end->next = pktl;
  402. else
  403. mp3->queue = pktl;
  404. mp3->queue_end = pktl;
  405. } else
  406. return mp3_write_audio_packet(s, pkt);
  407. } else {
  408. int ret;
  409. /* warn only once for each stream */
  410. if (s->streams[pkt->stream_index]->nb_frames == 1) {
  411. av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
  412. " ignoring.\n", pkt->stream_index);
  413. }
  414. if (!mp3->pics_to_write || s->streams[pkt->stream_index]->nb_frames >= 1)
  415. return 0;
  416. if ((ret = ff_id3v2_write_apic(s, &mp3->id3, pkt)) < 0)
  417. return ret;
  418. mp3->pics_to_write--;
  419. /* flush the buffered audio packets */
  420. if (!mp3->pics_to_write &&
  421. (ret = mp3_queue_flush(s)) < 0)
  422. return ret;
  423. }
  424. return 0;
  425. }
  426. /**
  427. * Write an ID3v2 header at beginning of stream
  428. */
  429. static int mp3_write_header(struct AVFormatContext *s)
  430. {
  431. MP3Context *mp3 = s->priv_data;
  432. int ret, i;
  433. if (mp3->id3v2_version &&
  434. mp3->id3v2_version != 3 &&
  435. mp3->id3v2_version != 4) {
  436. av_log(s, AV_LOG_ERROR, "Invalid ID3v2 version requested: %d. Only "
  437. "3, 4 or 0 (disabled) are allowed.\n", mp3->id3v2_version);
  438. return AVERROR(EINVAL);
  439. }
  440. /* check the streams -- we want exactly one audio and arbitrary number of
  441. * video (attached pictures) */
  442. mp3->audio_stream_idx = -1;
  443. for (i = 0; i < s->nb_streams; i++) {
  444. AVStream *st = s->streams[i];
  445. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  446. if (mp3->audio_stream_idx >= 0 || st->codec->codec_id != AV_CODEC_ID_MP3) {
  447. av_log(s, AV_LOG_ERROR, "Invalid audio stream. Exactly one MP3 "
  448. "audio stream is required.\n");
  449. return AVERROR(EINVAL);
  450. }
  451. mp3->audio_stream_idx = i;
  452. } else if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO) {
  453. av_log(s, AV_LOG_ERROR, "Only audio streams and pictures are allowed in MP3.\n");
  454. return AVERROR(EINVAL);
  455. }
  456. }
  457. if (mp3->audio_stream_idx < 0) {
  458. av_log(s, AV_LOG_ERROR, "No audio stream present.\n");
  459. return AVERROR(EINVAL);
  460. }
  461. mp3->pics_to_write = s->nb_streams - 1;
  462. if (mp3->pics_to_write && !mp3->id3v2_version) {
  463. av_log(s, AV_LOG_ERROR, "Attached pictures were requested, but the "
  464. "ID3v2 header is disabled.\n");
  465. return AVERROR(EINVAL);
  466. }
  467. if (mp3->id3v2_version) {
  468. ff_id3v2_start(&mp3->id3, s->pb, mp3->id3v2_version, ID3v2_DEFAULT_MAGIC);
  469. ret = ff_id3v2_write_metadata(s, &mp3->id3);
  470. if (ret < 0)
  471. return ret;
  472. }
  473. if (!mp3->pics_to_write) {
  474. if (mp3->id3v2_version)
  475. ff_id3v2_finish(&mp3->id3, s->pb);
  476. mp3_write_xing(s);
  477. }
  478. return 0;
  479. }
  480. AVOutputFormat ff_mp3_muxer = {
  481. .name = "mp3",
  482. .long_name = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
  483. .mime_type = "audio/mpeg",
  484. .extensions = "mp3",
  485. .priv_data_size = sizeof(MP3Context),
  486. .audio_codec = AV_CODEC_ID_MP3,
  487. .video_codec = AV_CODEC_ID_PNG,
  488. .write_header = mp3_write_header,
  489. .write_packet = mp3_write_packet,
  490. .write_trailer = mp3_write_trailer,
  491. .flags = AVFMT_NOTIMESTAMPS,
  492. .priv_class = &mp3_muxer_class,
  493. };
  494. #endif