Statistics
| Branch: | Revision:

ffmpeg / libavformat / mp3enc.c @ d62bf5d4

History | View | Annotate | Download (13.4 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 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
static const uint32_t XING = MKBETAG('X', 'i', 'n', 'g');
211
#ifdef FILTER_VBR_HEADERS
212
static const uint32_t INFO = MKBETAG('I', 'n', 'f', 'o');
213
static const uint32_t VBRI = MKBETAG('V', 'B', 'R', 'I');
214
#endif
215

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

    
230
    for (i = 0; i < FF_ARRAY_ELEMS(ff_mpa_freq_tab); i++)
231
        if (ff_mpa_freq_tab[i] == codec->sample_rate) {
232
            srate_idx = i;
233
            break;
234
        }
235
    if (i == FF_ARRAY_ELEMS(ff_mpa_freq_tab)) {
236
        av_log(s, AV_LOG_ERROR, "Unsupported sample rate.\n");
237
        return -1;
238
    }
239

    
240
    switch (codec->channels) {
241
    case 1:  channels = MPA_MONO;                                          break;
242
    case 2:  channels = MPA_STEREO;                                        break;
243
    default: av_log(s, AV_LOG_ERROR, "Unsupported number of channels.\n"); return -1;
244
    }
245

    
246
    /* dummy MPEG audio header */
247
    header  =  0xff                                  << 24; // sync
248
    header |= (0x7 << 5 | 0x3 << 3 | 0x1 << 1 | 0x1) << 16; // sync/mpeg-1/layer 3/no crc*/
249
    header |= (srate_idx << 2) <<  8;
250
    header |= channels << 6;
251

    
252
    for (;;) {
253
        if (15 == bitrate_idx)
254
            return -1;
255

    
256
        mask = (bitrate_idx << 4) <<  8;
257
        header |= mask;
258
        ff_mpegaudio_decode_header(&c, header);
259
        xing_offset=xing_offtbl[c.lsf == 1][c.nb_channels == 1];
260
        needed = 4              // header
261
               + xing_offset
262
               + 4              // xing tag
263
               + 4              // frames/size/toc flags
264
               + 4              // frames
265
               + 4              // size
266
               + VBR_TOC_SIZE;  // toc
267

    
268
        if (needed <= c.frame_size)
269
            break;
270

    
271
        header &= ~mask;
272
        ++bitrate_idx;
273
    }
274

    
275
    avio_wb32(s->pb, header);
276
    ffio_fill(s->pb, 0, xing_offset);
277
    avio_wb32(s->pb, XING);
278
    avio_wb32(s->pb, 0x01 | 0x02 | 0x04);  // frames/size/toc
279

    
280
    mp3->xing_header.offset = avio_tell(s->pb);
281
    mp3->xing_header.size = c.frame_size;
282
    mp3->xing_header.toc.want=1;
283
    mp3->xing_header.toc.seen=0;
284
    mp3->xing_header.toc.pos=0;
285
    mp3->xing_header.toc.sum=0;
286

    
287
    avio_wb32(s->pb, 0);  // frames
288
    avio_wb32(s->pb, 0);  // size
289

    
290
    // toc
291
    for (i = 0; i < VBR_TOC_SIZE; ++i)
292
        avio_w8(s->pb, (uint8_t)(255 * i / VBR_TOC_SIZE));
293

    
294
    ffio_fill(s->pb, 0, c.frame_size - needed);
295
    avio_flush(s->pb);
296

    
297
    return 0;
298
}
299

    
300
/*
301
 * Add a frame to XING data.
302
 * Following lame's "VbrTag.c".
303
 */
304
static void mp3_xing_add_frame(AVFormatContext *s, AVPacket *pkt, MPADecodeHeader *c)
305
{
306
    MP3Context  *mp3 = s->priv_data;
307
    struct xing_header *xing_header = &mp3->xing_header;
308
    struct xing_toc *toc = &xing_header->toc;
309
    int i;
310

    
311
    ++xing_header->frames;
312
    xing_header->size += pkt->size;
313
    toc->sum += c->bit_rate / 1000;
314

    
315
    if (toc->want == ++toc->seen) {
316
        toc->bag[toc->pos] = toc->sum;
317

    
318
        if (VBR_NUM_BAGS == ++toc->pos) {
319
            /* shrink table to half size by throwing away each second bag. */
320
            for (i = 1; i < VBR_NUM_BAGS; i += 2)
321
                toc->bag[i >> 1] = toc->bag[i];
322

    
323
            /* double wanted amount per bag. */
324
            toc->want <<= 1;
325
            /* adjust current position to half of table size. */
326
            toc->pos >>= 1;
327
        }
328

    
329
        toc->seen = 0;
330
    }
331
}
332

    
333
static void mp3_fix_xing(AVFormatContext *s)
334
{
335
    MP3Context  *mp3 = s->priv_data;
336
    struct xing_header *xing_header = &mp3->xing_header;
337
    struct xing_toc *toc = &xing_header->toc;
338
    double scale = (double)toc->pos / (double)VBR_TOC_SIZE;
339
    int i;
340

    
341
    avio_flush(s->pb);
342
    avio_seek(s->pb, xing_header->offset, SEEK_SET);
343
    avio_wb32(s->pb, xing_header->frames);
344
    avio_wb32(s->pb, xing_header->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 = (int)floor(scale * i);
350
        int seek_point = (int)floor(256.0 * toc->bag[j] / toc->sum);
351

    
352
        avio_w8(s->pb, (uint8_t)(seek_point < 256 ? seek_point : 255));
353
    }
354

    
355
    avio_flush(s->pb);
356
    avio_seek(s->pb, 0, SEEK_END);
357
}
358

    
359
/**
360
 * Write an ID3v2 header at beginning of stream
361
 */
362

    
363
static int mp3_write_header(struct AVFormatContext *s)
364
{
365
    MP3Context  *mp3 = s->priv_data;
366
    AVMetadataTag *t = NULL;
367
    int totlen = 0, enc = mp3->id3v2_version == 3 ? ID3v2_ENCODING_UTF16BOM :
368
                                                    ID3v2_ENCODING_UTF8;
369
    int64_t size_pos, cur_pos;
370

    
371
    avio_wb32(s->pb, MKBETAG('I', 'D', '3', mp3->id3v2_version));
372
    avio_w8(s->pb, 0);
373
    avio_w8(s->pb, 0); /* flags */
374

    
375
    /* reserve space for size */
376
    size_pos = avio_tell(s->pb);
377
    avio_wb32(s->pb, 0);
378

    
379
    ff_metadata_conv(&s->metadata, ff_id3v2_34_metadata_conv, NULL);
380
    if (mp3->id3v2_version == 4)
381
        ff_metadata_conv(&s->metadata, ff_id3v2_4_metadata_conv, NULL);
382

    
383
    while ((t = av_metadata_get(s->metadata, "", t, AV_METADATA_IGNORE_SUFFIX))) {
384
        int ret;
385

    
386
        if ((ret = id3v2_check_write_tag(s, t, ff_id3v2_tags, enc)) > 0) {
387
            totlen += ret;
388
            continue;
389
        }
390
        if ((ret = id3v2_check_write_tag(s, t, mp3->id3v2_version == 3 ?
391
                                               ff_id3v2_3_tags : ff_id3v2_4_tags, enc)) > 0) {
392
            totlen += ret;
393
            continue;
394
        }
395

    
396
        /* unknown tag, write as TXXX frame */
397
        if ((ret = id3v2_put_ttag(s, t->key, t->value, MKBETAG('T', 'X', 'X', 'X'), enc)) < 0)
398
            return ret;
399
        totlen += ret;
400
    }
401

    
402
    cur_pos = avio_tell(s->pb);
403
    avio_seek(s->pb, size_pos, SEEK_SET);
404
    id3v2_put_size(s, totlen);
405
    avio_seek(s->pb, cur_pos, SEEK_SET);
406

    
407
    if (s->pb->seekable)
408
        mp3_write_xing(s);
409

    
410
    return 0;
411
}
412

    
413
static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
414
{
415
    if (! pkt || ! pkt->data || pkt->size < 4)
416
        return ff_raw_write_packet(s, pkt);
417
    else {
418
        MP3Context  *mp3 = s->priv_data;
419
        MPADecodeHeader c;
420
#ifdef FILTER_VBR_HEADERS
421
        int base;
422
#endif
423

    
424
        ff_mpegaudio_decode_header(&c, AV_RB32(pkt->data));
425

    
426
#ifdef FILTER_VBR_HEADERS
427
        /* filter out XING and INFO headers. */
428
        base = 4 + xing_offtbl[c.lsf == 1][c.nb_channels == 1];
429

    
430
        if (base + 4 <= pkt->size) {
431
            uint32_t v = AV_RB32(pkt->data + base);
432

    
433
            if (XING == v || INFO == v)
434
                return 0;
435
        }
436

    
437
        /* filter out VBRI headers. */
438
        base = 4 + 32;
439

    
440
        if (base + 4 <= pkt->size && VBRI == AV_RB32(pkt->data + base))
441
            return 0;
442
#endif
443

    
444
        if (0 < mp3->xing_header.offset)
445
            mp3_xing_add_frame(s, pkt, &c);
446

    
447
        return ff_raw_write_packet(s, pkt);
448
    }
449
}
450

    
451
static int mp3_write_trailer(AVFormatContext *s)
452
{
453
    MP3Context  *mp3 = s->priv_data;
454
    int ret=mp2_write_trailer(s);
455

    
456
    if (ret < 0)
457
        return ret;
458

    
459
    if (0 < mp3->xing_header.offset)
460
        mp3_fix_xing(s);
461

    
462
    return 0;
463
}
464

    
465
AVOutputFormat ff_mp3_muxer = {
466
    "mp3",
467
    NULL_IF_CONFIG_SMALL("MPEG audio layer 3"),
468
    "audio/x-mpeg",
469
    "mp3",
470
    sizeof(MP3Context),
471
    CODEC_ID_MP3,
472
    CODEC_ID_NONE,
473
    mp3_write_header,
474
    mp3_write_packet,
475
    mp3_write_trailer,
476
    AVFMT_NOTIMESTAMPS,
477
    .priv_class = &mp3_muxer_class,
478
};
479
#endif