Statistics
| Branch: | Revision:

ffmpeg / libavformat / mp3enc.c @ e1e8a8de

History | View | Annotate | Download (12.5 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
    int64_t frames_offset;
167
    int32_t frames;
168
    int32_t size;
169
    uint32_t want;
170
    uint32_t seen;
171
    uint32_t pos;
172
    uint64_t bag[VBR_NUM_BAGS];
173
} MP3Context;
174

    
175
static const AVOption options[] = {
176
    { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.",
177
      offsetof(MP3Context, id3v2_version), FF_OPT_TYPE_INT, {.dbl = 4}, 3, 4, AV_OPT_FLAG_ENCODING_PARAM},
178
    { NULL },
179
};
180

    
181
static const AVClass mp3_muxer_class = {
182
    .class_name     = "MP3 muxer",
183
    .item_name      = av_default_item_name,
184
    .option         = options,
185
    .version        = LIBAVUTIL_VERSION_INT,
186
};
187

    
188
static int id3v2_check_write_tag(AVFormatContext *s, AVMetadataTag *t, const char table[][4],
189
                                 enum ID3v2Encoding enc)
190
{
191
    uint32_t tag;
192
    int i;
193

    
194
    if (t->key[0] != 'T' || strlen(t->key) != 4)
195
        return -1;
196
    tag = AV_RB32(t->key);
197
    for (i = 0; *table[i]; i++)
198
        if (tag == AV_RB32(table[i]))
199
            return id3v2_put_ttag(s, t->value, NULL, tag, enc);
200
    return -1;
201
}
202

    
203
static const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
204

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

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

    
229
    switch (codec->channels) {
230
    case 1:  channels = MPA_MONO;                                          break;
231
    case 2:  channels = MPA_STEREO;                                        break;
232
    default: av_log(s, AV_LOG_ERROR, "Unsupported number of channels.\n"); return -1;
233
    }
234

    
235
    /* dummy MPEG audio header */
236
    header  =  0xff                                  << 24; // sync
237
    header |= (0x7 << 5 | 0x3 << 3 | 0x1 << 1 | 0x1) << 16; // sync/mpeg-1/layer 3/no crc*/
238
    header |= (srate_idx << 2) <<  8;
239
    header |= channels << 6;
240

    
241
    for (;;) {
242
        if (15 == bitrate_idx)
243
            return -1;
244

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

    
257
        if (needed <= c.frame_size)
258
            break;
259

    
260
        header &= ~mask;
261
        ++bitrate_idx;
262
    }
263

    
264
    avio_wb32(s->pb, header);
265
    ffio_fill(s->pb, 0, xing_offset);
266
    avio_wb32(s->pb, MKBETAG('X', 'i', 'n', 'g'));
267
    avio_wb32(s->pb, 0x01 | 0x02 | 0x04);  // frames/size/toc
268

    
269
    mp3->frames_offset = avio_tell(s->pb);
270
    mp3->size = c.frame_size;
271
    mp3->want=1;
272
    mp3->seen=0;
273
    mp3->pos=0;
274

    
275
    avio_wb32(s->pb, 0);  // frames
276
    avio_wb32(s->pb, 0);  // size
277

    
278
    // toc
279
    for (i = 0; i < VBR_TOC_SIZE; ++i)
280
        avio_w8(s->pb, (uint8_t)(255 * i / VBR_TOC_SIZE));
281

    
282
    ffio_fill(s->pb, 0, c.frame_size - needed);
283
    avio_flush(s->pb);
284

    
285
    return 0;
286
}
287

    
288
/*
289
 * Add a frame to XING data.
290
 * Following lame's "VbrTag.c".
291
 */
292
static void mp3_xing_add_frame(AVFormatContext *s, AVPacket *pkt)
293
{
294
    MP3Context  *mp3 = s->priv_data;
295
    int i;
296

    
297
    ++mp3->frames;
298
    mp3->size += pkt->size;
299

    
300
    if (mp3->want == ++mp3->seen) {
301
        mp3->bag[mp3->pos] = mp3->size;
302

    
303
        if (VBR_NUM_BAGS == ++mp3->pos) {
304
            /* shrink table to half size by throwing away each second bag. */
305
            for (i = 1; i < VBR_NUM_BAGS; i += 2)
306
                mp3->bag[i >> 1] = mp3->bag[i];
307

    
308
            /* double wanted amount per bag. */
309
            mp3->want <<= 1;
310
            /* adjust current position to half of table size. */
311
            mp3->pos >>= 1;
312
        }
313

    
314
        mp3->seen = 0;
315
    }
316
}
317

    
318
static void mp3_fix_xing(AVFormatContext *s)
319
{
320
    MP3Context  *mp3 = s->priv_data;
321
    int i;
322

    
323
    avio_flush(s->pb);
324
    avio_seek(s->pb, mp3->frames_offset, SEEK_SET);
325
    avio_wb32(s->pb, mp3->frames);
326
    avio_wb32(s->pb, mp3->size);
327

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

    
330
    for (i = 1; i < VBR_TOC_SIZE; ++i) {
331
        int j = i * mp3->pos / VBR_TOC_SIZE;
332
        int seek_point = 256LL * mp3->bag[j] / mp3->size;
333
        avio_w8(s->pb, FFMIN(seek_point, 255));
334
    }
335

    
336
    avio_flush(s->pb);
337
    avio_seek(s->pb, 0, SEEK_END);
338
}
339

    
340
/**
341
 * Write an ID3v2 header at beginning of stream
342
 */
343

    
344
static int mp3_write_header(struct AVFormatContext *s)
345
{
346
    MP3Context  *mp3 = s->priv_data;
347
    AVMetadataTag *t = NULL;
348
    int totlen = 0, enc = mp3->id3v2_version == 3 ? ID3v2_ENCODING_UTF16BOM :
349
                                                    ID3v2_ENCODING_UTF8;
350
    int64_t size_pos, cur_pos;
351

    
352
    avio_wb32(s->pb, MKBETAG('I', 'D', '3', mp3->id3v2_version));
353
    avio_w8(s->pb, 0);
354
    avio_w8(s->pb, 0); /* flags */
355

    
356
    /* reserve space for size */
357
    size_pos = avio_tell(s->pb);
358
    avio_wb32(s->pb, 0);
359

    
360
    ff_metadata_conv(&s->metadata, ff_id3v2_34_metadata_conv, NULL);
361
    if (mp3->id3v2_version == 4)
362
        ff_metadata_conv(&s->metadata, ff_id3v2_4_metadata_conv, NULL);
363

    
364
    while ((t = av_metadata_get(s->metadata, "", t, AV_METADATA_IGNORE_SUFFIX))) {
365
        int ret;
366

    
367
        if ((ret = id3v2_check_write_tag(s, t, ff_id3v2_tags, enc)) > 0) {
368
            totlen += ret;
369
            continue;
370
        }
371
        if ((ret = id3v2_check_write_tag(s, t, mp3->id3v2_version == 3 ?
372
                                               ff_id3v2_3_tags : ff_id3v2_4_tags, enc)) > 0) {
373
            totlen += ret;
374
            continue;
375
        }
376

    
377
        /* unknown tag, write as TXXX frame */
378
        if ((ret = id3v2_put_ttag(s, t->key, t->value, MKBETAG('T', 'X', 'X', 'X'), enc)) < 0)
379
            return ret;
380
        totlen += ret;
381
    }
382

    
383
    cur_pos = avio_tell(s->pb);
384
    avio_seek(s->pb, size_pos, SEEK_SET);
385
    id3v2_put_size(s, totlen);
386
    avio_seek(s->pb, cur_pos, SEEK_SET);
387

    
388
    if (s->pb->seekable)
389
        mp3_write_xing(s);
390

    
391
    return 0;
392
}
393

    
394
static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt)
395
{
396
    if (! pkt || ! pkt->data || pkt->size < 4)
397
        return ff_raw_write_packet(s, pkt);
398
    else {
399
        MP3Context  *mp3 = s->priv_data;
400
        MPADecodeHeader c;
401
        int base;
402

    
403
#ifdef FILTER_VBR_HEADERS
404
        ff_mpegaudio_decode_header(&c, AV_RB32(pkt->data));
405

    
406
        /* filter out XING and INFO headers. */
407
        base = 4 + xing_offtbl[c.lsf == 1][c.nb_channels == 1];
408

    
409
        if (base + 4 <= pkt->size) {
410
            uint32_t v = AV_RB32(pkt->data + base);
411

    
412
            if (MKBETAG('X','i','n','g') == v || MKBETAG('I','n','f','o') == v)
413
                return 0;
414
        }
415

    
416
        /* filter out VBRI headers. */
417
        base = 4 + 32;
418

    
419
        if (base + 4 <= pkt->size && MKBETAG('V','B','R','I') == AV_RB32(pkt->data + base))
420
            return 0;
421
#endif
422

    
423
        if (0 < mp3->frames_offset)
424
            mp3_xing_add_frame(s, pkt);
425

    
426
        return ff_raw_write_packet(s, pkt);
427
    }
428
}
429

    
430
static int mp3_write_trailer(AVFormatContext *s)
431
{
432
    MP3Context  *mp3 = s->priv_data;
433
    int ret=mp2_write_trailer(s);
434

    
435
    if (ret < 0)
436
        return ret;
437

    
438
    if (0 < mp3->frames_offset)
439
        mp3_fix_xing(s);
440

    
441
    return 0;
442
}
443

    
444
AVOutputFormat ff_mp3_muxer = {
445
    "mp3",
446
    NULL_IF_CONFIG_SMALL("MPEG audio layer 3"),
447
    "audio/x-mpeg",
448
    "mp3",
449
    sizeof(MP3Context),
450
    CODEC_ID_MP3,
451
    CODEC_ID_NONE,
452
    mp3_write_header,
453
    mp3_write_packet,
454
    mp3_write_trailer,
455
    AVFMT_NOTIMESTAMPS,
456
    .priv_class = &mp3_muxer_class,
457
};
458
#endif