Statistics
| Branch: | Revision:

ffmpeg / libavformat / mp3.c @ 2a758efe

History | View | Annotate | Download (10.3 KB)

1
/*
2
 * MP3 muxer and demuxer
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 "libavutil/avstring.h"
24
#include "libavutil/intreadwrite.h"
25
#include "avformat.h"
26
#include "id3v2.h"
27
#include "id3v1.h"
28

    
29
#if CONFIG_MP3_DEMUXER
30

    
31
#include "libavcodec/mpegaudio.h"
32
#include "libavcodec/mpegaudiodecheader.h"
33

    
34
/* mp3 read */
35

    
36
static int mp3_read_probe(AVProbeData *p)
37
{
38
    int max_frames, first_frames = 0;
39
    int fsize, frames, sample_rate;
40
    uint32_t header;
41
    uint8_t *buf, *buf0, *buf2, *end;
42
    AVCodecContext avctx;
43

    
44
    buf0 = p->buf;
45
    if(ff_id3v2_match(buf0, ID3v2_DEFAULT_MAGIC)) {
46
        buf0 += ff_id3v2_tag_len(buf0);
47
    }
48
    end = p->buf + p->buf_size - sizeof(uint32_t);
49
    while(buf0 < end && !*buf0)
50
        buf0++;
51

    
52
    max_frames = 0;
53
    buf = buf0;
54

    
55
    for(; buf < end; buf= buf2+1) {
56
        buf2 = buf;
57

    
58
        for(frames = 0; buf2 < end; frames++) {
59
            header = AV_RB32(buf2);
60
            fsize = ff_mpa_decode_header(&avctx, header, &sample_rate, &sample_rate, &sample_rate, &sample_rate);
61
            if(fsize < 0)
62
                break;
63
            buf2 += fsize;
64
        }
65
        max_frames = FFMAX(max_frames, frames);
66
        if(buf == buf0)
67
            first_frames= frames;
68
    }
69
    // keep this in sync with ac3 probe, both need to avoid
70
    // issues with MPEG-files!
71
    if   (first_frames>=4) return AVPROBE_SCORE_MAX/2+1;
72
    else if(max_frames>500)return AVPROBE_SCORE_MAX/2;
73
    else if(max_frames>=4) return AVPROBE_SCORE_MAX/4;
74
    else if(buf0!=p->buf)  return AVPROBE_SCORE_MAX/4-1;
75
    else if(max_frames>=1) return 1;
76
    else                   return 0;
77
//mpegps_mp3_unrecognized_format.mpg has max_frames=3
78
}
79

    
80
/**
81
 * Try to find Xing/Info/VBRI tags and compute duration from info therein
82
 */
83
static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)
84
{
85
    uint32_t v, spf;
86
    unsigned frames = 0; /* Total number of frames in file */
87
    unsigned size = 0; /* Total number of bytes in the stream */
88
    const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};
89
    MPADecodeHeader c;
90
    int vbrtag_size = 0;
91

    
92
    v = get_be32(s->pb);
93
    if(ff_mpa_check_header(v) < 0)
94
      return -1;
95

    
96
    if (ff_mpegaudio_decode_header(&c, v) == 0)
97
        vbrtag_size = c.frame_size;
98
    if(c.layer != 3)
99
        return -1;
100

    
101
    /* Check for Xing / Info tag */
102
    url_fseek(s->pb, xing_offtbl[c.lsf == 1][c.nb_channels == 1], SEEK_CUR);
103
    v = get_be32(s->pb);
104
    if(v == MKBETAG('X', 'i', 'n', 'g') || v == MKBETAG('I', 'n', 'f', 'o')) {
105
        v = get_be32(s->pb);
106
        if(v & 0x1)
107
            frames = get_be32(s->pb);
108
        if(v & 0x2)
109
            size = get_be32(s->pb);
110
    }
111

    
112
    /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */
113
    url_fseek(s->pb, base + 4 + 32, SEEK_SET);
114
    v = get_be32(s->pb);
115
    if(v == MKBETAG('V', 'B', 'R', 'I')) {
116
        /* Check tag version */
117
        if(get_be16(s->pb) == 1) {
118
            /* skip delay and quality */
119
            url_fseek(s->pb, 4, SEEK_CUR);
120
            frames = get_be32(s->pb);
121
            size = get_be32(s->pb);
122
        }
123
    }
124

    
125
    if(!frames && !size)
126
        return -1;
127

    
128
    /* Skip the vbr tag frame */
129
    url_fseek(s->pb, base + vbrtag_size, SEEK_SET);
130

    
131
    spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */
132
    if(frames)
133
        st->duration = av_rescale_q(frames, (AVRational){spf, c.sample_rate},
134
                                    st->time_base);
135
    if(size)
136
        st->codec->bit_rate = av_rescale(size, 8 * c.sample_rate, frames * (int64_t)spf);
137

    
138
    return 0;
139
}
140

    
141
static int mp3_read_header(AVFormatContext *s,
142
                           AVFormatParameters *ap)
143
{
144
    AVStream *st;
145
    int64_t off;
146

    
147
    st = av_new_stream(s, 0);
148
    if (!st)
149
        return AVERROR(ENOMEM);
150

    
151
    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
152
    st->codec->codec_id = CODEC_ID_MP3;
153
    st->need_parsing = AVSTREAM_PARSE_FULL;
154
    st->start_time = 0;
155

    
156
    // lcm of all mp3 sample rates
157
    av_set_pts_info(st, 64, 1, 14112000);
158

    
159
    ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC);
160
    off = url_ftell(s->pb);
161

    
162
    if (!av_metadata_get(s->metadata, "", NULL, AV_METADATA_IGNORE_SUFFIX))
163
        ff_id3v1_read(s);
164

    
165
    if (mp3_parse_vbr_tags(s, st, off) < 0)
166
        url_fseek(s->pb, off, SEEK_SET);
167

    
168
    /* the parameters will be extracted from the compressed bitstream */
169
    return 0;
170
}
171

    
172
#define MP3_PACKET_SIZE 1024
173

    
174
static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
175
{
176
    int ret, size;
177
    //    AVStream *st = s->streams[0];
178

    
179
    size= MP3_PACKET_SIZE;
180

    
181
    ret= av_get_packet(s->pb, pkt, size);
182

    
183
    pkt->stream_index = 0;
184
    if (ret <= 0) {
185
        return AVERROR(EIO);
186
    }
187
    /* note: we need to modify the packet size here to handle the last
188
       packet */
189
    pkt->size = ret;
190
    return ret;
191
}
192

    
193
AVInputFormat mp3_demuxer = {
194
    "mp3",
195
    NULL_IF_CONFIG_SMALL("MPEG audio layer 2/3"),
196
    0,
197
    mp3_read_probe,
198
    mp3_read_header,
199
    mp3_read_packet,
200
    .flags= AVFMT_GENERIC_INDEX,
201
    .extensions = "mp2,mp3,m2a", /* XXX: use probe */
202
    .metadata_conv = ff_id3v2_metadata_conv,
203
};
204
#endif
205

    
206
#if CONFIG_MP2_MUXER || CONFIG_MP3_MUXER
207
static int id3v1_set_string(AVFormatContext *s, const char *key,
208
                            uint8_t *buf, int buf_size)
209
{
210
    AVMetadataTag *tag;
211
    if ((tag = av_metadata_get(s->metadata, key, NULL, 0)))
212
        strncpy(buf, tag->value, buf_size);
213
    return !!tag;
214
}
215

    
216
static int id3v1_create_tag(AVFormatContext *s, uint8_t *buf)
217
{
218
    AVMetadataTag *tag;
219
    int i, count = 0;
220

    
221
    memset(buf, 0, ID3v1_TAG_SIZE); /* fail safe */
222
    buf[0] = 'T';
223
    buf[1] = 'A';
224
    buf[2] = 'G';
225
    count += id3v1_set_string(s, "TIT2",    buf +  3, 30);       //title
226
    count += id3v1_set_string(s, "TPE1",    buf + 33, 30);       //author|artist
227
    count += id3v1_set_string(s, "TALB",    buf + 63, 30);       //album
228
    count += id3v1_set_string(s, "TDRL",    buf + 93,  4);       //date
229
    count += id3v1_set_string(s, "comment", buf + 97, 30);
230
    if ((tag = av_metadata_get(s->metadata, "TRCK", NULL, 0))) { //track
231
        buf[125] = 0;
232
        buf[126] = atoi(tag->value);
233
        count++;
234
    }
235
    buf[127] = 0xFF; /* default to unknown genre */
236
    if ((tag = av_metadata_get(s->metadata, "TCON", NULL, 0))) { //genre
237
        for(i = 0; i <= ID3v1_GENRE_MAX; i++) {
238
            if (!strcasecmp(tag->value, ff_id3v1_genre_str[i])) {
239
                buf[127] = i;
240
                count++;
241
                break;
242
            }
243
        }
244
    }
245
    return count;
246
}
247

    
248
/* simple formats */
249

    
250
static void id3v2_put_size(AVFormatContext *s, int size)
251
{
252
    put_byte(s->pb, size >> 21 & 0x7f);
253
    put_byte(s->pb, size >> 14 & 0x7f);
254
    put_byte(s->pb, size >> 7  & 0x7f);
255
    put_byte(s->pb, size       & 0x7f);
256
}
257

    
258
static void id3v2_put_ttag(AVFormatContext *s, const char *buf, int len,
259
                           uint32_t tag)
260
{
261
    put_be32(s->pb, tag);
262
    id3v2_put_size(s, len + 1);
263
    put_be16(s->pb, 0);
264
    put_byte(s->pb, 3); /* UTF-8 */
265
    put_buffer(s->pb, buf, len);
266
}
267

    
268

    
269
static int mp3_write_packet(struct AVFormatContext *s, AVPacket *pkt)
270
{
271
    put_buffer(s->pb, pkt->data, pkt->size);
272
    put_flush_packet(s->pb);
273
    return 0;
274
}
275

    
276
static int mp3_write_trailer(struct AVFormatContext *s)
277
{
278
    uint8_t buf[ID3v1_TAG_SIZE];
279

    
280
    /* write the id3v1 tag */
281
    if (id3v1_create_tag(s, buf) > 0) {
282
        put_buffer(s->pb, buf, ID3v1_TAG_SIZE);
283
        put_flush_packet(s->pb);
284
    }
285
    return 0;
286
}
287
#endif /* CONFIG_MP2_MUXER || CONFIG_MP3_MUXER */
288

    
289
#if CONFIG_MP2_MUXER
290
AVOutputFormat mp2_muxer = {
291
    "mp2",
292
    NULL_IF_CONFIG_SMALL("MPEG audio layer 2"),
293
    "audio/x-mpeg",
294
    "mp2,m2a",
295
    0,
296
    CODEC_ID_MP2,
297
    CODEC_ID_NONE,
298
    NULL,
299
    mp3_write_packet,
300
    mp3_write_trailer,
301
    .metadata_conv = ff_id3v2_metadata_conv,
302
};
303
#endif
304

    
305
#if CONFIG_MP3_MUXER
306
/**
307
 * Write an ID3v2.4 header at beginning of stream
308
 */
309

    
310
static int mp3_write_header(struct AVFormatContext *s)
311
{
312
    AVMetadataTag *t = NULL;
313
    int totlen = 0;
314
    int64_t size_pos, cur_pos;
315

    
316
    put_be32(s->pb, MKBETAG('I', 'D', '3', 0x04)); /* ID3v2.4 */
317
    put_byte(s->pb, 0);
318
    put_byte(s->pb, 0); /* flags */
319

    
320
    /* reserve space for size */
321
    size_pos = url_ftell(s->pb);
322
    put_be32(s->pb, 0);
323

    
324
    while ((t = av_metadata_get(s->metadata, "", t, AV_METADATA_IGNORE_SUFFIX))) {
325
        uint32_t tag = 0;
326

    
327
        if (t->key[0] == 'T' && strlen(t->key) == 4) {
328
            int i;
329
            for (i = 0; *ff_id3v2_tags[i]; i++)
330
                if (AV_RB32(t->key) == AV_RB32(ff_id3v2_tags[i])) {
331
                    int len = strlen(t->value);
332
                    tag = AV_RB32(t->key);
333
                    totlen += len + ID3v2_HEADER_SIZE + 2;
334
                    id3v2_put_ttag(s, t->value, len + 1, tag);
335
                    break;
336
                }
337
        }
338

    
339
        if (!tag) { /* unknown tag, write as TXXX frame */
340
            int   len = strlen(t->key), len1 = strlen(t->value);
341
            char *buf = av_malloc(len + len1 + 2);
342
            if (!buf)
343
                return AVERROR(ENOMEM);
344
            tag = MKBETAG('T', 'X', 'X', 'X');
345
            strcpy(buf,           t->key);
346
            strcpy(buf + len + 1, t->value);
347
            id3v2_put_ttag(s, buf, len + len1 + 2, tag);
348
            totlen += len + len1 + ID3v2_HEADER_SIZE + 3;
349
            av_free(buf);
350
        }
351
    }
352

    
353
    cur_pos = url_ftell(s->pb);
354
    url_fseek(s->pb, size_pos, SEEK_SET);
355
    id3v2_put_size(s, totlen);
356
    url_fseek(s->pb, cur_pos, SEEK_SET);
357

    
358
    return 0;
359
}
360

    
361
AVOutputFormat mp3_muxer = {
362
    "mp3",
363
    NULL_IF_CONFIG_SMALL("MPEG audio layer 3"),
364
    "audio/x-mpeg",
365
    "mp3",
366
    0,
367
    CODEC_ID_MP3,
368
    CODEC_ID_NONE,
369
    mp3_write_header,
370
    mp3_write_packet,
371
    mp3_write_trailer,
372
    AVFMT_NOTIMESTAMPS,
373
    .metadata_conv = ff_id3v2_metadata_conv,
374
};
375
#endif