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