3 * Copyright (c) 2003 Fabrice Bellard
5 * This file is part of FFmpeg.
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.
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.
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
24 #include "avio_internal.h"
28 #include "libavutil/avstring.h"
29 #include "libavcodec/mpegaudio.h"
30 #include "libavcodec/mpegaudiodata.h"
31 #include "libavcodec/mpegaudiodecheader.h"
32 #include "libavutil/intreadwrite.h"
33 #include "libavutil/opt.h"
34 #include "libavcodec/mpegaudio.h"
35 #include "libavcodec/mpegaudiodata.h"
36 #include "libavcodec/mpegaudiodecheader.h"
37 #include "libavformat/avio_internal.h"
38 #include "libavutil/dict.h"
40 static int id3v1_set_string(AVFormatContext *s, const char *key,
41 uint8_t *buf, int buf_size)
43 AVDictionaryEntry *tag;
44 if ((tag = av_dict_get(s->metadata, key, NULL, 0)))
45 av_strlcpy(buf, tag->value, buf_size);
49 static int id3v1_create_tag(AVFormatContext *s, uint8_t *buf)
51 AVDictionaryEntry *tag;
54 memset(buf, 0, ID3v1_TAG_SIZE); /* fail safe */
58 count += id3v1_set_string(s, "TIT2", buf + 3, 30); //title
59 count += id3v1_set_string(s, "TPE1", buf + 33, 30); //author|artist
60 count += id3v1_set_string(s, "TALB", buf + 63, 30); //album
61 count += id3v1_set_string(s, "TDRL", buf + 93, 4); //date
62 count += id3v1_set_string(s, "comment", buf + 97, 30);
63 if ((tag = av_dict_get(s->metadata, "TRCK", NULL, 0))) { //track
65 buf[126] = atoi(tag->value);
68 buf[127] = 0xFF; /* default to unknown genre */
69 if ((tag = av_dict_get(s->metadata, "TCON", NULL, 0))) { //genre
70 for(i = 0; i <= ID3v1_GENRE_MAX; i++) {
71 if (!strcasecmp(tag->value, ff_id3v1_genre_str[i])) {
83 static void id3v2_put_size(AVFormatContext *s, int size)
85 avio_w8(s->pb, size >> 21 & 0x7f);
86 avio_w8(s->pb, size >> 14 & 0x7f);
87 avio_w8(s->pb, size >> 7 & 0x7f);
88 avio_w8(s->pb, size & 0x7f);
91 static int string_is_ascii(const uint8_t *str)
93 while (*str && *str < 128) str++;
98 * Write a text frame with one (normal frames) or two (TXXX frames) strings
99 * according to encoding (only UTF-8 or UTF-16+BOM supported).
100 * @return number of bytes written or a negative error code.
102 static int id3v2_put_ttag(AVFormatContext *s, const char *str1, const char *str2,
103 uint32_t tag, enum ID3v2Encoding enc)
107 int (*put)(AVIOContext*, const char*);
108 AVIOContext *dyn_buf;
109 if (avio_open_dyn_buf(&dyn_buf) < 0)
110 return AVERROR(ENOMEM);
112 /* check if the strings are ASCII-only and use UTF16 only if
114 if (enc == ID3v2_ENCODING_UTF16BOM && string_is_ascii(str1) &&
115 (!str2 || string_is_ascii(str2)))
116 enc = ID3v2_ENCODING_ISO8859;
118 avio_w8(dyn_buf, enc);
119 if (enc == ID3v2_ENCODING_UTF16BOM) {
120 avio_wl16(dyn_buf, 0xFEFF); /* BOM */
121 put = avio_put_str16le;
128 len = avio_close_dyn_buf(dyn_buf, &pb);
130 avio_wb32(s->pb, tag);
131 id3v2_put_size(s, len);
133 avio_write(s->pb, pb, len);
136 return len + ID3v2_HEADER_SIZE;
139 #define VBR_NUM_BAGS 400
140 #define VBR_TOC_SIZE 100
141 typedef struct MP3Context {
142 const AVClass *class;
144 int64_t frames_offset;
150 uint64_t bag[VBR_NUM_BAGS];
153 static int mp2_write_trailer(struct AVFormatContext *s)
155 uint8_t buf[ID3v1_TAG_SIZE];
156 MP3Context *mp3 = s->priv_data;
158 /* write the id3v1 tag */
159 if (id3v1_create_tag(s, buf) > 0) {
160 avio_write(s->pb, buf, ID3v1_TAG_SIZE);
163 /* write number of frames */
164 if (mp3 && mp3->frames_offset) {
165 avio_seek(s->pb, mp3->frames_offset, SEEK_SET);
166 avio_wb32(s->pb, s->streams[0]->nb_frames);
167 avio_seek(s->pb, 0, SEEK_END);
176 AVOutputFormat ff_mp2_muxer = {
178 .long_name = NULL_IF_CONFIG_SMALL("MPEG audio layer 2"),
179 .mime_type = "audio/x-mpeg",
180 .extensions = "mp2,m2a",
181 .audio_codec = CODEC_ID_MP2,
182 .video_codec = CODEC_ID_NONE,
183 .write_packet = ff_raw_write_packet,
184 .write_trailer = mp2_write_trailer,
190 static const AVOption options[] = {
191 { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
192 offsetof(MP3Context, id3v2_version), FF_OPT_TYPE_INT, {.dbl = 4}, 3, 4, AV_OPT_FLAG_ENCODING_PARAM},
196 static const AVClass mp3_muxer_class = {
197 .class_name = "MP3 muxer",
198 .item_name = av_default_item_name,
200 .version = LIBAVUTIL_VERSION_INT,
203 static int id3v2_check_write_tag(AVFormatContext *s, AVDictionaryEntry *t, const char table[][4],
204 enum ID3v2Encoding enc)
209 if (t->key[0] != 'T' || strlen(t->key) != 4)
211 tag = AV_RB32(t->key);
212 for (i = 0; *table[i]; i++)
213 if (tag == AV_RB32(table[i]))
214 return id3v2_put_ttag(s, t->value, NULL, tag, enc);
218 static const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
221 * Write an empty XING header and initialize respective data.
223 static int mp3_write_xing(AVFormatContext *s)
225 AVCodecContext *codec = s->streams[0]->codec;
226 MP3Context *mp3 = s->priv_data;
229 int32_t mask, header;
231 int srate_idx, i, channels;
234 for (i = 0; i < FF_ARRAY_ELEMS(ff_mpa_freq_tab); i++)
235 if (ff_mpa_freq_tab[i] == codec->sample_rate) {
239 if (i == FF_ARRAY_ELEMS(ff_mpa_freq_tab)) {
240 av_log(s, AV_LOG_ERROR, "Unsupported sample rate.\n");
244 switch (codec->channels) {
245 case 1: channels = MPA_MONO; break;
246 case 2: channels = MPA_STEREO; break;
247 default: av_log(s, AV_LOG_ERROR, "Unsupported number of channels.\n"); return -1;
250 /* dummy MPEG audio header */
251 header = 0xff << 24; // sync
252 header |= (0x7 << 5 | 0x3 << 3 | 0x1 << 1 | 0x1) << 16; // sync/mpeg-1/layer 3/no crc*/
253 header |= (srate_idx << 2) << 8;
254 header |= channels << 6;
257 if (15 == bitrate_idx)
260 mask = (bitrate_idx << 4) << 8;
262 ff_mpegaudio_decode_header(&c, header);
263 xing_offset=xing_offtbl[c.lsf == 1][c.nb_channels == 1];
267 + 4 // frames/size/toc flags
270 + VBR_TOC_SIZE; // toc
272 if (needed <= c.frame_size)
279 avio_wb32(s->pb, header);
280 ffio_fill(s->pb, 0, xing_offset);
281 avio_wb32(s->pb, MKBETAG('X', 'i', 'n', 'g'));
282 avio_wb32(s->pb, 0x01 | 0x02 | 0x04); // frames/size/toc
284 mp3->frames_offset = avio_tell(s->pb);
285 mp3->size = c.frame_size;
290 avio_wb32(s->pb, 0); // frames
291 avio_wb32(s->pb, 0); // size
294 for (i = 0; i < VBR_TOC_SIZE; ++i)
295 avio_w8(s->pb, (uint8_t)(255 * i / VBR_TOC_SIZE));
297 ffio_fill(s->pb, 0, c.frame_size - needed);
304 * Add a frame to XING data.
305 * Following lame's "VbrTag.c".
307 static void mp3_xing_add_frame(AVFormatContext *s, AVPacket *pkt)
309 MP3Context *mp3 = s->priv_data;
313 mp3->size += pkt->size;
315 if (mp3->want == ++mp3->seen) {
316 mp3->bag[mp3->pos] = mp3->size;
318 if (VBR_NUM_BAGS == ++mp3->pos) {
319 /* shrink table to half size by throwing away each second bag. */
320 for (i = 1; i < VBR_NUM_BAGS; i += 2)
321 mp3->bag[i >> 1] = mp3->bag[i];
323 /* double wanted amount per bag. */
325 /* adjust current position to half of table size. */
333 static void mp3_fix_xing(AVFormatContext *s)
335 MP3Context *mp3 = s->priv_data;
339 avio_seek(s->pb, mp3->frames_offset, SEEK_SET);
340 avio_wb32(s->pb, mp3->frames);
341 avio_wb32(s->pb, mp3->size);
343 avio_w8(s->pb, 0); // first toc entry has to be zero.
345 for (i = 1; i < VBR_TOC_SIZE; ++i) {
346 int j = i * mp3->pos / VBR_TOC_SIZE;
347 int seek_point = 256LL * mp3->bag[j] / mp3->size;
348 avio_w8(s->pb, FFMIN(seek_point, 255));
352 avio_seek(s->pb, 0, SEEK_END);
356 * Write an ID3v2 header at beginning of stream
359 static int mp3_write_header(struct AVFormatContext *s)
361 MP3Context *mp3 = s->priv_data;
362 AVDictionaryEntry *t = NULL;
363 int totlen = 0, enc = mp3->id3v2_version == 3 ? ID3v2_ENCODING_UTF16BOM :
365 int64_t size_pos, cur_pos;
367 avio_wb32(s->pb, MKBETAG('I', 'D', '3', mp3->id3v2_version));
369 avio_w8(s->pb, 0); /* flags */
371 /* reserve space for size */
372 size_pos = avio_tell(s->pb);
375 ff_metadata_conv(&s->metadata, ff_id3v2_34_metadata_conv, NULL);
376 if (mp3->id3v2_version == 4)
377 ff_metadata_conv(&s->metadata, ff_id3v2_4_metadata_conv, NULL);
379 while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX))) {
382 if ((ret = id3v2_check_write_tag(s, t, ff_id3v2_tags, enc)) > 0) {
386 if ((ret = id3v2_check_write_tag(s, t, mp3->id3v2_version == 3 ?
387 ff_id3v2_3_tags : ff_id3v2_4_tags, enc)) > 0) {
392 /* unknown tag, write as TXXX frame */
393 if ((ret = id3v2_put_ttag(s, t->key, t->value, MKBETAG('T', 'X', 'X', 'X'), enc)) < 0)
398 cur_pos = avio_tell(s->pb);
399 avio_seek(s->pb, size_pos, SEEK_SET);
400 id3v2_put_size(s, totlen);
401 avio_seek(s->pb, cur_pos, SEEK_SET);
409 static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
411 if (! pkt || ! pkt->data || pkt->size < 4)
412 return ff_raw_write_packet(s, pkt);
414 MP3Context *mp3 = s->priv_data;
415 #ifdef FILTER_VBR_HEADERS
419 ff_mpegaudio_decode_header(&c, AV_RB32(pkt->data));
421 /* filter out XING and INFO headers. */
422 base = 4 + xing_offtbl[c.lsf == 1][c.nb_channels == 1];
424 if (base + 4 <= pkt->size) {
425 uint32_t v = AV_RB32(pkt->data + base);
427 if (MKBETAG('X','i','n','g') == v || MKBETAG('I','n','f','o') == v)
431 /* filter out VBRI headers. */
434 if (base + 4 <= pkt->size && MKBETAG('V','B','R','I') == AV_RB32(pkt->data + base))
438 if (mp3->frames_offset)
439 mp3_xing_add_frame(s, pkt);
441 return ff_raw_write_packet(s, pkt);
445 static int mp3_write_trailer(AVFormatContext *s)
447 MP3Context *mp3 = s->priv_data;
448 int ret=mp2_write_trailer(s);
453 if (mp3->frames_offset)
459 AVOutputFormat ff_mp3_muxer = {
461 .long_name = NULL_IF_CONFIG_SMALL("MPEG audio layer 3"),
462 .mime_type = "audio/x-mpeg",
464 .priv_data_size = sizeof(MP3Context),
465 .audio_codec = CODEC_ID_MP3,
466 .video_codec = CODEC_ID_NONE,
467 .write_header = mp3_write_header,
468 .write_packet = mp3_write_packet,
469 .write_trailer = mp3_write_trailer,
470 .flags = AVFMT_NOTIMESTAMPS,
471 .priv_class = &mp3_muxer_class,