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