mp3enc.c 15 KB

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