mp3enc.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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 <strings.h>
  22. #include "avformat.h"
  23. #include "id3v1.h"
  24. #include "id3v2.h"
  25. #include "rawenc.h"
  26. #include "libavutil/avstring.h"
  27. #include "libavutil/intreadwrite.h"
  28. #include "libavutil/opt.h"
  29. #include "libavcodec/mpegaudio.h"
  30. #include "libavcodec/mpegaudiodata.h"
  31. #include "libavcodec/mpegaudiodecheader.h"
  32. #include "libavformat/avio_internal.h"
  33. #include "libavutil/dict.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. /* we knowingly overspecify each tag length by one byte to compensate for the mandatory null byte added by av_strlcpy */
  51. count += id3v1_set_string(s, "TIT2", buf + 3, 30 + 1); //title
  52. count += id3v1_set_string(s, "TPE1", buf + 33, 30 + 1); //author|artist
  53. count += id3v1_set_string(s, "TALB", buf + 63, 30 + 1); //album
  54. count += id3v1_set_string(s, "TDRL", buf + 93, 4 + 1); //date
  55. count += id3v1_set_string(s, "comment", buf + 97, 30 + 1);
  56. if ((tag = av_dict_get(s->metadata, "TRCK", NULL, 0))) { //track
  57. buf[125] = 0;
  58. buf[126] = atoi(tag->value);
  59. count++;
  60. }
  61. buf[127] = 0xFF; /* default to unknown genre */
  62. if ((tag = av_dict_get(s->metadata, "TCON", NULL, 0))) { //genre
  63. for(i = 0; i <= ID3v1_GENRE_MAX; i++) {
  64. if (!strcasecmp(tag->value, ff_id3v1_genre_str[i])) {
  65. buf[127] = i;
  66. count++;
  67. break;
  68. }
  69. }
  70. }
  71. return count;
  72. }
  73. /* simple formats */
  74. static void id3v2_put_size(AVFormatContext *s, int size)
  75. {
  76. avio_w8(s->pb, size >> 21 & 0x7f);
  77. avio_w8(s->pb, size >> 14 & 0x7f);
  78. avio_w8(s->pb, size >> 7 & 0x7f);
  79. avio_w8(s->pb, size & 0x7f);
  80. }
  81. static int string_is_ascii(const uint8_t *str)
  82. {
  83. while (*str && *str < 128) str++;
  84. return !*str;
  85. }
  86. /**
  87. * Write a text frame with one (normal frames) or two (TXXX frames) strings
  88. * according to encoding (only UTF-8 or UTF-16+BOM supported).
  89. * @return number of bytes written or a negative error code.
  90. */
  91. static int id3v2_put_ttag(AVFormatContext *s, const char *str1, const char *str2,
  92. uint32_t tag, enum ID3v2Encoding enc)
  93. {
  94. int len;
  95. uint8_t *pb;
  96. int (*put)(AVIOContext*, const char*);
  97. AVIOContext *dyn_buf;
  98. if (avio_open_dyn_buf(&dyn_buf) < 0)
  99. return AVERROR(ENOMEM);
  100. /* check if the strings are ASCII-only and use UTF16 only if
  101. * they're not */
  102. if (enc == ID3v2_ENCODING_UTF16BOM && string_is_ascii(str1) &&
  103. (!str2 || string_is_ascii(str2)))
  104. enc = ID3v2_ENCODING_ISO8859;
  105. avio_w8(dyn_buf, enc);
  106. if (enc == ID3v2_ENCODING_UTF16BOM) {
  107. avio_wl16(dyn_buf, 0xFEFF); /* BOM */
  108. put = avio_put_str16le;
  109. } else
  110. put = avio_put_str;
  111. put(dyn_buf, str1);
  112. if (str2)
  113. put(dyn_buf, str2);
  114. len = avio_close_dyn_buf(dyn_buf, &pb);
  115. avio_wb32(s->pb, tag);
  116. id3v2_put_size(s, len);
  117. avio_wb16(s->pb, 0);
  118. avio_write(s->pb, pb, len);
  119. av_freep(&pb);
  120. return len + ID3v2_HEADER_SIZE;
  121. }
  122. static int mp2_write_trailer(struct AVFormatContext *s)
  123. {
  124. uint8_t buf[ID3v1_TAG_SIZE];
  125. /* write the id3v1 tag */
  126. if (id3v1_create_tag(s, buf) > 0) {
  127. avio_write(s->pb, buf, ID3v1_TAG_SIZE);
  128. avio_flush(s->pb);
  129. }
  130. return 0;
  131. }
  132. #if CONFIG_MP2_MUXER
  133. AVOutputFormat ff_mp2_muxer = {
  134. "mp2",
  135. NULL_IF_CONFIG_SMALL("MPEG audio layer 2"),
  136. "audio/x-mpeg",
  137. "mp2,m2a",
  138. 0,
  139. CODEC_ID_MP2,
  140. CODEC_ID_NONE,
  141. NULL,
  142. ff_raw_write_packet,
  143. mp2_write_trailer,
  144. };
  145. #endif
  146. #if CONFIG_MP3_MUXER
  147. #define VBR_NUM_BAGS 400
  148. #define VBR_TOC_SIZE 100
  149. typedef struct MP3Context {
  150. const AVClass *class;
  151. int id3v2_version;
  152. int64_t frames_offset;
  153. int32_t frames;
  154. int32_t size;
  155. uint32_t want;
  156. uint32_t seen;
  157. uint32_t pos;
  158. uint64_t bag[VBR_NUM_BAGS];
  159. } MP3Context;
  160. static const AVOption options[] = {
  161. { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
  162. offsetof(MP3Context, id3v2_version), FF_OPT_TYPE_INT, {.dbl = 4}, 3, 4, AV_OPT_FLAG_ENCODING_PARAM},
  163. { NULL },
  164. };
  165. static const AVClass mp3_muxer_class = {
  166. .class_name = "MP3 muxer",
  167. .item_name = av_default_item_name,
  168. .option = options,
  169. .version = LIBAVUTIL_VERSION_INT,
  170. };
  171. static int id3v2_check_write_tag(AVFormatContext *s, AVDictionaryEntry *t, const char table[][4],
  172. enum ID3v2Encoding enc)
  173. {
  174. uint32_t tag;
  175. int i;
  176. if (t->key[0] != 'T' || strlen(t->key) != 4)
  177. return -1;
  178. tag = AV_RB32(t->key);
  179. for (i = 0; *table[i]; i++)
  180. if (tag == AV_RB32(table[i]))
  181. return id3v2_put_ttag(s, t->value, NULL, tag, enc);
  182. return -1;
  183. }
  184. static const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
  185. /*
  186. * Write an empty XING header and initialize respective data.
  187. */
  188. static int mp3_write_xing(AVFormatContext *s)
  189. {
  190. AVCodecContext *codec = s->streams[0]->codec;
  191. MP3Context *mp3 = s->priv_data;
  192. int bitrate_idx = 3;
  193. int64_t xing_offset;
  194. int32_t mask, header;
  195. MPADecodeHeader c;
  196. int srate_idx, i, channels;
  197. int needed;
  198. for (i = 0; i < FF_ARRAY_ELEMS(ff_mpa_freq_tab); i++)
  199. if (ff_mpa_freq_tab[i] == codec->sample_rate) {
  200. srate_idx = i;
  201. break;
  202. }
  203. if (i == FF_ARRAY_ELEMS(ff_mpa_freq_tab)) {
  204. av_log(s, AV_LOG_ERROR, "Unsupported sample rate.\n");
  205. return -1;
  206. }
  207. switch (codec->channels) {
  208. case 1: channels = MPA_MONO; break;
  209. case 2: channels = MPA_STEREO; break;
  210. default: av_log(s, AV_LOG_ERROR, "Unsupported number of channels.\n"); return -1;
  211. }
  212. /* dummy MPEG audio header */
  213. header = 0xff << 24; // sync
  214. header |= (0x7 << 5 | 0x3 << 3 | 0x1 << 1 | 0x1) << 16; // sync/mpeg-1/layer 3/no crc*/
  215. header |= (srate_idx << 2) << 8;
  216. header |= channels << 6;
  217. for (;;) {
  218. if (15 == bitrate_idx)
  219. return -1;
  220. mask = (bitrate_idx << 4) << 8;
  221. header |= mask;
  222. ff_mpegaudio_decode_header(&c, header);
  223. xing_offset=xing_offtbl[c.lsf == 1][c.nb_channels == 1];
  224. needed = 4 // header
  225. + xing_offset
  226. + 4 // xing tag
  227. + 4 // frames/size/toc flags
  228. + 4 // frames
  229. + 4 // size
  230. + VBR_TOC_SIZE; // toc
  231. if (needed <= c.frame_size)
  232. break;
  233. header &= ~mask;
  234. ++bitrate_idx;
  235. }
  236. avio_wb32(s->pb, header);
  237. ffio_fill(s->pb, 0, xing_offset);
  238. avio_wb32(s->pb, MKBETAG('X', 'i', 'n', 'g'));
  239. avio_wb32(s->pb, 0x01 | 0x02 | 0x04); // frames/size/toc
  240. mp3->frames_offset = avio_tell(s->pb);
  241. mp3->size = c.frame_size;
  242. mp3->want=1;
  243. mp3->seen=0;
  244. mp3->pos=0;
  245. avio_wb32(s->pb, 0); // frames
  246. avio_wb32(s->pb, 0); // size
  247. // toc
  248. for (i = 0; i < VBR_TOC_SIZE; ++i)
  249. avio_w8(s->pb, (uint8_t)(255 * i / VBR_TOC_SIZE));
  250. ffio_fill(s->pb, 0, c.frame_size - needed);
  251. avio_flush(s->pb);
  252. return 0;
  253. }
  254. /*
  255. * Add a frame to XING data.
  256. * Following lame's "VbrTag.c".
  257. */
  258. static void mp3_xing_add_frame(AVFormatContext *s, AVPacket *pkt)
  259. {
  260. MP3Context *mp3 = s->priv_data;
  261. int i;
  262. ++mp3->frames;
  263. mp3->size += pkt->size;
  264. if (mp3->want == ++mp3->seen) {
  265. mp3->bag[mp3->pos] = mp3->size;
  266. if (VBR_NUM_BAGS == ++mp3->pos) {
  267. /* shrink table to half size by throwing away each second bag. */
  268. for (i = 1; i < VBR_NUM_BAGS; i += 2)
  269. mp3->bag[i >> 1] = mp3->bag[i];
  270. /* double wanted amount per bag. */
  271. mp3->want <<= 1;
  272. /* adjust current position to half of table size. */
  273. mp3->pos >>= 1;
  274. }
  275. mp3->seen = 0;
  276. }
  277. }
  278. static void mp3_fix_xing(AVFormatContext *s)
  279. {
  280. MP3Context *mp3 = s->priv_data;
  281. int i;
  282. avio_flush(s->pb);
  283. avio_seek(s->pb, mp3->frames_offset, SEEK_SET);
  284. avio_wb32(s->pb, mp3->frames);
  285. avio_wb32(s->pb, mp3->size);
  286. avio_w8(s->pb, 0); // first toc entry has to be zero.
  287. for (i = 1; i < VBR_TOC_SIZE; ++i) {
  288. int j = i * mp3->pos / VBR_TOC_SIZE;
  289. int seek_point = 256LL * mp3->bag[j] / mp3->size;
  290. avio_w8(s->pb, FFMIN(seek_point, 255));
  291. }
  292. avio_flush(s->pb);
  293. avio_seek(s->pb, 0, SEEK_END);
  294. }
  295. /**
  296. * Write an ID3v2 header at beginning of stream
  297. */
  298. static int mp3_write_header(struct AVFormatContext *s)
  299. {
  300. MP3Context *mp3 = s->priv_data;
  301. AVDictionaryEntry *t = NULL;
  302. int totlen = 0, enc = mp3->id3v2_version == 3 ? ID3v2_ENCODING_UTF16BOM :
  303. ID3v2_ENCODING_UTF8;
  304. int64_t size_pos, cur_pos;
  305. avio_wb32(s->pb, MKBETAG('I', 'D', '3', mp3->id3v2_version));
  306. avio_w8(s->pb, 0);
  307. avio_w8(s->pb, 0); /* flags */
  308. /* reserve space for size */
  309. size_pos = avio_tell(s->pb);
  310. avio_wb32(s->pb, 0);
  311. ff_metadata_conv(&s->metadata, ff_id3v2_34_metadata_conv, NULL);
  312. if (mp3->id3v2_version == 4)
  313. ff_metadata_conv(&s->metadata, ff_id3v2_4_metadata_conv, NULL);
  314. while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX))) {
  315. int ret;
  316. if ((ret = id3v2_check_write_tag(s, t, ff_id3v2_tags, enc)) > 0) {
  317. totlen += ret;
  318. continue;
  319. }
  320. if ((ret = id3v2_check_write_tag(s, t, mp3->id3v2_version == 3 ?
  321. ff_id3v2_3_tags : ff_id3v2_4_tags, enc)) > 0) {
  322. totlen += ret;
  323. continue;
  324. }
  325. /* unknown tag, write as TXXX frame */
  326. if ((ret = id3v2_put_ttag(s, t->key, t->value, MKBETAG('T', 'X', 'X', 'X'), enc)) < 0)
  327. return ret;
  328. totlen += ret;
  329. }
  330. cur_pos = avio_tell(s->pb);
  331. avio_seek(s->pb, size_pos, SEEK_SET);
  332. id3v2_put_size(s, totlen);
  333. avio_seek(s->pb, cur_pos, SEEK_SET);
  334. if (s->pb->seekable)
  335. mp3_write_xing(s);
  336. return 0;
  337. }
  338. static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
  339. {
  340. if (! pkt || ! pkt->data || pkt->size < 4)
  341. return ff_raw_write_packet(s, pkt);
  342. else {
  343. MP3Context *mp3 = s->priv_data;
  344. #ifdef FILTER_VBR_HEADERS
  345. MPADecodeHeader c;
  346. int base;
  347. ff_mpegaudio_decode_header(&c, AV_RB32(pkt->data));
  348. /* filter out XING and INFO headers. */
  349. base = 4 + xing_offtbl[c.lsf == 1][c.nb_channels == 1];
  350. if (base + 4 <= pkt->size) {
  351. uint32_t v = AV_RB32(pkt->data + base);
  352. if (MKBETAG('X','i','n','g') == v || MKBETAG('I','n','f','o') == v)
  353. return 0;
  354. }
  355. /* filter out VBRI headers. */
  356. base = 4 + 32;
  357. if (base + 4 <= pkt->size && MKBETAG('V','B','R','I') == AV_RB32(pkt->data + base))
  358. return 0;
  359. #endif
  360. if (mp3->frames_offset)
  361. mp3_xing_add_frame(s, pkt);
  362. return ff_raw_write_packet(s, pkt);
  363. }
  364. }
  365. static int mp3_write_trailer(AVFormatContext *s)
  366. {
  367. MP3Context *mp3 = s->priv_data;
  368. int ret=mp2_write_trailer(s);
  369. if (ret < 0)
  370. return ret;
  371. if (mp3->frames_offset)
  372. mp3_fix_xing(s);
  373. return 0;
  374. }
  375. AVOutputFormat ff_mp3_muxer = {
  376. "mp3",
  377. NULL_IF_CONFIG_SMALL("MPEG audio layer 3"),
  378. "audio/x-mpeg",
  379. "mp3",
  380. sizeof(MP3Context),
  381. CODEC_ID_MP3,
  382. CODEC_ID_NONE,
  383. mp3_write_header,
  384. mp3_write_packet,
  385. mp3_write_trailer,
  386. AVFMT_NOTIMESTAMPS,
  387. .priv_class = &mp3_muxer_class,
  388. };
  389. #endif