Statistics
| Branch: | Revision:

ffmpeg / libavformat / cafdec.c @ b7effd4e

History | View | Annotate | Download (12.5 KB)

1
/*
2
 * Core Audio Format demuxer
3
 * Copyright (c) 2007 Justin Ruggles
4
 * Copyright (c) 2009 Peter Ross
5
 *
6
 * This file is part of FFmpeg.
7
 *
8
 * FFmpeg is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * FFmpeg is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with FFmpeg; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
 */
22

    
23
/**
24
 * @file
25
 * Core Audio Format demuxer
26
 */
27

    
28
#include "avformat.h"
29
#include "riff.h"
30
#include "isom.h"
31
#include "libavutil/intreadwrite.h"
32
#include "caf.h"
33

    
34
typedef struct {
35
    int bytes_per_packet;           ///< bytes in a packet, or 0 if variable
36
    int frames_per_packet;          ///< frames in a packet, or 0 if variable
37
    int64_t num_bytes;              ///< total number of bytes in stream
38

    
39
    int64_t packet_cnt;             ///< packet counter
40
    int64_t frame_cnt;              ///< frame counter
41

    
42
    int64_t data_start;             ///< data start position, in bytes
43
    int64_t data_size;              ///< raw data size, in bytes
44
} CaffContext;
45

    
46
static int probe(AVProbeData *p)
47
{
48
    if (AV_RB32(p->buf) == MKBETAG('c','a','f','f') && AV_RB16(&p->buf[4]) == 1)
49
        return AVPROBE_SCORE_MAX;
50
    return 0;
51
}
52

    
53
/** Read audio description chunk */
54
static int read_desc_chunk(AVFormatContext *s)
55
{
56
    AVIOContext *pb = s->pb;
57
    CaffContext *caf  = s->priv_data;
58
    AVStream *st;
59
    int flags;
60

    
61
    /* new audio stream */
62
    st = av_new_stream(s, 0);
63
    if (!st)
64
        return AVERROR(ENOMEM);
65

    
66
    /* parse format description */
67
    st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
68
    st->codec->sample_rate = av_int2dbl(avio_rb64(pb));
69
    st->codec->codec_tag   = avio_rb32(pb);
70
    flags = avio_rb32(pb);
71
    caf->bytes_per_packet  = avio_rb32(pb);
72
    st->codec->block_align = caf->bytes_per_packet;
73
    caf->frames_per_packet = avio_rb32(pb);
74
    st->codec->channels    = avio_rb32(pb);
75
    st->codec->bits_per_coded_sample = avio_rb32(pb);
76

    
77
    /* calculate bit rate for constant size packets */
78
    if (caf->frames_per_packet > 0 && caf->bytes_per_packet > 0) {
79
        st->codec->bit_rate = (uint64_t)st->codec->sample_rate * (uint64_t)caf->bytes_per_packet * 8
80
                              / (uint64_t)caf->frames_per_packet;
81
    } else {
82
        st->codec->bit_rate = 0;
83
    }
84

    
85
    /* determine codec */
86
    if (st->codec->codec_tag == MKBETAG('l','p','c','m'))
87
        st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, (flags ^ 0x2) | 0x4);
88
    else
89
        st->codec->codec_id = ff_codec_get_id(ff_codec_caf_tags, st->codec->codec_tag);
90
    return 0;
91
}
92

    
93
/** Read magic cookie chunk */
94
static int read_kuki_chunk(AVFormatContext *s, int64_t size)
95
{
96
    AVIOContext *pb = s->pb;
97
    AVStream *st      = s->streams[0];
98

    
99
    if (size < 0 || size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE)
100
        return -1;
101

    
102
    if (st->codec->codec_id == CODEC_ID_AAC) {
103
        /* The magic cookie format for AAC is an mp4 esds atom.
104
           The lavc AAC decoder requires the data from the codec specific
105
           description as extradata input. */
106
        int strt, skip;
107
        MOVAtom atom;
108

    
109
        strt = url_ftell(pb);
110
        ff_mov_read_esds(s, pb, atom);
111
        skip = size - (url_ftell(pb) - strt);
112
        if (skip < 0 || !st->codec->extradata ||
113
            st->codec->codec_id != CODEC_ID_AAC) {
114
            av_log(s, AV_LOG_ERROR, "invalid AAC magic cookie\n");
115
            return AVERROR_INVALIDDATA;
116
        }
117
        url_fskip(pb, skip);
118
    } else if (st->codec->codec_id == CODEC_ID_ALAC) {
119
#define ALAC_PREAMBLE 12
120
#define ALAC_HEADER   36
121
        if (size < ALAC_PREAMBLE + ALAC_HEADER) {
122
            av_log(s, AV_LOG_ERROR, "invalid ALAC magic cookie\n");
123
            url_fskip(pb, size);
124
            return AVERROR_INVALIDDATA;
125
        }
126
        url_fskip(pb, ALAC_PREAMBLE);
127
        st->codec->extradata = av_mallocz(ALAC_HEADER + FF_INPUT_BUFFER_PADDING_SIZE);
128
        if (!st->codec->extradata)
129
            return AVERROR(ENOMEM);
130
        avio_read(pb, st->codec->extradata, ALAC_HEADER);
131
        st->codec->extradata_size = ALAC_HEADER;
132
        url_fskip(pb, size - ALAC_PREAMBLE - ALAC_HEADER);
133
    } else {
134
        st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
135
        if (!st->codec->extradata)
136
            return AVERROR(ENOMEM);
137
        avio_read(pb, st->codec->extradata, size);
138
        st->codec->extradata_size = size;
139
    }
140

    
141
    return 0;
142
}
143

    
144
/** Read packet table chunk */
145
static int read_pakt_chunk(AVFormatContext *s, int64_t size)
146
{
147
    AVIOContext *pb = s->pb;
148
    AVStream *st      = s->streams[0];
149
    CaffContext *caf  = s->priv_data;
150
    int64_t pos = 0, ccount;
151
    int num_packets, i;
152

    
153
    ccount = url_ftell(pb);
154

    
155
    num_packets = avio_rb64(pb);
156
    if (num_packets < 0 || INT32_MAX / sizeof(AVIndexEntry) < num_packets)
157
        return AVERROR_INVALIDDATA;
158

    
159
    st->nb_frames  = avio_rb64(pb); /* valid frames */
160
    st->nb_frames += avio_rb32(pb); /* priming frames */
161
    st->nb_frames += avio_rb32(pb); /* remainder frames */
162

    
163
    st->duration = 0;
164
    for (i = 0; i < num_packets; i++) {
165
        av_add_index_entry(s->streams[0], pos, st->duration, 0, 0, AVINDEX_KEYFRAME);
166
        pos += caf->bytes_per_packet ? caf->bytes_per_packet : ff_mp4_read_descr_len(pb);
167
        st->duration += caf->frames_per_packet ? caf->frames_per_packet : ff_mp4_read_descr_len(pb);
168
    }
169

    
170
    if (url_ftell(pb) - ccount != size) {
171
        av_log(s, AV_LOG_ERROR, "error reading packet table\n");
172
        return -1;
173
    }
174

    
175
    caf->num_bytes = pos;
176
    return 0;
177
}
178

    
179
/** Read information chunk */
180
static void read_info_chunk(AVFormatContext *s, int64_t size)
181
{
182
    AVIOContext *pb = s->pb;
183
    unsigned int i;
184
    unsigned int nb_entries = avio_rb32(pb);
185
    for (i = 0; i < nb_entries; i++) {
186
        char key[32];
187
        char value[1024];
188
        get_strz(pb, key, sizeof(key));
189
        get_strz(pb, value, sizeof(value));
190
        av_metadata_set2(&s->metadata, key, value, 0);
191
    }
192
}
193

    
194
static int read_header(AVFormatContext *s,
195
                       AVFormatParameters *ap)
196
{
197
    AVIOContext *pb = s->pb;
198
    CaffContext *caf  = s->priv_data;
199
    AVStream *st;
200
    uint32_t tag = 0;
201
    int found_data, ret;
202
    int64_t size;
203

    
204
    url_fskip(pb, 8); /* magic, version, file flags */
205

    
206
    /* audio description chunk */
207
    if (avio_rb32(pb) != MKBETAG('d','e','s','c')) {
208
        av_log(s, AV_LOG_ERROR, "desc chunk not present\n");
209
        return AVERROR_INVALIDDATA;
210
    }
211
    size = avio_rb64(pb);
212
    if (size != 32)
213
        return AVERROR_INVALIDDATA;
214

    
215
    ret = read_desc_chunk(s);
216
    if (ret)
217
        return ret;
218
    st = s->streams[0];
219

    
220
    /* parse each chunk */
221
    found_data = 0;
222
    while (!url_feof(pb)) {
223

    
224
        /* stop at data chunk if seeking is not supported or
225
           data chunk size is unknown */
226
        if (found_data && (caf->data_size < 0 || url_is_streamed(pb)))
227
            break;
228

    
229
        tag  = avio_rb32(pb);
230
        size = avio_rb64(pb);
231
        if (url_feof(pb))
232
            break;
233

    
234
        switch (tag) {
235
        case MKBETAG('d','a','t','a'):
236
            url_fskip(pb, 4); /* edit count */
237
            caf->data_start = url_ftell(pb);
238
            caf->data_size  = size < 0 ? -1 : size - 4;
239
            if (caf->data_size > 0 && !url_is_streamed(pb))
240
                url_fskip(pb, caf->data_size);
241
            found_data = 1;
242
            break;
243

    
244
        /* magic cookie chunk */
245
        case MKBETAG('k','u','k','i'):
246
            if (read_kuki_chunk(s, size))
247
                return AVERROR_INVALIDDATA;
248
            break;
249

    
250
        /* packet table chunk */
251
        case MKBETAG('p','a','k','t'):
252
            if (read_pakt_chunk(s, size))
253
                return AVERROR_INVALIDDATA;
254
            break;
255

    
256
        case MKBETAG('i','n','f','o'):
257
            read_info_chunk(s, size);
258
            break;
259

    
260
        default:
261
#define _(x) ((x) >= ' ' ? (x) : ' ')
262
            av_log(s, AV_LOG_WARNING, "skipping CAF chunk: %08X (%c%c%c%c)\n",
263
                tag, _(tag>>24), _((tag>>16)&0xFF), _((tag>>8)&0xFF), _(tag&0xFF));
264
#undef _
265
        case MKBETAG('f','r','e','e'):
266
            if (size < 0)
267
                return AVERROR_INVALIDDATA;
268
            url_fskip(pb, size);
269
            break;
270
        }
271
    }
272

    
273
    if (!found_data)
274
        return AVERROR_INVALIDDATA;
275

    
276
    if (caf->bytes_per_packet > 0 && caf->frames_per_packet > 0) {
277
        if (caf->data_size > 0)
278
            st->nb_frames = (caf->data_size / caf->bytes_per_packet) * caf->frames_per_packet;
279
    } else if (st->nb_index_entries) {
280
        st->codec->bit_rate = st->codec->sample_rate * caf->data_size * 8 /
281
                              st->duration;
282
    } else {
283
        av_log(s, AV_LOG_ERROR, "Missing packet table. It is required when "
284
                                "block size or frame size are variable.\n");
285
        return AVERROR_INVALIDDATA;
286
    }
287
    s->file_size = url_fsize(pb);
288
    s->file_size = FFMAX(0, s->file_size);
289

    
290
    av_set_pts_info(st, 64, 1, st->codec->sample_rate);
291
    st->start_time = 0;
292

    
293
    /* position the stream at the start of data */
294
    if (caf->data_size >= 0)
295
        url_fseek(pb, caf->data_start, SEEK_SET);
296

    
297
    return 0;
298
}
299

    
300
#define CAF_MAX_PKT_SIZE 4096
301

    
302
static int read_packet(AVFormatContext *s, AVPacket *pkt)
303
{
304
    AVIOContext *pb = s->pb;
305
    AVStream *st      = s->streams[0];
306
    CaffContext *caf  = s->priv_data;
307
    int res, pkt_size = 0, pkt_frames = 0;
308
    int64_t left      = CAF_MAX_PKT_SIZE;
309

    
310
    if (url_feof(pb))
311
        return AVERROR(EIO);
312

    
313
    /* don't read past end of data chunk */
314
    if (caf->data_size > 0) {
315
        left = (caf->data_start + caf->data_size) - url_ftell(pb);
316
        if (left <= 0)
317
            return AVERROR(EIO);
318
    }
319

    
320
    pkt_frames = caf->frames_per_packet;
321
    pkt_size   = caf->bytes_per_packet;
322

    
323
    if (pkt_size > 0 && pkt_frames == 1) {
324
        pkt_size   = (CAF_MAX_PKT_SIZE / pkt_size) * pkt_size;
325
        pkt_size   = FFMIN(pkt_size, left);
326
        pkt_frames = pkt_size / caf->bytes_per_packet;
327
    } else if (st->nb_index_entries) {
328
        if (caf->packet_cnt < st->nb_index_entries - 1) {
329
            pkt_size   = st->index_entries[caf->packet_cnt + 1].pos       - st->index_entries[caf->packet_cnt].pos;
330
            pkt_frames = st->index_entries[caf->packet_cnt + 1].timestamp - st->index_entries[caf->packet_cnt].timestamp;
331
        } else if (caf->packet_cnt == st->nb_index_entries - 1) {
332
            pkt_size   = caf->num_bytes - st->index_entries[caf->packet_cnt].pos;
333
            pkt_frames = st->duration   - st->index_entries[caf->packet_cnt].timestamp;
334
        } else {
335
            return AVERROR(EIO);
336
        }
337
    }
338

    
339
    if (pkt_size == 0 || pkt_frames == 0 || pkt_size > left)
340
        return AVERROR(EIO);
341

    
342
    res = av_get_packet(pb, pkt, pkt_size);
343
    if (res < 0)
344
        return res;
345

    
346
    pkt->size           = res;
347
    pkt->stream_index   = 0;
348
    pkt->dts = pkt->pts = caf->frame_cnt;
349

    
350
    caf->packet_cnt++;
351
    caf->frame_cnt += pkt_frames;
352

    
353
    return 0;
354
}
355

    
356
static int read_seek(AVFormatContext *s, int stream_index,
357
                     int64_t timestamp, int flags)
358
{
359
    AVStream *st = s->streams[0];
360
    CaffContext *caf = s->priv_data;
361
    int64_t pos;
362

    
363
    timestamp = FFMAX(timestamp, 0);
364

    
365
    if (caf->frames_per_packet > 0 && caf->bytes_per_packet > 0) {
366
        /* calculate new byte position based on target frame position */
367
        pos = caf->bytes_per_packet * timestamp / caf->frames_per_packet;
368
        if (caf->data_size > 0)
369
            pos = FFMIN(pos, caf->data_size);
370
        caf->packet_cnt = pos / caf->bytes_per_packet;
371
        caf->frame_cnt  = caf->frames_per_packet * caf->packet_cnt;
372
    } else if (st->nb_index_entries) {
373
        caf->packet_cnt = av_index_search_timestamp(st, timestamp, flags);
374
        caf->frame_cnt  = st->index_entries[caf->packet_cnt].timestamp;
375
        pos             = st->index_entries[caf->packet_cnt].pos;
376
    } else {
377
        return -1;
378
    }
379

    
380
    url_fseek(s->pb, pos + caf->data_start, SEEK_SET);
381
    return 0;
382
}
383

    
384
AVInputFormat ff_caf_demuxer = {
385
    "caf",
386
    NULL_IF_CONFIG_SMALL("Apple Core Audio Format"),
387
    sizeof(CaffContext),
388
    probe,
389
    read_header,
390
    read_packet,
391
    NULL,
392
    read_seek,
393
    .codec_tag = (const AVCodecTag*[]){ff_codec_caf_tags, 0},
394
};