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.

477 lines
14KB

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