mp3enc.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. static int id3v1_set_string(AVFormatContext *s, const char *key,
  38. uint8_t *buf, int buf_size)
  39. {
  40. AVDictionaryEntry *tag;
  41. if ((tag = av_dict_get(s->metadata, key, NULL, 0)))
  42. av_strlcpy(buf, tag->value, buf_size);
  43. return !!tag;
  44. }
  45. static int id3v1_create_tag(AVFormatContext *s, uint8_t *buf)
  46. {
  47. AVDictionaryEntry *tag;
  48. int i, count = 0;
  49. memset(buf, 0, ID3v1_TAG_SIZE); /* fail safe */
  50. buf[0] = 'T';
  51. buf[1] = 'A';
  52. buf[2] = 'G';
  53. /* we knowingly overspecify each tag length by one byte to compensate for the mandatory null byte added by av_strlcpy */
  54. count += id3v1_set_string(s, "TIT2", buf + 3, 30 + 1); //title
  55. count += id3v1_set_string(s, "TPE1", buf + 33, 30 + 1); //author|artist
  56. count += id3v1_set_string(s, "TALB", buf + 63, 30 + 1); //album
  57. count += id3v1_set_string(s, "TDRL", buf + 93, 4 + 1); //date
  58. count += id3v1_set_string(s, "comment", buf + 97, 30 + 1);
  59. if ((tag = av_dict_get(s->metadata, "TRCK", NULL, 0))) { //track
  60. buf[125] = 0;
  61. buf[126] = atoi(tag->value);
  62. count++;
  63. }
  64. buf[127] = 0xFF; /* default to unknown genre */
  65. if ((tag = av_dict_get(s->metadata, "TCON", NULL, 0))) { //genre
  66. for(i = 0; i <= ID3v1_GENRE_MAX; i++) {
  67. if (!av_strcasecmp(tag->value, ff_id3v1_genre_str[i])) {
  68. buf[127] = i;
  69. count++;
  70. break;
  71. }
  72. }
  73. }
  74. return count;
  75. }
  76. #define VBR_NUM_BAGS 400
  77. #define VBR_TOC_SIZE 100
  78. typedef struct MP3Context {
  79. const AVClass *class;
  80. int id3v2_version;
  81. int write_id3v1;
  82. int64_t frames_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[VBR_NUM_BAGS];
  89. } MP3Context;
  90. static int mp2_write_trailer(struct AVFormatContext *s)
  91. {
  92. uint8_t buf[ID3v1_TAG_SIZE];
  93. MP3Context *mp3 = s->priv_data;
  94. /* write the id3v1 tag */
  95. if (mp3 && mp3->write_id3v1 && id3v1_create_tag(s, buf) > 0) {
  96. avio_write(s->pb, buf, ID3v1_TAG_SIZE);
  97. }
  98. /* write number of frames */
  99. if (mp3 && mp3->frames_offset) {
  100. avio_seek(s->pb, mp3->frames_offset, SEEK_SET);
  101. avio_wb32(s->pb, s->streams[0]->nb_frames);
  102. avio_seek(s->pb, 0, SEEK_END);
  103. }
  104. avio_flush(s->pb);
  105. return 0;
  106. }
  107. #if CONFIG_MP2_MUXER
  108. AVOutputFormat ff_mp2_muxer = {
  109. .name = "mp2",
  110. .long_name = NULL_IF_CONFIG_SMALL("MPEG audio layer 2"),
  111. .mime_type = "audio/x-mpeg",
  112. .extensions = "mp2,m2a",
  113. .audio_codec = CODEC_ID_MP2,
  114. .video_codec = CODEC_ID_NONE,
  115. .write_packet = ff_raw_write_packet,
  116. .write_trailer = mp2_write_trailer,
  117. .flags = AVFMT_NOTIMESTAMPS,
  118. };
  119. #endif
  120. #if CONFIG_MP3_MUXER
  121. static const AVOption options[] = {
  122. { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
  123. offsetof(MP3Context, id3v2_version), AV_OPT_TYPE_INT, {.dbl = 4}, 3, 4, AV_OPT_FLAG_ENCODING_PARAM},
  124. { "write_id3v1", "Enable ID3v1 writing. ID3v1 tags are written in UTF-8 which may not be supported by most software.",
  125. offsetof(MP3Context, write_id3v1), AV_OPT_TYPE_INT, {.dbl = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  126. { NULL },
  127. };
  128. static const AVClass mp3_muxer_class = {
  129. .class_name = "MP3 muxer",
  130. .item_name = av_default_item_name,
  131. .option = options,
  132. .version = LIBAVUTIL_VERSION_INT,
  133. };
  134. static const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
  135. /*
  136. * Write an empty XING header and initialize respective data.
  137. */
  138. static int mp3_write_xing(AVFormatContext *s)
  139. {
  140. AVCodecContext *codec = s->streams[0]->codec;
  141. MP3Context *mp3 = s->priv_data;
  142. int bitrate_idx = 3;
  143. int64_t xing_offset;
  144. int32_t mask, header;
  145. MPADecodeHeader c;
  146. int srate_idx, i, channels;
  147. int needed;
  148. for (i = 0; i < FF_ARRAY_ELEMS(avpriv_mpa_freq_tab); i++)
  149. if (avpriv_mpa_freq_tab[i] == codec->sample_rate) {
  150. srate_idx = i;
  151. break;
  152. }
  153. if (i == FF_ARRAY_ELEMS(avpriv_mpa_freq_tab)) {
  154. av_log(s, AV_LOG_ERROR, "Unsupported sample rate.\n");
  155. return -1;
  156. }
  157. switch (codec->channels) {
  158. case 1: channels = MPA_MONO; break;
  159. case 2: channels = MPA_STEREO; break;
  160. default: av_log(s, AV_LOG_ERROR, "Unsupported number of channels.\n"); return -1;
  161. }
  162. /* dummy MPEG audio header */
  163. header = 0xff << 24; // sync
  164. header |= (0x7 << 5 | 0x3 << 3 | 0x1 << 1 | 0x1) << 16; // sync/mpeg-1/layer 3/no crc*/
  165. header |= (srate_idx << 2) << 8;
  166. header |= channels << 6;
  167. for (;;) {
  168. if (15 == bitrate_idx)
  169. return -1;
  170. mask = (bitrate_idx << 4) << 8;
  171. header |= mask;
  172. avpriv_mpegaudio_decode_header(&c, header);
  173. xing_offset=xing_offtbl[c.lsf == 1][c.nb_channels == 1];
  174. needed = 4 // header
  175. + xing_offset
  176. + 4 // xing tag
  177. + 4 // frames/size/toc flags
  178. + 4 // frames
  179. + 4 // size
  180. + VBR_TOC_SIZE; // toc
  181. if (needed <= c.frame_size)
  182. break;
  183. header &= ~mask;
  184. ++bitrate_idx;
  185. }
  186. avio_wb32(s->pb, header);
  187. ffio_fill(s->pb, 0, xing_offset);
  188. avio_wb32(s->pb, MKBETAG('X', 'i', 'n', 'g'));
  189. avio_wb32(s->pb, 0x01 | 0x02 | 0x04); // frames/size/toc
  190. mp3->frames_offset = avio_tell(s->pb);
  191. mp3->size = c.frame_size;
  192. mp3->want=1;
  193. mp3->seen=0;
  194. mp3->pos=0;
  195. avio_wb32(s->pb, 0); // frames
  196. avio_wb32(s->pb, 0); // size
  197. // toc
  198. for (i = 0; i < VBR_TOC_SIZE; ++i)
  199. avio_w8(s->pb, (uint8_t)(255 * i / VBR_TOC_SIZE));
  200. ffio_fill(s->pb, 0, c.frame_size - needed);
  201. avio_flush(s->pb);
  202. return 0;
  203. }
  204. /*
  205. * Add a frame to XING data.
  206. * Following lame's "VbrTag.c".
  207. */
  208. static void mp3_xing_add_frame(AVFormatContext *s, AVPacket *pkt)
  209. {
  210. MP3Context *mp3 = s->priv_data;
  211. int i;
  212. ++mp3->frames;
  213. mp3->size += pkt->size;
  214. if (mp3->want == ++mp3->seen) {
  215. mp3->bag[mp3->pos] = mp3->size;
  216. if (VBR_NUM_BAGS == ++mp3->pos) {
  217. /* shrink table to half size by throwing away each second bag. */
  218. for (i = 1; i < VBR_NUM_BAGS; i += 2)
  219. mp3->bag[i >> 1] = mp3->bag[i];
  220. /* double wanted amount per bag. */
  221. mp3->want <<= 1;
  222. /* adjust current position to half of table size. */
  223. mp3->pos >>= 1;
  224. }
  225. mp3->seen = 0;
  226. }
  227. }
  228. static void mp3_fix_xing(AVFormatContext *s)
  229. {
  230. MP3Context *mp3 = s->priv_data;
  231. int i;
  232. avio_flush(s->pb);
  233. avio_seek(s->pb, mp3->frames_offset, SEEK_SET);
  234. avio_wb32(s->pb, mp3->frames);
  235. avio_wb32(s->pb, mp3->size);
  236. avio_w8(s->pb, 0); // first toc entry has to be zero.
  237. for (i = 1; i < VBR_TOC_SIZE; ++i) {
  238. int j = i * mp3->pos / VBR_TOC_SIZE;
  239. int seek_point = 256LL * mp3->bag[j] / mp3->size;
  240. avio_w8(s->pb, FFMIN(seek_point, 255));
  241. }
  242. avio_flush(s->pb);
  243. avio_seek(s->pb, 0, SEEK_END);
  244. }
  245. /**
  246. * Write an ID3v2 header at beginning of stream
  247. */
  248. static int mp3_write_header(struct AVFormatContext *s)
  249. {
  250. MP3Context *mp3 = s->priv_data;
  251. int ret;
  252. ret = ff_id3v2_write(s, mp3->id3v2_version, ID3v2_DEFAULT_MAGIC);
  253. if (ret < 0)
  254. return ret;
  255. if (s->pb->seekable)
  256. mp3_write_xing(s);
  257. return 0;
  258. }
  259. static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
  260. {
  261. if (! pkt || ! pkt->data || pkt->size < 4)
  262. return ff_raw_write_packet(s, pkt);
  263. else {
  264. MP3Context *mp3 = s->priv_data;
  265. #ifdef FILTER_VBR_HEADERS
  266. MPADecodeHeader c;
  267. int base;
  268. ff_mpegaudio_decode_header(&c, AV_RB32(pkt->data));
  269. /* filter out XING and INFO headers. */
  270. base = 4 + xing_offtbl[c.lsf == 1][c.nb_channels == 1];
  271. if (base + 4 <= pkt->size) {
  272. uint32_t v = AV_RB32(pkt->data + base);
  273. if (MKBETAG('X','i','n','g') == v || MKBETAG('I','n','f','o') == v)
  274. return 0;
  275. }
  276. /* filter out VBRI headers. */
  277. base = 4 + 32;
  278. if (base + 4 <= pkt->size && MKBETAG('V','B','R','I') == AV_RB32(pkt->data + base))
  279. return 0;
  280. #endif
  281. if (mp3->frames_offset)
  282. mp3_xing_add_frame(s, pkt);
  283. return ff_raw_write_packet(s, pkt);
  284. }
  285. }
  286. static int mp3_write_trailer(AVFormatContext *s)
  287. {
  288. MP3Context *mp3 = s->priv_data;
  289. int ret=mp2_write_trailer(s);
  290. if (ret < 0)
  291. return ret;
  292. if (mp3->frames_offset)
  293. mp3_fix_xing(s);
  294. return 0;
  295. }
  296. AVOutputFormat ff_mp3_muxer = {
  297. .name = "mp3",
  298. .long_name = NULL_IF_CONFIG_SMALL("MPEG audio layer 3"),
  299. .mime_type = "audio/x-mpeg",
  300. .extensions = "mp3",
  301. .priv_data_size = sizeof(MP3Context),
  302. .audio_codec = CODEC_ID_MP3,
  303. .video_codec = CODEC_ID_NONE,
  304. .write_header = mp3_write_header,
  305. .write_packet = mp3_write_packet,
  306. .write_trailer = mp3_write_trailer,
  307. .flags = AVFMT_NOTIMESTAMPS,
  308. .priv_class = &mp3_muxer_class,
  309. };
  310. #endif