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.

382 lines
11KB

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