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.

495 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. avpriv_mpegaudio_decode_header(&c, AV_RB32(pkt->data));
  215. if (!mp3->initial_bitrate)
  216. mp3->initial_bitrate = c.bit_rate;
  217. if ((c.bit_rate == 0) || (mp3->initial_bitrate != c.bit_rate))
  218. mp3->has_variable_bitrate = 1;
  219. mp3_xing_add_frame(mp3, pkt);
  220. }
  221. return ff_raw_write_packet(s, pkt);
  222. }
  223. static int mp3_queue_flush(AVFormatContext *s)
  224. {
  225. MP3Context *mp3 = s->priv_data;
  226. AVPacketList *pktl;
  227. int ret = 0, write = 1;
  228. ff_id3v2_finish(&mp3->id3, s->pb);
  229. mp3_write_xing(s);
  230. while ((pktl = mp3->queue)) {
  231. if (write && (ret = mp3_write_audio_packet(s, &pktl->pkt)) < 0)
  232. write = 0;
  233. av_free_packet(&pktl->pkt);
  234. mp3->queue = pktl->next;
  235. av_freep(&pktl);
  236. }
  237. mp3->queue_end = NULL;
  238. return ret;
  239. }
  240. static void mp3_update_xing(AVFormatContext *s)
  241. {
  242. MP3Context *mp3 = s->priv_data;
  243. int i;
  244. /* replace "Xing" identification string with "Info" for CBR files. */
  245. if (!mp3->has_variable_bitrate) {
  246. avio_seek(s->pb, mp3->xing_offset, SEEK_SET);
  247. ffio_wfourcc(s->pb, "Info");
  248. }
  249. avio_seek(s->pb, mp3->xing_offset + 8, SEEK_SET);
  250. avio_wb32(s->pb, mp3->frames);
  251. avio_wb32(s->pb, mp3->size);
  252. avio_w8(s->pb, 0); // first toc entry has to be zero.
  253. for (i = 1; i < XING_TOC_SIZE; ++i) {
  254. int j = i * mp3->pos / XING_TOC_SIZE;
  255. int seek_point = 256LL * mp3->bag[j] / mp3->size;
  256. avio_w8(s->pb, FFMIN(seek_point, 255));
  257. }
  258. avio_seek(s->pb, 0, SEEK_END);
  259. }
  260. static int mp3_write_trailer(struct AVFormatContext *s)
  261. {
  262. uint8_t buf[ID3v1_TAG_SIZE];
  263. MP3Context *mp3 = s->priv_data;
  264. if (mp3->pics_to_write) {
  265. av_log(s, AV_LOG_WARNING, "No packets were sent for some of the "
  266. "attached pictures.\n");
  267. mp3_queue_flush(s);
  268. }
  269. /* write the id3v1 tag */
  270. if (mp3->write_id3v1 && id3v1_create_tag(s, buf) > 0) {
  271. avio_write(s->pb, buf, ID3v1_TAG_SIZE);
  272. }
  273. if (mp3->xing_offset)
  274. mp3_update_xing(s);
  275. return 0;
  276. }
  277. #if CONFIG_MP2_MUXER
  278. AVOutputFormat ff_mp2_muxer = {
  279. .name = "mp2",
  280. .long_name = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
  281. .mime_type = "audio/x-mpeg",
  282. .extensions = "mp2,m2a,mpa",
  283. .audio_codec = AV_CODEC_ID_MP2,
  284. .video_codec = AV_CODEC_ID_NONE,
  285. .write_packet = ff_raw_write_packet,
  286. .flags = AVFMT_NOTIMESTAMPS,
  287. };
  288. #endif
  289. #if CONFIG_MP3_MUXER
  290. static const AVOption options[] = {
  291. { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
  292. offsetof(MP3Context, id3v2_version), AV_OPT_TYPE_INT, {.i64 = 4}, 0, 4, AV_OPT_FLAG_ENCODING_PARAM},
  293. { "write_id3v1", "Enable ID3v1 writing. ID3v1 tags are written in UTF-8 which may not be supported by most software.",
  294. offsetof(MP3Context, write_id3v1), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  295. { "write_xing", "Write the Xing header containing file duration.",
  296. offsetof(MP3Context, write_xing), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  297. { NULL },
  298. };
  299. static const AVClass mp3_muxer_class = {
  300. .class_name = "MP3 muxer",
  301. .item_name = av_default_item_name,
  302. .option = options,
  303. .version = LIBAVUTIL_VERSION_INT,
  304. };
  305. static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
  306. {
  307. MP3Context *mp3 = s->priv_data;
  308. if (pkt->stream_index == mp3->audio_stream_idx) {
  309. if (mp3->pics_to_write) {
  310. /* buffer audio packets until we get all the pictures */
  311. AVPacketList *pktl = av_mallocz(sizeof(*pktl));
  312. if (!pktl)
  313. return AVERROR(ENOMEM);
  314. pktl->pkt = *pkt;
  315. pktl->pkt.buf = av_buffer_ref(pkt->buf);
  316. if (!pktl->pkt.buf) {
  317. av_freep(&pktl);
  318. return AVERROR(ENOMEM);
  319. }
  320. if (mp3->queue_end)
  321. mp3->queue_end->next = pktl;
  322. else
  323. mp3->queue = pktl;
  324. mp3->queue_end = pktl;
  325. } else
  326. return mp3_write_audio_packet(s, pkt);
  327. } else {
  328. int ret;
  329. /* warn only once for each stream */
  330. if (s->streams[pkt->stream_index]->nb_frames == 1) {
  331. av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
  332. " ignoring.\n", pkt->stream_index);
  333. }
  334. if (!mp3->pics_to_write || s->streams[pkt->stream_index]->nb_frames >= 1)
  335. return 0;
  336. if ((ret = ff_id3v2_write_apic(s, &mp3->id3, pkt)) < 0)
  337. return ret;
  338. mp3->pics_to_write--;
  339. /* flush the buffered audio packets */
  340. if (!mp3->pics_to_write &&
  341. (ret = mp3_queue_flush(s)) < 0)
  342. return ret;
  343. }
  344. return 0;
  345. }
  346. /**
  347. * Write an ID3v2 header at beginning of stream
  348. */
  349. static int mp3_write_header(struct AVFormatContext *s)
  350. {
  351. MP3Context *mp3 = s->priv_data;
  352. int ret, i;
  353. if (mp3->id3v2_version &&
  354. mp3->id3v2_version != 3 &&
  355. mp3->id3v2_version != 4) {
  356. av_log(s, AV_LOG_ERROR, "Invalid ID3v2 version requested: %d. Only "
  357. "3, 4 or 0 (disabled) are allowed.\n", mp3->id3v2_version);
  358. return AVERROR(EINVAL);
  359. }
  360. /* check the streams -- we want exactly one audio and arbitrary number of
  361. * video (attached pictures) */
  362. mp3->audio_stream_idx = -1;
  363. for (i = 0; i < s->nb_streams; i++) {
  364. AVStream *st = s->streams[i];
  365. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  366. if (mp3->audio_stream_idx >= 0 || st->codec->codec_id != AV_CODEC_ID_MP3) {
  367. av_log(s, AV_LOG_ERROR, "Invalid audio stream. Exactly one MP3 "
  368. "audio stream is required.\n");
  369. return AVERROR(EINVAL);
  370. }
  371. mp3->audio_stream_idx = i;
  372. } else if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO) {
  373. av_log(s, AV_LOG_ERROR, "Only audio streams and pictures are allowed in MP3.\n");
  374. return AVERROR(EINVAL);
  375. }
  376. }
  377. if (mp3->audio_stream_idx < 0) {
  378. av_log(s, AV_LOG_ERROR, "No audio stream present.\n");
  379. return AVERROR(EINVAL);
  380. }
  381. mp3->pics_to_write = s->nb_streams - 1;
  382. if (mp3->pics_to_write && !mp3->id3v2_version) {
  383. av_log(s, AV_LOG_ERROR, "Attached pictures were requested, but the "
  384. "ID3v2 header is disabled.\n");
  385. return AVERROR(EINVAL);
  386. }
  387. if (mp3->id3v2_version) {
  388. ff_id3v2_start(&mp3->id3, s->pb, mp3->id3v2_version, ID3v2_DEFAULT_MAGIC);
  389. ret = ff_id3v2_write_metadata(s, &mp3->id3);
  390. if (ret < 0)
  391. return ret;
  392. }
  393. if (!mp3->pics_to_write) {
  394. if (mp3->id3v2_version)
  395. ff_id3v2_finish(&mp3->id3, s->pb);
  396. mp3_write_xing(s);
  397. }
  398. return 0;
  399. }
  400. AVOutputFormat ff_mp3_muxer = {
  401. .name = "mp3",
  402. .long_name = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
  403. .mime_type = "audio/x-mpeg",
  404. .extensions = "mp3",
  405. .priv_data_size = sizeof(MP3Context),
  406. .audio_codec = AV_CODEC_ID_MP3,
  407. .video_codec = AV_CODEC_ID_PNG,
  408. .write_header = mp3_write_header,
  409. .write_packet = mp3_write_packet,
  410. .write_trailer = mp3_write_trailer,
  411. .flags = AVFMT_NOTIMESTAMPS,
  412. .priv_class = &mp3_muxer_class,
  413. };
  414. #endif