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.

459 lines
13KB

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