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.

542 lines
17KB

  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 "libavutil/dict.h"
  33. #include "libavutil/avassert.h"
  34. static int id3v1_set_string(AVFormatContext *s, const char *key,
  35. uint8_t *buf, int buf_size)
  36. {
  37. AVDictionaryEntry *tag;
  38. if ((tag = av_dict_get(s->metadata, key, NULL, 0)))
  39. av_strlcpy(buf, tag->value, buf_size);
  40. return !!tag;
  41. }
  42. static int id3v1_create_tag(AVFormatContext *s, uint8_t *buf)
  43. {
  44. AVDictionaryEntry *tag;
  45. int i, count = 0;
  46. memset(buf, 0, ID3v1_TAG_SIZE); /* fail safe */
  47. buf[0] = 'T';
  48. buf[1] = 'A';
  49. buf[2] = 'G';
  50. /* we knowingly overspecify each tag length by one byte to compensate for the mandatory null byte added by av_strlcpy */
  51. count += id3v1_set_string(s, "TIT2", buf + 3, 30 + 1); //title
  52. count += id3v1_set_string(s, "TPE1", buf + 33, 30 + 1); //author|artist
  53. count += id3v1_set_string(s, "TALB", buf + 63, 30 + 1); //album
  54. count += id3v1_set_string(s, "TDRL", buf + 93, 4 + 1); //date
  55. count += id3v1_set_string(s, "comment", buf + 97, 30 + 1);
  56. if ((tag = av_dict_get(s->metadata, "TRCK", NULL, 0))) { //track
  57. buf[125] = 0;
  58. buf[126] = atoi(tag->value);
  59. count++;
  60. }
  61. buf[127] = 0xFF; /* default to unknown genre */
  62. if ((tag = av_dict_get(s->metadata, "TCON", NULL, 0))) { //genre
  63. for(i = 0; i <= ID3v1_GENRE_MAX; i++) {
  64. if (!av_strcasecmp(tag->value, ff_id3v1_genre_str[i])) {
  65. buf[127] = i;
  66. count++;
  67. break;
  68. }
  69. }
  70. }
  71. return count;
  72. }
  73. #define XING_NUM_BAGS 400
  74. #define XING_TOC_SIZE 100
  75. // maximum size of the xing frame: offset/Xing/flags/frames/size/TOC
  76. #define XING_MAX_SIZE (32 + 4 + 4 + 4 + 4 + XING_TOC_SIZE)
  77. typedef struct MP3Context {
  78. const AVClass *class;
  79. ID3v2EncContext id3;
  80. int id3v2_version;
  81. int write_id3v1;
  82. int write_xing;
  83. /* xing header */
  84. int64_t xing_offset;
  85. int32_t frames;
  86. int32_t size;
  87. uint32_t want;
  88. uint32_t seen;
  89. uint32_t pos;
  90. uint64_t bag[XING_NUM_BAGS];
  91. int initial_bitrate;
  92. int has_variable_bitrate;
  93. /* index of the audio stream */
  94. int audio_stream_idx;
  95. /* number of attached pictures we still need to write */
  96. int pics_to_write;
  97. /* audio packets are queued here until we get all the attached pictures */
  98. AVPacketList *queue, *queue_end;
  99. } MP3Context;
  100. static const uint8_t xing_offtbl[2][2] = {{32, 17}, {17, 9}};
  101. /*
  102. * Write an empty XING header and initialize respective data.
  103. */
  104. static int mp3_write_xing(AVFormatContext *s)
  105. {
  106. MP3Context *mp3 = s->priv_data;
  107. AVCodecContext *codec = s->streams[mp3->audio_stream_idx]->codec;
  108. int32_t header;
  109. MPADecodeHeader mpah;
  110. int srate_idx, i, channels;
  111. int bitrate_idx;
  112. int best_bitrate_idx = -1;
  113. int best_bitrate_error = INT_MAX;
  114. int xing_offset;
  115. int ver = 0;
  116. int bytes_needed;
  117. const char *vendor = (s->flags & AVFMT_FLAG_BITEXACT) ? "Lavf" : LIBAVFORMAT_IDENT;
  118. if (!s->pb->seekable || !mp3->write_xing)
  119. return 0;
  120. for (i = 0; i < FF_ARRAY_ELEMS(avpriv_mpa_freq_tab); i++) {
  121. const uint16_t base_freq = avpriv_mpa_freq_tab[i];
  122. if (codec->sample_rate == base_freq) ver = 0x3; // MPEG 1
  123. else if (codec->sample_rate == base_freq / 2) ver = 0x2; // MPEG 2
  124. else if (codec->sample_rate == base_freq / 4) ver = 0x0; // MPEG 2.5
  125. else continue;
  126. srate_idx = i;
  127. break;
  128. }
  129. if (i == FF_ARRAY_ELEMS(avpriv_mpa_freq_tab)) {
  130. av_log(s, AV_LOG_WARNING, "Unsupported sample rate, not writing Xing header.\n");
  131. return -1;
  132. }
  133. switch (codec->channels) {
  134. case 1: channels = MPA_MONO; break;
  135. case 2: channels = MPA_STEREO; break;
  136. default: av_log(s, AV_LOG_WARNING, "Unsupported number of channels, "
  137. "not writing Xing header.\n");
  138. return -1;
  139. }
  140. /* dummy MPEG audio header */
  141. header = 0xffU << 24; // sync
  142. header |= (0x7 << 5 | ver << 3 | 0x1 << 1 | 0x1) << 16; // sync/audio-version/layer 3/no crc*/
  143. header |= (srate_idx << 2) << 8;
  144. header |= channels << 6;
  145. for (bitrate_idx = 1; bitrate_idx < 15; bitrate_idx++) {
  146. int bit_rate = 1000 * avpriv_mpa_bitrate_tab[ver != 3][3 - 1][bitrate_idx];
  147. int error = FFABS(bit_rate - codec->bit_rate);
  148. if (error < best_bitrate_error) {
  149. best_bitrate_error = error;
  150. best_bitrate_idx = bitrate_idx;
  151. }
  152. }
  153. av_assert0(best_bitrate_idx >= 0);
  154. for (bitrate_idx = best_bitrate_idx; ; bitrate_idx++) {
  155. int32_t mask = bitrate_idx << (4 + 8);
  156. if (15 == bitrate_idx)
  157. return -1;
  158. header |= mask;
  159. avpriv_mpegaudio_decode_header(&mpah, header);
  160. xing_offset=xing_offtbl[mpah.lsf == 1][mpah.nb_channels == 1];
  161. bytes_needed = 4 // header
  162. + xing_offset
  163. + 4 // xing tag
  164. + 4 // frames/size/toc flags
  165. + 4 // frames
  166. + 4 // size
  167. + XING_TOC_SIZE // toc
  168. + 24
  169. ;
  170. if (bytes_needed <= mpah.frame_size)
  171. break;
  172. header &= ~mask;
  173. }
  174. avio_wb32(s->pb, header);
  175. ffio_fill(s->pb, 0, xing_offset);
  176. mp3->xing_offset = avio_tell(s->pb);
  177. ffio_wfourcc(s->pb, "Xing");
  178. avio_wb32(s->pb, 0x01 | 0x02 | 0x04); // frames / size / TOC
  179. mp3->size = mpah.frame_size;
  180. mp3->want=1;
  181. mp3->seen=0;
  182. mp3->pos=0;
  183. avio_wb32(s->pb, 0); // frames
  184. avio_wb32(s->pb, 0); // size
  185. // toc
  186. for (i = 0; i < XING_TOC_SIZE; ++i)
  187. avio_w8(s->pb, (uint8_t)(255 * i / XING_TOC_SIZE));
  188. for (i = 0; i < strlen(vendor); ++i)
  189. avio_w8(s->pb, vendor[i]);
  190. for (; i < 21; ++i)
  191. avio_w8(s->pb, 0);
  192. avio_wb24(s->pb, FFMAX(codec->delay - 528 - 1, 0)<<12);
  193. ffio_fill(s->pb, 0, mpah.frame_size - bytes_needed);
  194. return 0;
  195. }
  196. /*
  197. * Add a frame to XING data.
  198. * Following lame's "VbrTag.c".
  199. */
  200. static void mp3_xing_add_frame(MP3Context *mp3, AVPacket *pkt)
  201. {
  202. int i;
  203. mp3->frames++;
  204. mp3->seen++;
  205. mp3->size += pkt->size;
  206. if (mp3->want == mp3->seen) {
  207. mp3->bag[mp3->pos] = mp3->size;
  208. if (XING_NUM_BAGS == ++mp3->pos) {
  209. /* shrink table to half size by throwing away each second bag. */
  210. for (i = 1; i < XING_NUM_BAGS; i += 2)
  211. mp3->bag[i >> 1] = mp3->bag[i];
  212. /* double wanted amount per bag. */
  213. mp3->want *= 2;
  214. /* adjust current position to half of table size. */
  215. mp3->pos = XING_NUM_BAGS / 2;
  216. }
  217. mp3->seen = 0;
  218. }
  219. }
  220. static int mp3_write_audio_packet(AVFormatContext *s, AVPacket *pkt)
  221. {
  222. MP3Context *mp3 = s->priv_data;
  223. if (pkt->data && pkt->size >= 4) {
  224. MPADecodeHeader mpah;
  225. int av_unused base;
  226. uint32_t h;
  227. h = AV_RB32(pkt->data);
  228. if (ff_mpa_check_header(h) == 0) {
  229. avpriv_mpegaudio_decode_header(&mpah, h);
  230. if (!mp3->initial_bitrate)
  231. mp3->initial_bitrate = mpah.bit_rate;
  232. if ((mpah.bit_rate == 0) || (mp3->initial_bitrate != mpah.bit_rate))
  233. mp3->has_variable_bitrate = 1;
  234. } else {
  235. av_log(s, AV_LOG_WARNING, "Audio packet of size %d (starting with %08X...) "
  236. "is invalid, writing it anyway.\n", pkt->size, h);
  237. }
  238. #ifdef FILTER_VBR_HEADERS
  239. /* filter out XING and INFO headers. */
  240. base = 4 + xing_offtbl[mpah.lsf == 1][mpah.nb_channels == 1];
  241. if (base + 4 <= pkt->size) {
  242. uint32_t v = AV_RB32(pkt->data + base);
  243. if (MKBETAG('X','i','n','g') == v || MKBETAG('I','n','f','o') == v)
  244. return 0;
  245. }
  246. /* filter out VBRI headers. */
  247. base = 4 + 32;
  248. if (base + 4 <= pkt->size && MKBETAG('V','B','R','I') == AV_RB32(pkt->data + base))
  249. return 0;
  250. #endif
  251. if (mp3->xing_offset)
  252. mp3_xing_add_frame(mp3, pkt);
  253. }
  254. return ff_raw_write_packet(s, pkt);
  255. }
  256. static int mp3_queue_flush(AVFormatContext *s)
  257. {
  258. MP3Context *mp3 = s->priv_data;
  259. AVPacketList *pktl;
  260. int ret = 0, write = 1;
  261. ff_id3v2_finish(&mp3->id3, s->pb, s->metadata_header_padding);
  262. mp3_write_xing(s);
  263. while ((pktl = mp3->queue)) {
  264. if (write && (ret = mp3_write_audio_packet(s, &pktl->pkt)) < 0)
  265. write = 0;
  266. av_free_packet(&pktl->pkt);
  267. mp3->queue = pktl->next;
  268. av_freep(&pktl);
  269. }
  270. mp3->queue_end = NULL;
  271. return ret;
  272. }
  273. static void mp3_update_xing(AVFormatContext *s)
  274. {
  275. MP3Context *mp3 = s->priv_data;
  276. int i;
  277. /* replace "Xing" identification string with "Info" for CBR files. */
  278. if (!mp3->has_variable_bitrate) {
  279. avio_seek(s->pb, mp3->xing_offset, SEEK_SET);
  280. ffio_wfourcc(s->pb, "Info");
  281. }
  282. avio_seek(s->pb, mp3->xing_offset + 8, SEEK_SET);
  283. avio_wb32(s->pb, mp3->frames);
  284. avio_wb32(s->pb, mp3->size);
  285. avio_w8(s->pb, 0); // first toc entry has to be zero.
  286. for (i = 1; i < XING_TOC_SIZE; ++i) {
  287. int j = i * mp3->pos / XING_TOC_SIZE;
  288. int seek_point = 256LL * mp3->bag[j] / mp3->size;
  289. avio_w8(s->pb, FFMIN(seek_point, 255));
  290. }
  291. avio_seek(s->pb, 0, SEEK_END);
  292. }
  293. static int mp3_write_trailer(struct AVFormatContext *s)
  294. {
  295. uint8_t buf[ID3v1_TAG_SIZE];
  296. MP3Context *mp3 = s->priv_data;
  297. if (mp3->pics_to_write) {
  298. av_log(s, AV_LOG_WARNING, "No packets were sent for some of the "
  299. "attached pictures.\n");
  300. mp3_queue_flush(s);
  301. }
  302. /* write the id3v1 tag */
  303. if (mp3->write_id3v1 && id3v1_create_tag(s, buf) > 0) {
  304. avio_write(s->pb, buf, ID3v1_TAG_SIZE);
  305. }
  306. if (mp3->xing_offset)
  307. mp3_update_xing(s);
  308. return 0;
  309. }
  310. static int query_codec(enum AVCodecID id, int std_compliance)
  311. {
  312. const CodecMime *cm= ff_id3v2_mime_tags;
  313. while(cm->id != AV_CODEC_ID_NONE) {
  314. if(id == cm->id)
  315. return MKTAG('A', 'P', 'I', 'C');
  316. cm++;
  317. }
  318. return -1;
  319. }
  320. #if CONFIG_MP2_MUXER
  321. AVOutputFormat ff_mp2_muxer = {
  322. .name = "mp2",
  323. .long_name = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"),
  324. .mime_type = "audio/mpeg",
  325. .extensions = "mp2,m2a,mpa",
  326. .audio_codec = AV_CODEC_ID_MP2,
  327. .video_codec = AV_CODEC_ID_NONE,
  328. .write_packet = ff_raw_write_packet,
  329. .flags = AVFMT_NOTIMESTAMPS,
  330. };
  331. #endif
  332. #if CONFIG_MP3_MUXER
  333. static const AVOption options[] = {
  334. { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
  335. offsetof(MP3Context, id3v2_version), AV_OPT_TYPE_INT, {.i64 = 4}, 0, 4, AV_OPT_FLAG_ENCODING_PARAM},
  336. { "write_id3v1", "Enable ID3v1 writing. ID3v1 tags are written in UTF-8 which may not be supported by most software.",
  337. offsetof(MP3Context, write_id3v1), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  338. { "write_xing", "Write the Xing header containing file duration.",
  339. offsetof(MP3Context, write_xing), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
  340. { NULL },
  341. };
  342. static const AVClass mp3_muxer_class = {
  343. .class_name = "MP3 muxer",
  344. .item_name = av_default_item_name,
  345. .option = options,
  346. .version = LIBAVUTIL_VERSION_INT,
  347. };
  348. static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
  349. {
  350. MP3Context *mp3 = s->priv_data;
  351. if (pkt->stream_index == mp3->audio_stream_idx) {
  352. if (mp3->pics_to_write) {
  353. /* buffer audio packets until we get all the pictures */
  354. AVPacketList *pktl = av_mallocz(sizeof(*pktl));
  355. int ret;
  356. if (!pktl)
  357. return AVERROR(ENOMEM);
  358. ret = av_copy_packet(&pktl->pkt, pkt);
  359. if (ret < 0) {
  360. av_freep(&pktl);
  361. return ret;
  362. }
  363. if (mp3->queue_end)
  364. mp3->queue_end->next = pktl;
  365. else
  366. mp3->queue = pktl;
  367. mp3->queue_end = pktl;
  368. } else
  369. return mp3_write_audio_packet(s, pkt);
  370. } else {
  371. int ret;
  372. /* warn only once for each stream */
  373. if (s->streams[pkt->stream_index]->nb_frames == 1) {
  374. av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
  375. " ignoring.\n", pkt->stream_index);
  376. }
  377. if (!mp3->pics_to_write || s->streams[pkt->stream_index]->nb_frames >= 1)
  378. return 0;
  379. if ((ret = ff_id3v2_write_apic(s, &mp3->id3, pkt)) < 0)
  380. return ret;
  381. mp3->pics_to_write--;
  382. /* flush the buffered audio packets */
  383. if (!mp3->pics_to_write &&
  384. (ret = mp3_queue_flush(s)) < 0)
  385. return ret;
  386. }
  387. return 0;
  388. }
  389. /**
  390. * Write an ID3v2 header at beginning of stream
  391. */
  392. static int mp3_write_header(struct AVFormatContext *s)
  393. {
  394. MP3Context *mp3 = s->priv_data;
  395. int ret, i;
  396. if (mp3->id3v2_version &&
  397. mp3->id3v2_version != 3 &&
  398. mp3->id3v2_version != 4) {
  399. av_log(s, AV_LOG_ERROR, "Invalid ID3v2 version requested: %d. Only "
  400. "3, 4 or 0 (disabled) are allowed.\n", mp3->id3v2_version);
  401. return AVERROR(EINVAL);
  402. }
  403. /* check the streams -- we want exactly one audio and arbitrary number of
  404. * video (attached pictures) */
  405. mp3->audio_stream_idx = -1;
  406. for (i = 0; i < s->nb_streams; i++) {
  407. AVStream *st = s->streams[i];
  408. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  409. if (mp3->audio_stream_idx >= 0 || st->codec->codec_id != AV_CODEC_ID_MP3) {
  410. av_log(s, AV_LOG_ERROR, "Invalid audio stream. Exactly one MP3 "
  411. "audio stream is required.\n");
  412. return AVERROR(EINVAL);
  413. }
  414. mp3->audio_stream_idx = i;
  415. } else if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO) {
  416. av_log(s, AV_LOG_ERROR, "Only audio streams and pictures are allowed in MP3.\n");
  417. return AVERROR(EINVAL);
  418. }
  419. }
  420. if (mp3->audio_stream_idx < 0) {
  421. av_log(s, AV_LOG_ERROR, "No audio stream present.\n");
  422. return AVERROR(EINVAL);
  423. }
  424. mp3->pics_to_write = s->nb_streams - 1;
  425. if (mp3->pics_to_write && !mp3->id3v2_version) {
  426. av_log(s, AV_LOG_ERROR, "Attached pictures were requested, but the "
  427. "ID3v2 header is disabled.\n");
  428. return AVERROR(EINVAL);
  429. }
  430. if (mp3->id3v2_version) {
  431. ff_id3v2_start(&mp3->id3, s->pb, mp3->id3v2_version, ID3v2_DEFAULT_MAGIC);
  432. ret = ff_id3v2_write_metadata(s, &mp3->id3);
  433. if (ret < 0)
  434. return ret;
  435. }
  436. if (!mp3->pics_to_write) {
  437. if (mp3->id3v2_version)
  438. ff_id3v2_finish(&mp3->id3, s->pb, s->metadata_header_padding);
  439. mp3_write_xing(s);
  440. }
  441. return 0;
  442. }
  443. AVOutputFormat ff_mp3_muxer = {
  444. .name = "mp3",
  445. .long_name = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"),
  446. .mime_type = "audio/mpeg",
  447. .extensions = "mp3",
  448. .priv_data_size = sizeof(MP3Context),
  449. .audio_codec = AV_CODEC_ID_MP3,
  450. .video_codec = AV_CODEC_ID_PNG,
  451. .write_header = mp3_write_header,
  452. .write_packet = mp3_write_packet,
  453. .write_trailer = mp3_write_trailer,
  454. .query_codec = query_codec,
  455. .flags = AVFMT_NOTIMESTAMPS,
  456. .priv_class = &mp3_muxer_class,
  457. };
  458. #endif