Statistics
| Branch: | Revision:

ffmpeg / libavformat / mp3enc.c @ f2a90c3b

History | View | Annotate | Download (13 KB)

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 bag[VBR_NUM_BAGS];
176
        } toc;
177
    } xing_header;
178
} MP3Context;
179

    
180
static const AVOption options[] = {
181
    { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
182
      offsetof(MP3Context, id3v2_version), FF_OPT_TYPE_INT, {.dbl = 4}, 3, 4, AV_OPT_FLAG_ENCODING_PARAM},
183
    { NULL },
184
};
185

    
186
static const AVClass mp3_muxer_class = {
187
    .class_name     = "MP3 muxer",
188
    .item_name      = av_default_item_name,
189
    .option         = options,
190
    .version        = LIBAVUTIL_VERSION_INT,
191
};
192

    
193
static int id3v2_check_write_tag(AVFormatContext *s, AVMetadataTag *t, const char table[][4],
194
                                 enum ID3v2Encoding enc)
195
{
196
    uint32_t tag;
197
    int i;
198

    
199
    if (t->key[0] != 'T' || strlen(t->key) != 4)
200
        return -1;
201
    tag = AV_RB32(t->key);
202
    for (i = 0; *table[i]; i++)
203
        if (tag == AV_RB32(table[i]))
204
            return id3v2_put_ttag(s, t->value, NULL, tag, enc);
205
    return -1;
206
}
207

    
208
static const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
209

    
210
/*
211
 * Write an empty XING header and initialize respective data.
212
 */
213
static int mp3_write_xing(AVFormatContext *s)
214
{
215
    AVCodecContext   *codec = s->streams[0]->codec;
216
    MP3Context       *mp3 = s->priv_data;
217
    int              bitrate_idx = 3;
218
    int64_t          xing_offset;
219
    int32_t          mask, header;
220
    MPADecodeHeader  c;
221
    int              srate_idx, i, channels;
222
    int              needed;
223

    
224
    for (i = 0; i < FF_ARRAY_ELEMS(ff_mpa_freq_tab); i++)
225
        if (ff_mpa_freq_tab[i] == codec->sample_rate) {
226
            srate_idx = i;
227
            break;
228
        }
229
    if (i == FF_ARRAY_ELEMS(ff_mpa_freq_tab)) {
230
        av_log(s, AV_LOG_ERROR, "Unsupported sample rate.\n");
231
        return -1;
232
    }
233

    
234
    switch (codec->channels) {
235
    case 1:  channels = MPA_MONO;                                          break;
236
    case 2:  channels = MPA_STEREO;                                        break;
237
    default: av_log(s, AV_LOG_ERROR, "Unsupported number of channels.\n"); return -1;
238
    }
239

    
240
    /* dummy MPEG audio header */
241
    header  =  0xff                                  << 24; // sync
242
    header |= (0x7 << 5 | 0x3 << 3 | 0x1 << 1 | 0x1) << 16; // sync/mpeg-1/layer 3/no crc*/
243
    header |= (srate_idx << 2) <<  8;
244
    header |= channels << 6;
245

    
246
    for (;;) {
247
        if (15 == bitrate_idx)
248
            return -1;
249

    
250
        mask = (bitrate_idx << 4) <<  8;
251
        header |= mask;
252
        ff_mpegaudio_decode_header(&c, header);
253
        xing_offset=xing_offtbl[c.lsf == 1][c.nb_channels == 1];
254
        needed = 4              // header
255
               + xing_offset
256
               + 4              // xing tag
257
               + 4              // frames/size/toc flags
258
               + 4              // frames
259
               + 4              // size
260
               + VBR_TOC_SIZE;  // toc
261

    
262
        if (needed <= c.frame_size)
263
            break;
264

    
265
        header &= ~mask;
266
        ++bitrate_idx;
267
    }
268

    
269
    avio_wb32(s->pb, header);
270
    ffio_fill(s->pb, 0, xing_offset);
271
    avio_wb32(s->pb, MKBETAG('X', 'i', 'n', 'g'));
272
    avio_wb32(s->pb, 0x01 | 0x02 | 0x04);  // frames/size/toc
273

    
274
    mp3->xing_header.offset = avio_tell(s->pb);
275
    mp3->xing_header.size = c.frame_size;
276
    mp3->xing_header.toc.want=1;
277
    mp3->xing_header.toc.seen=0;
278
    mp3->xing_header.toc.pos=0;
279

    
280
    avio_wb32(s->pb, 0);  // frames
281
    avio_wb32(s->pb, 0);  // size
282

    
283
    // toc
284
    for (i = 0; i < VBR_TOC_SIZE; ++i)
285
        avio_w8(s->pb, (uint8_t)(255 * i / VBR_TOC_SIZE));
286

    
287
    ffio_fill(s->pb, 0, c.frame_size - needed);
288
    avio_flush(s->pb);
289

    
290
    return 0;
291
}
292

    
293
/*
294
 * Add a frame to XING data.
295
 * Following lame's "VbrTag.c".
296
 */
297
static void mp3_xing_add_frame(AVFormatContext *s, AVPacket *pkt)
298
{
299
    MP3Context  *mp3 = s->priv_data;
300
    struct xing_header *xing_header = &mp3->xing_header;
301
    struct xing_toc *toc = &xing_header->toc;
302
    int i;
303

    
304
    ++xing_header->frames;
305
    xing_header->size += pkt->size;
306

    
307
    if (toc->want == ++toc->seen) {
308
        toc->bag[toc->pos] = xing_header->size;
309

    
310
        if (VBR_NUM_BAGS == ++toc->pos) {
311
            /* shrink table to half size by throwing away each second bag. */
312
            for (i = 1; i < VBR_NUM_BAGS; i += 2)
313
                toc->bag[i >> 1] = toc->bag[i];
314

    
315
            /* double wanted amount per bag. */
316
            toc->want <<= 1;
317
            /* adjust current position to half of table size. */
318
            toc->pos >>= 1;
319
        }
320

    
321
        toc->seen = 0;
322
    }
323
}
324

    
325
static void mp3_fix_xing(AVFormatContext *s)
326
{
327
    MP3Context  *mp3 = s->priv_data;
328
    struct xing_header *xing_header = &mp3->xing_header;
329
    struct xing_toc *toc = &xing_header->toc;
330
    int i;
331

    
332
    avio_flush(s->pb);
333
    avio_seek(s->pb, xing_header->offset, SEEK_SET);
334
    avio_wb32(s->pb, xing_header->frames);
335
    avio_wb32(s->pb, xing_header->size);
336

    
337
    avio_w8(s->pb, 0);  // first toc entry has to be zero.
338

    
339
    for (i = 1; i < VBR_TOC_SIZE; ++i) {
340
        int j = i * toc->pos / VBR_TOC_SIZE;
341
        int seek_point = 256LL * toc->bag[j] / xing_header->size;
342
        avio_w8(s->pb, FFMIN(seek_point, 255));
343
    }
344

    
345
    avio_flush(s->pb);
346
    avio_seek(s->pb, 0, SEEK_END);
347
}
348

    
349
/**
350
 * Write an ID3v2 header at beginning of stream
351
 */
352

    
353
static int mp3_write_header(struct AVFormatContext *s)
354
{
355
    MP3Context  *mp3 = s->priv_data;
356
    AVMetadataTag *t = NULL;
357
    int totlen = 0, enc = mp3->id3v2_version == 3 ? ID3v2_ENCODING_UTF16BOM :
358
                                                    ID3v2_ENCODING_UTF8;
359
    int64_t size_pos, cur_pos;
360

    
361
    avio_wb32(s->pb, MKBETAG('I', 'D', '3', mp3->id3v2_version));
362
    avio_w8(s->pb, 0);
363
    avio_w8(s->pb, 0); /* flags */
364

    
365
    /* reserve space for size */
366
    size_pos = avio_tell(s->pb);
367
    avio_wb32(s->pb, 0);
368

    
369
    ff_metadata_conv(&s->metadata, ff_id3v2_34_metadata_conv, NULL);
370
    if (mp3->id3v2_version == 4)
371
        ff_metadata_conv(&s->metadata, ff_id3v2_4_metadata_conv, NULL);
372

    
373
    while ((t = av_metadata_get(s->metadata, "", t, AV_METADATA_IGNORE_SUFFIX))) {
374
        int ret;
375

    
376
        if ((ret = id3v2_check_write_tag(s, t, ff_id3v2_tags, enc)) > 0) {
377
            totlen += ret;
378
            continue;
379
        }
380
        if ((ret = id3v2_check_write_tag(s, t, mp3->id3v2_version == 3 ?
381
                                               ff_id3v2_3_tags : ff_id3v2_4_tags, enc)) > 0) {
382
            totlen += ret;
383
            continue;
384
        }
385

    
386
        /* unknown tag, write as TXXX frame */
387
        if ((ret = id3v2_put_ttag(s, t->key, t->value, MKBETAG('T', 'X', 'X', 'X'), enc)) < 0)
388
            return ret;
389
        totlen += ret;
390
    }
391

    
392
    cur_pos = avio_tell(s->pb);
393
    avio_seek(s->pb, size_pos, SEEK_SET);
394
    id3v2_put_size(s, totlen);
395
    avio_seek(s->pb, cur_pos, SEEK_SET);
396

    
397
    if (s->pb->seekable)
398
        mp3_write_xing(s);
399

    
400
    return 0;
401
}
402

    
403
static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
404
{
405
    if (! pkt || ! pkt->data || pkt->size < 4)
406
        return ff_raw_write_packet(s, pkt);
407
    else {
408
        MP3Context  *mp3 = s->priv_data;
409
        MPADecodeHeader c;
410
        int base;
411

    
412
#ifdef FILTER_VBR_HEADERS
413
        ff_mpegaudio_decode_header(&c, AV_RB32(pkt->data));
414

    
415
        /* filter out XING and INFO headers. */
416
        base = 4 + xing_offtbl[c.lsf == 1][c.nb_channels == 1];
417

    
418
        if (base + 4 <= pkt->size) {
419
            uint32_t v = AV_RB32(pkt->data + base);
420

    
421
            if (MKBETAG('X','i','n','g') == v || MKBETAG('I','n','f','o') == v)
422
                return 0;
423
        }
424

    
425
        /* filter out VBRI headers. */
426
        base = 4 + 32;
427

    
428
        if (base + 4 <= pkt->size && MKBETAG('V','B','R','I') == AV_RB32(pkt->data + base))
429
            return 0;
430
#endif
431

    
432
        if (0 < mp3->xing_header.offset)
433
            mp3_xing_add_frame(s, pkt);
434

    
435
        return ff_raw_write_packet(s, pkt);
436
    }
437
}
438

    
439
static int mp3_write_trailer(AVFormatContext *s)
440
{
441
    MP3Context  *mp3 = s->priv_data;
442
    int ret=mp2_write_trailer(s);
443

    
444
    if (ret < 0)
445
        return ret;
446

    
447
    if (0 < mp3->xing_header.offset)
448
        mp3_fix_xing(s);
449

    
450
    return 0;
451
}
452

    
453
AVOutputFormat ff_mp3_muxer = {
454
    "mp3",
455
    NULL_IF_CONFIG_SMALL("MPEG audio layer 3"),
456
    "audio/x-mpeg",
457
    "mp3",
458
    sizeof(MP3Context),
459
    CODEC_ID_MP3,
460
    CODEC_ID_NONE,
461
    mp3_write_header,
462
    mp3_write_packet,
463
    mp3_write_trailer,
464
    AVFMT_NOTIMESTAMPS,
465
    .priv_class = &mp3_muxer_class,
466
};
467
#endif