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.

469 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. struct xing_header {
  150. int64_t offset;
  151. int32_t frames;
  152. int32_t size;
  153. /* following lame's "VbrTag.c". */
  154. struct xing_toc {
  155. uint32_t want;
  156. uint32_t seen;
  157. uint32_t pos;
  158. uint64_t bag[VBR_NUM_BAGS];
  159. } toc;
  160. } xing_header;
  161. } MP3Context;
  162. static const AVOption options[] = {
  163. { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
  164. offsetof(MP3Context, id3v2_version), FF_OPT_TYPE_INT, {.dbl = 4}, 3, 4, AV_OPT_FLAG_ENCODING_PARAM},
  165. { NULL },
  166. };
  167. static const AVClass mp3_muxer_class = {
  168. .class_name = "MP3 muxer",
  169. .item_name = av_default_item_name,
  170. .option = options,
  171. .version = LIBAVUTIL_VERSION_INT,
  172. };
  173. static int id3v2_check_write_tag(AVFormatContext *s, AVMetadataTag *t, const char table[][4],
  174. enum ID3v2Encoding enc)
  175. {
  176. uint32_t tag;
  177. int i;
  178. if (t->key[0] != 'T' || strlen(t->key) != 4)
  179. return -1;
  180. tag = AV_RB32(t->key);
  181. for (i = 0; *table[i]; i++)
  182. if (tag == AV_RB32(table[i]))
  183. return id3v2_put_ttag(s, t->value, NULL, tag, enc);
  184. return -1;
  185. }
  186. static const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
  187. /*
  188. * Write an empty XING header and initialize respective data.
  189. */
  190. static int mp3_write_xing(AVFormatContext *s)
  191. {
  192. AVCodecContext *codec = s->streams[0]->codec;
  193. MP3Context *mp3 = s->priv_data;
  194. int bitrate_idx = 3;
  195. int64_t xing_offset;
  196. int32_t mask, header;
  197. MPADecodeHeader c;
  198. int srate_idx, i, channels;
  199. int needed;
  200. for (i = 0; i < FF_ARRAY_ELEMS(ff_mpa_freq_tab); i++)
  201. if (ff_mpa_freq_tab[i] == codec->sample_rate) {
  202. srate_idx = i;
  203. break;
  204. }
  205. if (i == FF_ARRAY_ELEMS(ff_mpa_freq_tab)) {
  206. av_log(s, AV_LOG_ERROR, "Unsupported sample rate.\n");
  207. return -1;
  208. }
  209. switch (codec->channels) {
  210. case 1: channels = MPA_MONO; break;
  211. case 2: channels = MPA_STEREO; break;
  212. default: av_log(s, AV_LOG_ERROR, "Unsupported number of channels.\n"); return -1;
  213. }
  214. /* dummy MPEG audio header */
  215. header = 0xff << 24; // sync
  216. header |= (0x7 << 5 | 0x3 << 3 | 0x1 << 1 | 0x1) << 16; // sync/mpeg-1/layer 3/no crc*/
  217. header |= (srate_idx << 2) << 8;
  218. header |= channels << 6;
  219. for (;;) {
  220. if (15 == bitrate_idx)
  221. return -1;
  222. mask = (bitrate_idx << 4) << 8;
  223. header |= mask;
  224. ff_mpegaudio_decode_header(&c, header);
  225. xing_offset=xing_offtbl[c.lsf == 1][c.nb_channels == 1];
  226. needed = 4 // header
  227. + xing_offset
  228. + 4 // xing tag
  229. + 4 // frames/size/toc flags
  230. + 4 // frames
  231. + 4 // size
  232. + VBR_TOC_SIZE; // toc
  233. if (needed <= c.frame_size)
  234. break;
  235. header &= ~mask;
  236. ++bitrate_idx;
  237. }
  238. avio_wb32(s->pb, header);
  239. ffio_fill(s->pb, 0, xing_offset);
  240. avio_wb32(s->pb, MKBETAG('X', 'i', 'n', 'g'));
  241. avio_wb32(s->pb, 0x01 | 0x02 | 0x04); // frames/size/toc
  242. mp3->xing_header.offset = avio_tell(s->pb);
  243. mp3->xing_header.size = c.frame_size;
  244. mp3->xing_header.toc.want=1;
  245. mp3->xing_header.toc.seen=0;
  246. mp3->xing_header.toc.pos=0;
  247. avio_wb32(s->pb, 0); // frames
  248. avio_wb32(s->pb, 0); // size
  249. // toc
  250. for (i = 0; i < VBR_TOC_SIZE; ++i)
  251. avio_w8(s->pb, (uint8_t)(255 * i / VBR_TOC_SIZE));
  252. ffio_fill(s->pb, 0, c.frame_size - needed);
  253. avio_flush(s->pb);
  254. return 0;
  255. }
  256. /*
  257. * Add a frame to XING data.
  258. * Following lame's "VbrTag.c".
  259. */
  260. static void mp3_xing_add_frame(AVFormatContext *s, AVPacket *pkt)
  261. {
  262. MP3Context *mp3 = s->priv_data;
  263. struct xing_header *xing_header = &mp3->xing_header;
  264. struct xing_toc *toc = &xing_header->toc;
  265. int i;
  266. ++xing_header->frames;
  267. xing_header->size += pkt->size;
  268. if (toc->want == ++toc->seen) {
  269. toc->bag[toc->pos] = xing_header->size;
  270. if (VBR_NUM_BAGS == ++toc->pos) {
  271. /* shrink table to half size by throwing away each second bag. */
  272. for (i = 1; i < VBR_NUM_BAGS; i += 2)
  273. toc->bag[i >> 1] = toc->bag[i];
  274. /* double wanted amount per bag. */
  275. toc->want <<= 1;
  276. /* adjust current position to half of table size. */
  277. toc->pos >>= 1;
  278. }
  279. toc->seen = 0;
  280. }
  281. }
  282. static void mp3_fix_xing(AVFormatContext *s)
  283. {
  284. MP3Context *mp3 = s->priv_data;
  285. struct xing_header *xing_header = &mp3->xing_header;
  286. struct xing_toc *toc = &xing_header->toc;
  287. double scale = (double)toc->pos / (double)VBR_TOC_SIZE;
  288. int i;
  289. avio_flush(s->pb);
  290. avio_seek(s->pb, xing_header->offset, SEEK_SET);
  291. avio_wb32(s->pb, xing_header->frames);
  292. avio_wb32(s->pb, xing_header->size);
  293. avio_w8(s->pb, 0); // first toc entry has to be zero.
  294. for (i = 1; i < VBR_TOC_SIZE; ++i) {
  295. int j = (int)floor(scale * i);
  296. int seek_point = (int)floor(256.0 * toc->bag[j] / xing_header->size);
  297. avio_w8(s->pb, (uint8_t)(seek_point < 256 ? seek_point : 255));
  298. }
  299. avio_flush(s->pb);
  300. avio_seek(s->pb, 0, SEEK_END);
  301. }
  302. /**
  303. * Write an ID3v2 header at beginning of stream
  304. */
  305. static int mp3_write_header(struct AVFormatContext *s)
  306. {
  307. MP3Context *mp3 = s->priv_data;
  308. AVMetadataTag *t = NULL;
  309. int totlen = 0, enc = mp3->id3v2_version == 3 ? ID3v2_ENCODING_UTF16BOM :
  310. ID3v2_ENCODING_UTF8;
  311. int64_t size_pos, cur_pos;
  312. avio_wb32(s->pb, MKBETAG('I', 'D', '3', mp3->id3v2_version));
  313. avio_w8(s->pb, 0);
  314. avio_w8(s->pb, 0); /* flags */
  315. /* reserve space for size */
  316. size_pos = avio_tell(s->pb);
  317. avio_wb32(s->pb, 0);
  318. ff_metadata_conv(&s->metadata, ff_id3v2_34_metadata_conv, NULL);
  319. if (mp3->id3v2_version == 4)
  320. ff_metadata_conv(&s->metadata, ff_id3v2_4_metadata_conv, NULL);
  321. while ((t = av_metadata_get(s->metadata, "", t, AV_METADATA_IGNORE_SUFFIX))) {
  322. int ret;
  323. if ((ret = id3v2_check_write_tag(s, t, ff_id3v2_tags, enc)) > 0) {
  324. totlen += ret;
  325. continue;
  326. }
  327. if ((ret = id3v2_check_write_tag(s, t, mp3->id3v2_version == 3 ?
  328. ff_id3v2_3_tags : ff_id3v2_4_tags, enc)) > 0) {
  329. totlen += ret;
  330. continue;
  331. }
  332. /* unknown tag, write as TXXX frame */
  333. if ((ret = id3v2_put_ttag(s, t->key, t->value, MKBETAG('T', 'X', 'X', 'X'), enc)) < 0)
  334. return ret;
  335. totlen += ret;
  336. }
  337. cur_pos = avio_tell(s->pb);
  338. avio_seek(s->pb, size_pos, SEEK_SET);
  339. id3v2_put_size(s, totlen);
  340. avio_seek(s->pb, cur_pos, SEEK_SET);
  341. if (s->pb->seekable)
  342. mp3_write_xing(s);
  343. return 0;
  344. }
  345. static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
  346. {
  347. if (! pkt || ! pkt->data || pkt->size < 4)
  348. return ff_raw_write_packet(s, pkt);
  349. else {
  350. MP3Context *mp3 = s->priv_data;
  351. MPADecodeHeader c;
  352. int base;
  353. #ifdef FILTER_VBR_HEADERS
  354. ff_mpegaudio_decode_header(&c, AV_RB32(pkt->data));
  355. /* filter out XING and INFO headers. */
  356. base = 4 + xing_offtbl[c.lsf == 1][c.nb_channels == 1];
  357. if (base + 4 <= pkt->size) {
  358. uint32_t v = AV_RB32(pkt->data + base);
  359. if (MKBETAG('X','i','n','g') == v || MKBETAG('I','n','f','o') == v)
  360. return 0;
  361. }
  362. /* filter out VBRI headers. */
  363. base = 4 + 32;
  364. if (base + 4 <= pkt->size && MKBETAG('V','B','R','I') == AV_RB32(pkt->data + base))
  365. return 0;
  366. #endif
  367. if (0 < mp3->xing_header.offset)
  368. mp3_xing_add_frame(s, pkt);
  369. return ff_raw_write_packet(s, pkt);
  370. }
  371. }
  372. static int mp3_write_trailer(AVFormatContext *s)
  373. {
  374. MP3Context *mp3 = s->priv_data;
  375. int ret=mp2_write_trailer(s);
  376. if (ret < 0)
  377. return ret;
  378. if (0 < mp3->xing_header.offset)
  379. mp3_fix_xing(s);
  380. return 0;
  381. }
  382. AVOutputFormat ff_mp3_muxer = {
  383. "mp3",
  384. NULL_IF_CONFIG_SMALL("MPEG audio layer 3"),
  385. "audio/x-mpeg",
  386. "mp3",
  387. sizeof(MP3Context),
  388. CODEC_ID_MP3,
  389. CODEC_ID_NONE,
  390. mp3_write_header,
  391. mp3_write_packet,
  392. mp3_write_trailer,
  393. AVFMT_NOTIMESTAMPS,
  394. .priv_class = &mp3_muxer_class,
  395. };
  396. #endif