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.

439 lines
13KB

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