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.

463 lines
14KB

  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 xing_offset;
  112. int ver = 0;
  113. if (!s->pb->seekable || !mp3->write_xing)
  114. return;
  115. for (i = 0; i < FF_ARRAY_ELEMS(avpriv_mpa_freq_tab); i++) {
  116. const uint16_t base_freq = avpriv_mpa_freq_tab[i];
  117. if (codec->sample_rate == base_freq) ver = 0x3; // MPEG 1
  118. else if (codec->sample_rate == base_freq / 2) ver = 0x2; // MPEG 2
  119. else if (codec->sample_rate == base_freq / 4) ver = 0x0; // MPEG 2.5
  120. else continue;
  121. srate_idx = i;
  122. break;
  123. }
  124. if (i == FF_ARRAY_ELEMS(avpriv_mpa_freq_tab)) {
  125. av_log(s, AV_LOG_WARNING, "Unsupported sample rate, not writing Xing "
  126. "header.\n");
  127. return;
  128. }
  129. switch (codec->channels) {
  130. case 1: channels = MPA_MONO; break;
  131. case 2: channels = MPA_STEREO; break;
  132. default: av_log(s, AV_LOG_WARNING, "Unsupported number of channels, "
  133. "not writing Xing header.\n");
  134. return;
  135. }
  136. /* 64 kbps frame, should be large enough */
  137. bitrate_idx = (ver == 3) ? 5 : 8;
  138. /* dummy MPEG audio header */
  139. header = 0xff << 24; // sync
  140. header |= (0x7 << 5 | ver << 3 | 0x1 << 1 | 0x1) << 16; // sync/audio-version/layer 3/no crc*/
  141. header |= (bitrate_idx << 4 | srate_idx << 2) << 8;
  142. header |= channels << 6;
  143. avio_wb32(s->pb, header);
  144. avpriv_mpegaudio_decode_header(&mpah, header);
  145. av_assert0(mpah.frame_size >= XING_MAX_SIZE);
  146. xing_offset = xing_offtbl[ver != 3][codec->channels == 1];
  147. ffio_fill(s->pb, 0, xing_offset);
  148. mp3->xing_offset = avio_tell(s->pb);
  149. ffio_wfourcc(s->pb, "Xing");
  150. avio_wb32(s->pb, 0x01 | 0x02 | 0x04); // frames / size / TOC
  151. mp3->size = mpah.frame_size;
  152. mp3->want = 1;
  153. avio_wb32(s->pb, 0); // frames
  154. avio_wb32(s->pb, 0); // size
  155. // TOC
  156. for (i = 0; i < XING_TOC_SIZE; i++)
  157. avio_w8(s->pb, 255 * i / XING_TOC_SIZE);
  158. mpah.frame_size -= 4 + xing_offset + 4 + 4 + 4 + 4 + XING_TOC_SIZE;
  159. ffio_fill(s->pb, 0, mpah.frame_size);
  160. }
  161. /*
  162. * Add a frame to XING data.
  163. * Following lame's "VbrTag.c".
  164. */
  165. static void mp3_xing_add_frame(MP3Context *mp3, AVPacket *pkt)
  166. {
  167. int i;
  168. mp3->frames++;
  169. mp3->seen++;
  170. mp3->size += pkt->size;
  171. if (mp3->want == mp3->seen) {
  172. mp3->bag[mp3->pos] = mp3->size;
  173. if (XING_NUM_BAGS == ++mp3->pos) {
  174. /* shrink table to half size by throwing away each second bag. */
  175. for (i = 1; i < XING_NUM_BAGS; i += 2)
  176. mp3->bag[i / 2] = mp3->bag[i];
  177. /* double wanted amount per bag. */
  178. mp3->want *= 2;
  179. /* adjust current position to half of table size. */
  180. mp3->pos = XING_NUM_BAGS / 2;
  181. }
  182. mp3->seen = 0;
  183. }
  184. }
  185. static int mp3_write_audio_packet(AVFormatContext *s, AVPacket *pkt)
  186. {
  187. MP3Context *mp3 = s->priv_data;
  188. if (mp3->xing_offset && pkt->size >= 4) {
  189. MPADecodeHeader c;
  190. avpriv_mpegaudio_decode_header(&c, AV_RB32(pkt->data));
  191. if (!mp3->initial_bitrate)
  192. mp3->initial_bitrate = c.bit_rate;
  193. if ((c.bit_rate == 0) || (mp3->initial_bitrate != c.bit_rate))
  194. mp3->has_variable_bitrate = 1;
  195. mp3_xing_add_frame(mp3, pkt);
  196. }
  197. return ff_raw_write_packet(s, pkt);
  198. }
  199. static int mp3_queue_flush(AVFormatContext *s)
  200. {
  201. MP3Context *mp3 = s->priv_data;
  202. AVPacketList *pktl;
  203. int ret = 0, write = 1;
  204. ff_id3v2_finish(&mp3->id3, s->pb);
  205. mp3_write_xing(s);
  206. while ((pktl = mp3->queue)) {
  207. if (write && (ret = mp3_write_audio_packet(s, &pktl->pkt)) < 0)
  208. write = 0;
  209. av_free_packet(&pktl->pkt);
  210. mp3->queue = pktl->next;
  211. av_freep(&pktl);
  212. }
  213. mp3->queue_end = NULL;
  214. return ret;
  215. }
  216. static void mp3_update_xing(AVFormatContext *s)
  217. {
  218. MP3Context *mp3 = s->priv_data;
  219. int i;
  220. /* replace "Xing" identification string with "Info" for CBR files. */
  221. if (!mp3->has_variable_bitrate) {
  222. avio_seek(s->pb, mp3->xing_offset, SEEK_SET);
  223. ffio_wfourcc(s->pb, "Info");
  224. }
  225. avio_seek(s->pb, mp3->xing_offset + 8, SEEK_SET);
  226. avio_wb32(s->pb, mp3->frames);
  227. avio_wb32(s->pb, mp3->size);
  228. avio_w8(s->pb, 0); // first toc entry has to be zero.
  229. for (i = 1; i < XING_TOC_SIZE; ++i) {
  230. int j = i * mp3->pos / XING_TOC_SIZE;
  231. int seek_point = 256LL * mp3->bag[j] / mp3->size;
  232. avio_w8(s->pb, FFMIN(seek_point, 255));
  233. }
  234. avio_seek(s->pb, 0, SEEK_END);
  235. }
  236. static int mp3_write_trailer(struct AVFormatContext *s)
  237. {
  238. uint8_t buf[ID3v1_TAG_SIZE];
  239. MP3Context *mp3 = s->priv_data;
  240. if (mp3->pics_to_write) {
  241. av_log(s, AV_LOG_WARNING, "No packets were sent for some of the "
  242. "attached pictures.\n");
  243. mp3_queue_flush(s);
  244. }
  245. /* write the id3v1 tag */
  246. if (mp3->write_id3v1 && id3v1_create_tag(s, buf) > 0) {
  247. avio_write(s->pb, buf, ID3v1_TAG_SIZE);
  248. }
  249. if (mp3->xing_offset)
  250. mp3_update_xing(s);
  251. return 0;
  252. }
  253. #if CONFIG_MP2_MUXER
  254. AVOutputFormat ff_mp2_muxer = {
  255. .name = "mp2",
  256. .long_name = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
  257. .mime_type = "audio/x-mpeg",
  258. .extensions = "mp2,m2a,mpa",
  259. .audio_codec = AV_CODEC_ID_MP2,
  260. .video_codec = AV_CODEC_ID_NONE,
  261. .write_packet = ff_raw_write_packet,
  262. .flags = AVFMT_NOTIMESTAMPS,
  263. };
  264. #endif
  265. #if CONFIG_MP3_MUXER
  266. static const AVOption options[] = {
  267. { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
  268. offsetof(MP3Context, id3v2_version), AV_OPT_TYPE_INT, {.i64 = 4}, 0, 4, AV_OPT_FLAG_ENCODING_PARAM},
  269. { "write_id3v1", "Enable ID3v1 writing. ID3v1 tags are written in UTF-8 which may not be supported by most software.",
  270. offsetof(MP3Context, write_id3v1), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  271. { "write_xing", "Write the Xing header containing file duration.",
  272. offsetof(MP3Context, write_xing), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  273. { NULL },
  274. };
  275. static const AVClass mp3_muxer_class = {
  276. .class_name = "MP3 muxer",
  277. .item_name = av_default_item_name,
  278. .option = options,
  279. .version = LIBAVUTIL_VERSION_INT,
  280. };
  281. static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
  282. {
  283. MP3Context *mp3 = s->priv_data;
  284. if (pkt->stream_index == mp3->audio_stream_idx) {
  285. if (mp3->pics_to_write) {
  286. /* buffer audio packets until we get all the pictures */
  287. AVPacketList *pktl = av_mallocz(sizeof(*pktl));
  288. if (!pktl)
  289. return AVERROR(ENOMEM);
  290. pktl->pkt = *pkt;
  291. pktl->pkt.buf = av_buffer_ref(pkt->buf);
  292. if (!pktl->pkt.buf) {
  293. av_freep(&pktl);
  294. return AVERROR(ENOMEM);
  295. }
  296. if (mp3->queue_end)
  297. mp3->queue_end->next = pktl;
  298. else
  299. mp3->queue = pktl;
  300. mp3->queue_end = pktl;
  301. } else
  302. return mp3_write_audio_packet(s, pkt);
  303. } else {
  304. int ret;
  305. /* warn only once for each stream */
  306. if (s->streams[pkt->stream_index]->nb_frames == 1) {
  307. av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
  308. " ignoring.\n", pkt->stream_index);
  309. }
  310. if (!mp3->pics_to_write || s->streams[pkt->stream_index]->nb_frames >= 1)
  311. return 0;
  312. if ((ret = ff_id3v2_write_apic(s, &mp3->id3, pkt)) < 0)
  313. return ret;
  314. mp3->pics_to_write--;
  315. /* flush the buffered audio packets */
  316. if (!mp3->pics_to_write &&
  317. (ret = mp3_queue_flush(s)) < 0)
  318. return ret;
  319. }
  320. return 0;
  321. }
  322. /**
  323. * Write an ID3v2 header at beginning of stream
  324. */
  325. static int mp3_write_header(struct AVFormatContext *s)
  326. {
  327. MP3Context *mp3 = s->priv_data;
  328. int ret, i;
  329. if (mp3->id3v2_version &&
  330. mp3->id3v2_version != 3 &&
  331. mp3->id3v2_version != 4) {
  332. av_log(s, AV_LOG_ERROR, "Invalid ID3v2 version requested: %d. Only "
  333. "3, 4 or 0 (disabled) are allowed.\n", mp3->id3v2_version);
  334. return AVERROR(EINVAL);
  335. }
  336. /* check the streams -- we want exactly one audio and arbitrary number of
  337. * video (attached pictures) */
  338. mp3->audio_stream_idx = -1;
  339. for (i = 0; i < s->nb_streams; i++) {
  340. AVStream *st = s->streams[i];
  341. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  342. if (mp3->audio_stream_idx >= 0 || st->codec->codec_id != AV_CODEC_ID_MP3) {
  343. av_log(s, AV_LOG_ERROR, "Invalid audio stream. Exactly one MP3 "
  344. "audio stream is required.\n");
  345. return AVERROR(EINVAL);
  346. }
  347. mp3->audio_stream_idx = i;
  348. } else if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO) {
  349. av_log(s, AV_LOG_ERROR, "Only audio streams and pictures are allowed in MP3.\n");
  350. return AVERROR(EINVAL);
  351. }
  352. }
  353. if (mp3->audio_stream_idx < 0) {
  354. av_log(s, AV_LOG_ERROR, "No audio stream present.\n");
  355. return AVERROR(EINVAL);
  356. }
  357. mp3->pics_to_write = s->nb_streams - 1;
  358. if (mp3->pics_to_write && !mp3->id3v2_version) {
  359. av_log(s, AV_LOG_ERROR, "Attached pictures were requested, but the "
  360. "ID3v2 header is disabled.\n");
  361. return AVERROR(EINVAL);
  362. }
  363. if (mp3->id3v2_version) {
  364. ff_id3v2_start(&mp3->id3, s->pb, mp3->id3v2_version, ID3v2_DEFAULT_MAGIC);
  365. ret = ff_id3v2_write_metadata(s, &mp3->id3);
  366. if (ret < 0)
  367. return ret;
  368. }
  369. if (!mp3->pics_to_write) {
  370. if (mp3->id3v2_version)
  371. ff_id3v2_finish(&mp3->id3, s->pb);
  372. mp3_write_xing(s);
  373. }
  374. return 0;
  375. }
  376. AVOutputFormat ff_mp3_muxer = {
  377. .name = "mp3",
  378. .long_name = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
  379. .mime_type = "audio/x-mpeg",
  380. .extensions = "mp3",
  381. .priv_data_size = sizeof(MP3Context),
  382. .audio_codec = AV_CODEC_ID_MP3,
  383. .video_codec = AV_CODEC_ID_PNG,
  384. .write_header = mp3_write_header,
  385. .write_packet = mp3_write_packet,
  386. .write_trailer = mp3_write_trailer,
  387. .flags = AVFMT_NOTIMESTAMPS,
  388. .priv_class = &mp3_muxer_class,
  389. };
  390. #endif