]> git.sesse.net Git - ffmpeg/blob - libavformat/mp3enc.c
7e96d47995d7adb0b5777f4fec309c761f889350
[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     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
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 (!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 /* simple formats */
82
83 static void id3v2_put_size(AVFormatContext *s, int size)
84 {
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);
89 }
90
91 static int string_is_ascii(const uint8_t *str)
92 {
93     while (*str && *str < 128) str++;
94     return !*str;
95 }
96
97 /**
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.
101  */
102 static int id3v2_put_ttag(AVFormatContext *s, const char *str1, const char *str2,
103                           uint32_t tag, enum ID3v2Encoding enc)
104 {
105     int len;
106     uint8_t *pb;
107     int (*put)(AVIOContext*, const char*);
108     AVIOContext *dyn_buf;
109     if (avio_open_dyn_buf(&dyn_buf) < 0)
110         return AVERROR(ENOMEM);
111
112     /* check if the strings are ASCII-only and use UTF16 only if
113      * they're not */
114     if (enc == ID3v2_ENCODING_UTF16BOM && string_is_ascii(str1) &&
115         (!str2 || string_is_ascii(str2)))
116         enc = ID3v2_ENCODING_ISO8859;
117
118     avio_w8(dyn_buf, enc);
119     if (enc == ID3v2_ENCODING_UTF16BOM) {
120         avio_wl16(dyn_buf, 0xFEFF);      /* BOM */
121         put = avio_put_str16le;
122     } else
123         put = avio_put_str;
124
125     put(dyn_buf, str1);
126     if (str2)
127         put(dyn_buf, str2);
128     len = avio_close_dyn_buf(dyn_buf, &pb);
129
130     avio_wb32(s->pb, tag);
131     id3v2_put_size(s, len);
132     avio_wb16(s->pb, 0);
133     avio_write(s->pb, pb, len);
134
135     av_freep(&pb);
136     return len + ID3v2_HEADER_SIZE;
137 }
138
139 #define VBR_NUM_BAGS 400
140 #define VBR_TOC_SIZE 100
141 typedef struct MP3Context {
142     const AVClass *class;
143     int id3v2_version;
144     int write_id3v1;
145     int64_t frames_offset;
146     int32_t frames;
147     int32_t size;
148     uint32_t want;
149     uint32_t seen;
150     uint32_t pos;
151     uint64_t bag[VBR_NUM_BAGS];
152 } MP3Context;
153
154 static int mp2_write_trailer(struct AVFormatContext *s)
155 {
156     uint8_t buf[ID3v1_TAG_SIZE];
157     MP3Context *mp3 = s->priv_data;
158
159     /* write the id3v1 tag */
160     if (mp3 && mp3->write_id3v1 && id3v1_create_tag(s, buf) > 0) {
161         avio_write(s->pb, buf, ID3v1_TAG_SIZE);
162     }
163
164     /* write number of frames */
165     if (mp3 && mp3->frames_offset) {
166         avio_seek(s->pb, mp3->frames_offset, SEEK_SET);
167         avio_wb32(s->pb, s->streams[0]->nb_frames);
168         avio_seek(s->pb, 0, SEEK_END);
169     }
170
171     avio_flush(s->pb);
172
173     return 0;
174 }
175
176 #if CONFIG_MP2_MUXER
177 AVOutputFormat ff_mp2_muxer = {
178     .name              = "mp2",
179     .long_name         = NULL_IF_CONFIG_SMALL("MPEG audio layer 2"),
180     .mime_type         = "audio/x-mpeg",
181     .extensions        = "mp2,m2a",
182     .audio_codec       = CODEC_ID_MP2,
183     .video_codec       = CODEC_ID_NONE,
184     .write_packet      = ff_raw_write_packet,
185     .write_trailer     = mp2_write_trailer,
186 };
187 #endif
188
189 #if CONFIG_MP3_MUXER
190
191 static const AVOption options[] = {
192     { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
193       offsetof(MP3Context, id3v2_version), FF_OPT_TYPE_INT, {.dbl = 4}, 3, 4, AV_OPT_FLAG_ENCODING_PARAM},
194     { "write_id3v1", "Enable ID3v1 writing. ID3v1 tags are written in UTF-8 which may not be supported by most software.",
195       offsetof(MP3Context, write_id3v1), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
196     { NULL },
197 };
198
199 static const AVClass mp3_muxer_class = {
200     .class_name     = "MP3 muxer",
201     .item_name      = av_default_item_name,
202     .option         = options,
203     .version        = LIBAVUTIL_VERSION_INT,
204 };
205
206 static int id3v2_check_write_tag(AVFormatContext *s, AVDictionaryEntry *t, const char table[][4],
207                                  enum ID3v2Encoding enc)
208 {
209     uint32_t tag;
210     int i;
211
212     if (t->key[0] != 'T' || strlen(t->key) != 4)
213         return -1;
214     tag = AV_RB32(t->key);
215     for (i = 0; *table[i]; i++)
216         if (tag == AV_RB32(table[i]))
217             return id3v2_put_ttag(s, t->value, NULL, tag, enc);
218     return -1;
219 }
220
221 static const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
222
223 /*
224  * Write an empty XING header and initialize respective data.
225  */
226 static int mp3_write_xing(AVFormatContext *s)
227 {
228     AVCodecContext   *codec = s->streams[0]->codec;
229     MP3Context       *mp3 = s->priv_data;
230     int              bitrate_idx = 3;
231     int64_t          xing_offset;
232     int32_t          mask, header;
233     MPADecodeHeader  c;
234     int              srate_idx, i, channels;
235     int              needed;
236
237     for (i = 0; i < FF_ARRAY_ELEMS(ff_mpa_freq_tab); i++)
238         if (ff_mpa_freq_tab[i] == codec->sample_rate) {
239             srate_idx = i;
240             break;
241         }
242     if (i == FF_ARRAY_ELEMS(ff_mpa_freq_tab)) {
243         av_log(s, AV_LOG_ERROR, "Unsupported sample rate.\n");
244         return -1;
245     }
246
247     switch (codec->channels) {
248     case 1:  channels = MPA_MONO;                                          break;
249     case 2:  channels = MPA_STEREO;                                        break;
250     default: av_log(s, AV_LOG_ERROR, "Unsupported number of channels.\n"); return -1;
251     }
252
253     /* dummy MPEG audio header */
254     header  =  0xff                                  << 24; // sync
255     header |= (0x7 << 5 | 0x3 << 3 | 0x1 << 1 | 0x1) << 16; // sync/mpeg-1/layer 3/no crc*/
256     header |= (srate_idx << 2) <<  8;
257     header |= channels << 6;
258
259     for (;;) {
260         if (15 == bitrate_idx)
261             return -1;
262
263         mask = (bitrate_idx << 4) <<  8;
264         header |= mask;
265         ff_mpegaudio_decode_header(&c, header);
266         xing_offset=xing_offtbl[c.lsf == 1][c.nb_channels == 1];
267         needed = 4              // header
268                + xing_offset
269                + 4              // xing tag
270                + 4              // frames/size/toc flags
271                + 4              // frames
272                + 4              // size
273                + VBR_TOC_SIZE;  // toc
274
275         if (needed <= c.frame_size)
276             break;
277
278         header &= ~mask;
279         ++bitrate_idx;
280     }
281
282     avio_wb32(s->pb, header);
283     ffio_fill(s->pb, 0, xing_offset);
284     avio_wb32(s->pb, MKBETAG('X', 'i', 'n', 'g'));
285     avio_wb32(s->pb, 0x01 | 0x02 | 0x04);  // frames/size/toc
286
287     mp3->frames_offset = avio_tell(s->pb);
288     mp3->size = c.frame_size;
289     mp3->want=1;
290     mp3->seen=0;
291     mp3->pos=0;
292
293     avio_wb32(s->pb, 0);  // frames
294     avio_wb32(s->pb, 0);  // size
295
296     // toc
297     for (i = 0; i < VBR_TOC_SIZE; ++i)
298         avio_w8(s->pb, (uint8_t)(255 * i / VBR_TOC_SIZE));
299
300     ffio_fill(s->pb, 0, c.frame_size - needed);
301     avio_flush(s->pb);
302
303     return 0;
304 }
305
306 /*
307  * Add a frame to XING data.
308  * Following lame's "VbrTag.c".
309  */
310 static void mp3_xing_add_frame(AVFormatContext *s, AVPacket *pkt)
311 {
312     MP3Context  *mp3 = s->priv_data;
313     int i;
314
315     ++mp3->frames;
316     mp3->size += pkt->size;
317
318     if (mp3->want == ++mp3->seen) {
319         mp3->bag[mp3->pos] = mp3->size;
320
321         if (VBR_NUM_BAGS == ++mp3->pos) {
322             /* shrink table to half size by throwing away each second bag. */
323             for (i = 1; i < VBR_NUM_BAGS; i += 2)
324                 mp3->bag[i >> 1] = mp3->bag[i];
325
326             /* double wanted amount per bag. */
327             mp3->want <<= 1;
328             /* adjust current position to half of table size. */
329             mp3->pos >>= 1;
330         }
331
332         mp3->seen = 0;
333     }
334 }
335
336 static void mp3_fix_xing(AVFormatContext *s)
337 {
338     MP3Context  *mp3 = s->priv_data;
339     int i;
340
341     avio_flush(s->pb);
342     avio_seek(s->pb, mp3->frames_offset, SEEK_SET);
343     avio_wb32(s->pb, mp3->frames);
344     avio_wb32(s->pb, mp3->size);
345
346     avio_w8(s->pb, 0);  // first toc entry has to be zero.
347
348     for (i = 1; i < VBR_TOC_SIZE; ++i) {
349         int j = i * mp3->pos / VBR_TOC_SIZE;
350         int seek_point = 256LL * mp3->bag[j] / mp3->size;
351         avio_w8(s->pb, FFMIN(seek_point, 255));
352     }
353
354     avio_flush(s->pb);
355     avio_seek(s->pb, 0, SEEK_END);
356 }
357
358 /**
359  * Write an ID3v2 header at beginning of stream
360  */
361
362 static int mp3_write_header(struct AVFormatContext *s)
363 {
364     MP3Context  *mp3 = s->priv_data;
365     AVDictionaryEntry *t = NULL;
366     int totlen = 0, enc = mp3->id3v2_version == 3 ? ID3v2_ENCODING_UTF16BOM :
367                                                     ID3v2_ENCODING_UTF8;
368     int64_t size_pos, cur_pos;
369
370     avio_wb32(s->pb, MKBETAG('I', 'D', '3', mp3->id3v2_version));
371     avio_w8(s->pb, 0);
372     avio_w8(s->pb, 0); /* flags */
373
374     /* reserve space for size */
375     size_pos = avio_tell(s->pb);
376     avio_wb32(s->pb, 0);
377
378     ff_metadata_conv(&s->metadata, ff_id3v2_34_metadata_conv, NULL);
379     if (mp3->id3v2_version == 4)
380         ff_metadata_conv(&s->metadata, ff_id3v2_4_metadata_conv, NULL);
381
382     while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX))) {
383         int ret;
384
385         if ((ret = id3v2_check_write_tag(s, t, ff_id3v2_tags, enc)) > 0) {
386             totlen += ret;
387             continue;
388         }
389         if ((ret = id3v2_check_write_tag(s, t, mp3->id3v2_version == 3 ?
390                                                ff_id3v2_3_tags : ff_id3v2_4_tags, enc)) > 0) {
391             totlen += ret;
392             continue;
393         }
394
395         /* unknown tag, write as TXXX frame */
396         if ((ret = id3v2_put_ttag(s, t->key, t->value, MKBETAG('T', 'X', 'X', 'X'), enc)) < 0)
397             return ret;
398         totlen += ret;
399     }
400
401     cur_pos = avio_tell(s->pb);
402     avio_seek(s->pb, size_pos, SEEK_SET);
403     id3v2_put_size(s, totlen);
404     avio_seek(s->pb, cur_pos, SEEK_SET);
405
406     if (s->pb->seekable)
407         mp3_write_xing(s);
408
409     return 0;
410 }
411
412 static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
413 {
414     if (! pkt || ! pkt->data || pkt->size < 4)
415         return ff_raw_write_packet(s, pkt);
416     else {
417         MP3Context  *mp3 = s->priv_data;
418 #ifdef FILTER_VBR_HEADERS
419         MPADecodeHeader c;
420         int base;
421
422         ff_mpegaudio_decode_header(&c, AV_RB32(pkt->data));
423
424         /* filter out XING and INFO headers. */
425         base = 4 + xing_offtbl[c.lsf == 1][c.nb_channels == 1];
426
427         if (base + 4 <= pkt->size) {
428             uint32_t v = AV_RB32(pkt->data + base);
429
430             if (MKBETAG('X','i','n','g') == v || MKBETAG('I','n','f','o') == v)
431                 return 0;
432         }
433
434         /* filter out VBRI headers. */
435         base = 4 + 32;
436
437         if (base + 4 <= pkt->size && MKBETAG('V','B','R','I') == AV_RB32(pkt->data + base))
438             return 0;
439 #endif
440
441         if (mp3->frames_offset)
442             mp3_xing_add_frame(s, pkt);
443
444         return ff_raw_write_packet(s, pkt);
445     }
446 }
447
448 static int mp3_write_trailer(AVFormatContext *s)
449 {
450     MP3Context  *mp3 = s->priv_data;
451     int ret=mp2_write_trailer(s);
452
453     if (ret < 0)
454         return ret;
455
456     if (mp3->frames_offset)
457         mp3_fix_xing(s);
458
459     return 0;
460 }
461
462 AVOutputFormat ff_mp3_muxer = {
463     .name              = "mp3",
464     .long_name         = NULL_IF_CONFIG_SMALL("MPEG audio layer 3"),
465     .mime_type         = "audio/x-mpeg",
466     .extensions        = "mp3",
467     .priv_data_size    = sizeof(MP3Context),
468     .audio_codec       = CODEC_ID_MP3,
469     .video_codec       = CODEC_ID_NONE,
470     .write_header      = mp3_write_header,
471     .write_packet      = mp3_write_packet,
472     .write_trailer     = mp3_write_trailer,
473     .flags             = AVFMT_NOTIMESTAMPS,
474     .priv_class = &mp3_muxer_class,
475 };
476 #endif