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.

498 lines
15KB

  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. static int id3v1_set_string(AVFormatContext *s, const char *key,
  35. uint8_t *buf, int buf_size)
  36. {
  37. AVDictionaryEntry *tag;
  38. if ((tag = av_dict_get(s->metadata, key, NULL, 0)))
  39. av_strlcpy(buf, tag->value, buf_size);
  40. return !!tag;
  41. }
  42. static int id3v1_create_tag(AVFormatContext *s, uint8_t *buf)
  43. {
  44. AVDictionaryEntry *tag;
  45. int i, count = 0;
  46. memset(buf, 0, ID3v1_TAG_SIZE); /* fail safe */
  47. buf[0] = 'T';
  48. buf[1] = 'A';
  49. buf[2] = 'G';
  50. count += id3v1_set_string(s, "TIT2", buf + 3, 30); //title
  51. count += id3v1_set_string(s, "TPE1", buf + 33, 30); //author|artist
  52. count += id3v1_set_string(s, "TALB", buf + 63, 30); //album
  53. count += id3v1_set_string(s, "TDRL", buf + 93, 4); //date
  54. count += id3v1_set_string(s, "comment", buf + 97, 30);
  55. if ((tag = av_dict_get(s->metadata, "TRCK", NULL, 0))) { //track
  56. buf[125] = 0;
  57. buf[126] = atoi(tag->value);
  58. count++;
  59. }
  60. buf[127] = 0xFF; /* default to unknown genre */
  61. if ((tag = av_dict_get(s->metadata, "TCON", NULL, 0))) { //genre
  62. for(i = 0; i <= ID3v1_GENRE_MAX; i++) {
  63. if (!av_strcasecmp(tag->value, ff_id3v1_genre_str[i])) {
  64. buf[127] = i;
  65. count++;
  66. break;
  67. }
  68. }
  69. }
  70. return count;
  71. }
  72. #define XING_NUM_BAGS 400
  73. #define XING_TOC_SIZE 100
  74. // maximum size of the xing frame: offset/Xing/flags/frames/size/TOC
  75. #define XING_MAX_SIZE (32 + 4 + 4 + 4 + 4 + XING_TOC_SIZE)
  76. typedef struct MP3Context {
  77. const AVClass *class;
  78. ID3v2EncContext id3;
  79. int id3v2_version;
  80. int write_id3v1;
  81. int write_xing;
  82. /* xing header */
  83. int64_t xing_offset;
  84. int32_t frames;
  85. int32_t size;
  86. uint32_t want;
  87. uint32_t seen;
  88. uint32_t pos;
  89. uint64_t bag[XING_NUM_BAGS];
  90. int initial_bitrate;
  91. int has_variable_bitrate;
  92. /* index of the audio stream */
  93. int audio_stream_idx;
  94. /* number of attached pictures we still need to write */
  95. int pics_to_write;
  96. /* audio packets are queued here until we get all the attached pictures */
  97. AVPacketList *queue, *queue_end;
  98. } MP3Context;
  99. static const uint8_t xing_offtbl[2][2] = {{32, 17}, {17, 9}};
  100. /*
  101. * Write an empty XING header and initialize respective data.
  102. */
  103. static void mp3_write_xing(AVFormatContext *s)
  104. {
  105. MP3Context *mp3 = s->priv_data;
  106. AVCodecContext *codec = s->streams[mp3->audio_stream_idx]->codec;
  107. int32_t header;
  108. MPADecodeHeader mpah;
  109. int srate_idx, i, channels;
  110. int bitrate_idx;
  111. int best_bitrate_idx;
  112. int best_bitrate_error = INT_MAX;
  113. int xing_offset;
  114. int ver = 0;
  115. int lsf, bytes_needed;
  116. if (!s->pb->seekable || !mp3->write_xing)
  117. return;
  118. for (i = 0; i < FF_ARRAY_ELEMS(avpriv_mpa_freq_tab); i++) {
  119. const uint16_t base_freq = avpriv_mpa_freq_tab[i];
  120. if (codec->sample_rate == base_freq) ver = 0x3; // MPEG 1
  121. else if (codec->sample_rate == base_freq / 2) ver = 0x2; // MPEG 2
  122. else if (codec->sample_rate == base_freq / 4) ver = 0x0; // MPEG 2.5
  123. else continue;
  124. srate_idx = i;
  125. break;
  126. }
  127. if (i == FF_ARRAY_ELEMS(avpriv_mpa_freq_tab)) {
  128. av_log(s, AV_LOG_WARNING, "Unsupported sample rate, not writing Xing "
  129. "header.\n");
  130. return;
  131. }
  132. switch (codec->channels) {
  133. case 1: channels = MPA_MONO; break;
  134. case 2: channels = MPA_STEREO; break;
  135. default: av_log(s, AV_LOG_WARNING, "Unsupported number of channels, "
  136. "not writing Xing header.\n");
  137. return;
  138. }
  139. /* dummy MPEG audio header */
  140. header = 0xff << 24; // sync
  141. header |= (0x7 << 5 | ver << 3 | 0x1 << 1 | 0x1) << 16; // sync/audio-version/layer 3/no crc*/
  142. header |= (srate_idx << 2) << 8;
  143. header |= channels << 6;
  144. lsf = !((header & (1 << 20) && header & (1 << 19)));
  145. xing_offset = xing_offtbl[ver != 3][channels == 1];
  146. bytes_needed = 4 // header
  147. + xing_offset
  148. + 4 // xing tag
  149. + 4 // frames/size/toc flags
  150. + 4 // frames
  151. + 4 // size
  152. + XING_TOC_SIZE; // toc
  153. for (bitrate_idx = 1; bitrate_idx < 15; bitrate_idx++) {
  154. int bit_rate = 1000 * avpriv_mpa_bitrate_tab[lsf][3 - 1][bitrate_idx];
  155. int error = FFABS(bit_rate - codec->bit_rate);
  156. if (error < best_bitrate_error){
  157. best_bitrate_error = error;
  158. best_bitrate_idx = bitrate_idx;
  159. }
  160. }
  161. for (bitrate_idx = best_bitrate_idx; bitrate_idx < 15; bitrate_idx++) {
  162. int32_t mask = bitrate_idx << (4 + 8);
  163. header |= mask;
  164. avpriv_mpegaudio_decode_header(&mpah, header);
  165. if (bytes_needed <= mpah.frame_size)
  166. break;
  167. header &= ~mask;
  168. }
  169. avio_wb32(s->pb, header);
  170. avpriv_mpegaudio_decode_header(&mpah, header);
  171. av_assert0(mpah.frame_size >= XING_MAX_SIZE);
  172. ffio_fill(s->pb, 0, xing_offset);
  173. mp3->xing_offset = avio_tell(s->pb);
  174. ffio_wfourcc(s->pb, "Xing");
  175. avio_wb32(s->pb, 0x01 | 0x02 | 0x04); // frames / size / TOC
  176. mp3->size = mpah.frame_size;
  177. mp3->want = 1;
  178. avio_wb32(s->pb, 0); // frames
  179. avio_wb32(s->pb, 0); // size
  180. // TOC
  181. for (i = 0; i < XING_TOC_SIZE; i++)
  182. avio_w8(s->pb, 255 * i / XING_TOC_SIZE);
  183. ffio_fill(s->pb, 0, mpah.frame_size - bytes_needed);
  184. }
  185. /*
  186. * Add a frame to XING data.
  187. * Following lame's "VbrTag.c".
  188. */
  189. static void mp3_xing_add_frame(MP3Context *mp3, AVPacket *pkt)
  190. {
  191. int i;
  192. mp3->frames++;
  193. mp3->seen++;
  194. mp3->size += pkt->size;
  195. if (mp3->want == mp3->seen) {
  196. mp3->bag[mp3->pos] = mp3->size;
  197. if (XING_NUM_BAGS == ++mp3->pos) {
  198. /* shrink table to half size by throwing away each second bag. */
  199. for (i = 1; i < XING_NUM_BAGS; i += 2)
  200. mp3->bag[i / 2] = mp3->bag[i];
  201. /* double wanted amount per bag. */
  202. mp3->want *= 2;
  203. /* adjust current position to half of table size. */
  204. mp3->pos = XING_NUM_BAGS / 2;
  205. }
  206. mp3->seen = 0;
  207. }
  208. }
  209. static int mp3_write_audio_packet(AVFormatContext *s, AVPacket *pkt)
  210. {
  211. MP3Context *mp3 = s->priv_data;
  212. if (mp3->xing_offset && pkt->size >= 4) {
  213. MPADecodeHeader c;
  214. uint32_t h;
  215. h = AV_RB32(pkt->data);
  216. if (ff_mpa_check_header(h) == 0) {
  217. avpriv_mpegaudio_decode_header(&c, h);
  218. if (!mp3->initial_bitrate)
  219. mp3->initial_bitrate = c.bit_rate;
  220. if ((c.bit_rate == 0) || (mp3->initial_bitrate != c.bit_rate))
  221. mp3->has_variable_bitrate = 1;
  222. }
  223. mp3_xing_add_frame(mp3, pkt);
  224. }
  225. return ff_raw_write_packet(s, pkt);
  226. }
  227. static int mp3_queue_flush(AVFormatContext *s)
  228. {
  229. MP3Context *mp3 = s->priv_data;
  230. AVPacketList *pktl;
  231. int ret = 0, write = 1;
  232. ff_id3v2_finish(&mp3->id3, s->pb);
  233. mp3_write_xing(s);
  234. while ((pktl = mp3->queue)) {
  235. if (write && (ret = mp3_write_audio_packet(s, &pktl->pkt)) < 0)
  236. write = 0;
  237. av_free_packet(&pktl->pkt);
  238. mp3->queue = pktl->next;
  239. av_freep(&pktl);
  240. }
  241. mp3->queue_end = NULL;
  242. return ret;
  243. }
  244. static void mp3_update_xing(AVFormatContext *s)
  245. {
  246. MP3Context *mp3 = s->priv_data;
  247. int i;
  248. /* replace "Xing" identification string with "Info" for CBR files. */
  249. if (!mp3->has_variable_bitrate) {
  250. avio_seek(s->pb, mp3->xing_offset, SEEK_SET);
  251. ffio_wfourcc(s->pb, "Info");
  252. }
  253. avio_seek(s->pb, mp3->xing_offset + 8, SEEK_SET);
  254. avio_wb32(s->pb, mp3->frames);
  255. avio_wb32(s->pb, mp3->size);
  256. avio_w8(s->pb, 0); // first toc entry has to be zero.
  257. for (i = 1; i < XING_TOC_SIZE; ++i) {
  258. int j = i * mp3->pos / XING_TOC_SIZE;
  259. int seek_point = 256LL * mp3->bag[j] / mp3->size;
  260. avio_w8(s->pb, FFMIN(seek_point, 255));
  261. }
  262. avio_seek(s->pb, 0, SEEK_END);
  263. }
  264. static int mp3_write_trailer(struct AVFormatContext *s)
  265. {
  266. uint8_t buf[ID3v1_TAG_SIZE];
  267. MP3Context *mp3 = s->priv_data;
  268. if (mp3->pics_to_write) {
  269. av_log(s, AV_LOG_WARNING, "No packets were sent for some of the "
  270. "attached pictures.\n");
  271. mp3_queue_flush(s);
  272. }
  273. /* write the id3v1 tag */
  274. if (mp3->write_id3v1 && id3v1_create_tag(s, buf) > 0) {
  275. avio_write(s->pb, buf, ID3v1_TAG_SIZE);
  276. }
  277. if (mp3->xing_offset)
  278. mp3_update_xing(s);
  279. return 0;
  280. }
  281. #if CONFIG_MP2_MUXER
  282. AVOutputFormat ff_mp2_muxer = {
  283. .name = "mp2",
  284. .long_name = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
  285. .mime_type = "audio/x-mpeg",
  286. .extensions = "mp2,m2a,mpa",
  287. .audio_codec = AV_CODEC_ID_MP2,
  288. .video_codec = AV_CODEC_ID_NONE,
  289. .write_packet = ff_raw_write_packet,
  290. .flags = AVFMT_NOTIMESTAMPS,
  291. };
  292. #endif
  293. #if CONFIG_MP3_MUXER
  294. static const AVOption options[] = {
  295. { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
  296. offsetof(MP3Context, id3v2_version), AV_OPT_TYPE_INT, {.i64 = 4}, 0, 4, AV_OPT_FLAG_ENCODING_PARAM},
  297. { "write_id3v1", "Enable ID3v1 writing. ID3v1 tags are written in UTF-8 which may not be supported by most software.",
  298. offsetof(MP3Context, write_id3v1), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  299. { "write_xing", "Write the Xing header containing file duration.",
  300. offsetof(MP3Context, write_xing), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  301. { NULL },
  302. };
  303. static const AVClass mp3_muxer_class = {
  304. .class_name = "MP3 muxer",
  305. .item_name = av_default_item_name,
  306. .option = options,
  307. .version = LIBAVUTIL_VERSION_INT,
  308. };
  309. static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
  310. {
  311. MP3Context *mp3 = s->priv_data;
  312. if (pkt->stream_index == mp3->audio_stream_idx) {
  313. if (mp3->pics_to_write) {
  314. /* buffer audio packets until we get all the pictures */
  315. AVPacketList *pktl = av_mallocz(sizeof(*pktl));
  316. if (!pktl)
  317. return AVERROR(ENOMEM);
  318. pktl->pkt = *pkt;
  319. pktl->pkt.buf = av_buffer_ref(pkt->buf);
  320. if (!pktl->pkt.buf) {
  321. av_freep(&pktl);
  322. return AVERROR(ENOMEM);
  323. }
  324. if (mp3->queue_end)
  325. mp3->queue_end->next = pktl;
  326. else
  327. mp3->queue = pktl;
  328. mp3->queue_end = pktl;
  329. } else
  330. return mp3_write_audio_packet(s, pkt);
  331. } else {
  332. int ret;
  333. /* warn only once for each stream */
  334. if (s->streams[pkt->stream_index]->nb_frames == 1) {
  335. av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
  336. " ignoring.\n", pkt->stream_index);
  337. }
  338. if (!mp3->pics_to_write || s->streams[pkt->stream_index]->nb_frames >= 1)
  339. return 0;
  340. if ((ret = ff_id3v2_write_apic(s, &mp3->id3, pkt)) < 0)
  341. return ret;
  342. mp3->pics_to_write--;
  343. /* flush the buffered audio packets */
  344. if (!mp3->pics_to_write &&
  345. (ret = mp3_queue_flush(s)) < 0)
  346. return ret;
  347. }
  348. return 0;
  349. }
  350. /**
  351. * Write an ID3v2 header at beginning of stream
  352. */
  353. static int mp3_write_header(struct AVFormatContext *s)
  354. {
  355. MP3Context *mp3 = s->priv_data;
  356. int ret, i;
  357. if (mp3->id3v2_version &&
  358. mp3->id3v2_version != 3 &&
  359. mp3->id3v2_version != 4) {
  360. av_log(s, AV_LOG_ERROR, "Invalid ID3v2 version requested: %d. Only "
  361. "3, 4 or 0 (disabled) are allowed.\n", mp3->id3v2_version);
  362. return AVERROR(EINVAL);
  363. }
  364. /* check the streams -- we want exactly one audio and arbitrary number of
  365. * video (attached pictures) */
  366. mp3->audio_stream_idx = -1;
  367. for (i = 0; i < s->nb_streams; i++) {
  368. AVStream *st = s->streams[i];
  369. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  370. if (mp3->audio_stream_idx >= 0 || st->codec->codec_id != AV_CODEC_ID_MP3) {
  371. av_log(s, AV_LOG_ERROR, "Invalid audio stream. Exactly one MP3 "
  372. "audio stream is required.\n");
  373. return AVERROR(EINVAL);
  374. }
  375. mp3->audio_stream_idx = i;
  376. } else if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO) {
  377. av_log(s, AV_LOG_ERROR, "Only audio streams and pictures are allowed in MP3.\n");
  378. return AVERROR(EINVAL);
  379. }
  380. }
  381. if (mp3->audio_stream_idx < 0) {
  382. av_log(s, AV_LOG_ERROR, "No audio stream present.\n");
  383. return AVERROR(EINVAL);
  384. }
  385. mp3->pics_to_write = s->nb_streams - 1;
  386. if (mp3->pics_to_write && !mp3->id3v2_version) {
  387. av_log(s, AV_LOG_ERROR, "Attached pictures were requested, but the "
  388. "ID3v2 header is disabled.\n");
  389. return AVERROR(EINVAL);
  390. }
  391. if (mp3->id3v2_version) {
  392. ff_id3v2_start(&mp3->id3, s->pb, mp3->id3v2_version, ID3v2_DEFAULT_MAGIC);
  393. ret = ff_id3v2_write_metadata(s, &mp3->id3);
  394. if (ret < 0)
  395. return ret;
  396. }
  397. if (!mp3->pics_to_write) {
  398. if (mp3->id3v2_version)
  399. ff_id3v2_finish(&mp3->id3, s->pb);
  400. mp3_write_xing(s);
  401. }
  402. return 0;
  403. }
  404. AVOutputFormat ff_mp3_muxer = {
  405. .name = "mp3",
  406. .long_name = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
  407. .mime_type = "audio/x-mpeg",
  408. .extensions = "mp3",
  409. .priv_data_size = sizeof(MP3Context),
  410. .audio_codec = AV_CODEC_ID_MP3,
  411. .video_codec = AV_CODEC_ID_PNG,
  412. .write_header = mp3_write_header,
  413. .write_packet = mp3_write_packet,
  414. .write_trailer = mp3_write_trailer,
  415. .flags = AVFMT_NOTIMESTAMPS,
  416. .priv_class = &mp3_muxer_class,
  417. };
  418. #endif