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