brstm.c 14.6 KB
Newer Older
Paul B Mahol's avatar
Paul B Mahol committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/*
 * BRSTM demuxer
 * Copyright (c) 2012 Paul B Mahol
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "libavutil/intreadwrite.h"
#include "libavcodec/bytestream.h"
#include "avformat.h"
#include "internal.h"

typedef struct BRSTMDemuxContext {
    uint32_t    block_size;
    uint32_t    block_count;
    uint32_t    current_block;
    uint32_t    samples_per_block;
    uint32_t    last_block_used_bytes;
33 34
    uint32_t    last_block_size;
    uint32_t    last_block_samples;
35
    uint32_t    data_start;
Paul B Mahol's avatar
Paul B Mahol committed
36 37
    uint8_t     *table;
    uint8_t     *adpc;
38
    int         little_endian;
Paul B Mahol's avatar
Paul B Mahol committed
39 40 41 42 43 44 45 46 47 48 49
} BRSTMDemuxContext;

static int probe(AVProbeData *p)
{
    if (AV_RL32(p->buf) == MKTAG('R','S','T','M') &&
        (AV_RL16(p->buf + 4) == 0xFFFE ||
         AV_RL16(p->buf + 4) == 0xFEFF))
        return AVPROBE_SCORE_MAX / 3 * 2;
    return 0;
}

50 51
static int probe_bfstm(AVProbeData *p)
{
52 53
    if ((AV_RL32(p->buf) == MKTAG('F','S','T','M') ||
         AV_RL32(p->buf) == MKTAG('C','S','T','M')) &&
54 55 56 57 58 59
        (AV_RL16(p->buf + 4) == 0xFFFE ||
         AV_RL16(p->buf + 4) == 0xFEFF))
        return AVPROBE_SCORE_MAX / 3 * 2;
    return 0;
}

Paul B Mahol's avatar
Paul B Mahol committed
60 61 62 63 64 65 66 67 68 69
static int read_close(AVFormatContext *s)
{
    BRSTMDemuxContext *b = s->priv_data;

    av_freep(&b->table);
    av_freep(&b->adpc);

    return 0;
}

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
static av_always_inline unsigned int read16(AVFormatContext *s)
{
    BRSTMDemuxContext *b = s->priv_data;
    if (b->little_endian)
        return avio_rl16(s->pb);
    else
        return avio_rb16(s->pb);
}

static av_always_inline unsigned int read32(AVFormatContext *s)
{
    BRSTMDemuxContext *b = s->priv_data;
    if (b->little_endian)
        return avio_rl32(s->pb);
    else
        return avio_rb32(s->pb);
}

Paul B Mahol's avatar
Paul B Mahol committed
88 89 90 91
static int read_header(AVFormatContext *s)
{
    BRSTMDemuxContext *b = s->priv_data;
    int bom, major, minor, codec, chunk;
92 93
    int64_t h1offset, pos, toffset;
    uint32_t size, asize, start = 0;
Paul B Mahol's avatar
Paul B Mahol committed
94 95
    AVStream *st;
    int ret = AVERROR_EOF;
96
    int loop = 0;
97
    int bfstm = !strcmp("bfstm", s->iformat->name);
98

Paul B Mahol's avatar
Paul B Mahol committed
99 100 101
    st = avformat_new_stream(s, NULL);
    if (!st)
        return AVERROR(ENOMEM);
102
    st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
Paul B Mahol's avatar
Paul B Mahol committed
103 104 105 106 107 108 109 110

    avio_skip(s->pb, 4);

    bom = avio_rb16(s->pb);
    if (bom != 0xFEFF && bom != 0xFFFE) {
        av_log(s, AV_LOG_ERROR, "invalid byte order: %X\n", bom);
        return AVERROR_INVALIDDATA;
    }
111 112 113

    if (bom == 0xFFFE)
        b->little_endian = 1;
Paul B Mahol's avatar
Paul B Mahol committed
114

115
    if (!bfstm) {
116 117 118
        major = avio_r8(s->pb);
        minor = avio_r8(s->pb);
        avio_skip(s->pb, 4); // size of file
119
        size = read16(s);
120 121 122 123 124 125 126 127
        if (size < 14)
            return AVERROR_INVALIDDATA;

        avio_skip(s->pb, size - 14);
        pos = avio_tell(s->pb);
        if (avio_rl32(s->pb) != MKTAG('H','E','A','D'))
            return AVERROR_INVALIDDATA;
    } else {
128
        uint32_t info_offset = 0;
129 130
        uint16_t section_count, header_size, i;

131
        header_size = read16(s); // 6
132 133 134

        avio_skip(s->pb, 4); // Unknown constant 0x00030000
        avio_skip(s->pb, 4); // size of file
135
        section_count = read16(s);
136 137
        avio_skip(s->pb, 2); // padding
        for (i = 0; avio_tell(s->pb) < header_size
138
                    && !(start && info_offset)
139
                    && i < section_count; i++) {
140 141
            uint16_t flag = read16(s);
            avio_skip(s->pb, 2);
142
            switch (flag) {
143 144
            case 0x4000:
                info_offset = read32(s);
145
                /*info_size =*/ read32(s);
146
                break;
147
            case 0x4001:
148 149 150
                avio_skip(s->pb, 4); // seek offset
                avio_skip(s->pb, 4); // seek size
                break;
151
            case 0x4002:
152
                start = read32(s) + 8;
153
                avio_skip(s->pb, 4); //data_size = read32(s);
154
                break;
155
            case 0x4003:
156 157 158 159 160 161
                avio_skip(s->pb, 4); // REGN offset
                avio_skip(s->pb, 4); // REGN size
                break;
            }
        }

162
        if (!info_offset || !start)
163 164 165 166 167 168 169
            return AVERROR_INVALIDDATA;

        avio_skip(s->pb, info_offset - avio_tell(s->pb));
        pos = avio_tell(s->pb);
        if (avio_rl32(s->pb) != MKTAG('I','N','F','O'))
            return AVERROR_INVALIDDATA;
    }
Paul B Mahol's avatar
Paul B Mahol committed
170

171
    size = read32(s);
172
    if (size < 40)
Paul B Mahol's avatar
Paul B Mahol committed
173 174
        return AVERROR_INVALIDDATA;
    avio_skip(s->pb, 4); // unknown
175
    h1offset = read32(s);
Paul B Mahol's avatar
Paul B Mahol committed
176 177 178
    if (h1offset > size)
        return AVERROR_INVALIDDATA;
    avio_skip(s->pb, 12);
179
    toffset = read32(s) + 16LL;
Paul B Mahol's avatar
Paul B Mahol committed
180 181 182 183 184 185 186 187
    if (toffset > size)
        return AVERROR_INVALIDDATA;

    avio_skip(s->pb, pos + h1offset + 8 - avio_tell(s->pb));
    codec = avio_r8(s->pb);

    switch (codec) {
    case 0: codec = AV_CODEC_ID_PCM_S8_PLANAR;    break;
188 189 190
    case 1: codec = b->little_endian ?
                    AV_CODEC_ID_PCM_S16LE_PLANAR :
                    AV_CODEC_ID_PCM_S16BE_PLANAR; break;
191 192 193
    case 2: codec = b->little_endian ?
                    AV_CODEC_ID_ADPCM_THP_LE :
                    AV_CODEC_ID_ADPCM_THP;        break;
Paul B Mahol's avatar
Paul B Mahol committed
194
    default:
195
        avpriv_request_sample(s, "codec %d", codec);
Paul B Mahol's avatar
Paul B Mahol committed
196 197 198
        return AVERROR_PATCHWELCOME;
    }

199
    loop = avio_r8(s->pb); // loop flag
200 201 202
    st->codecpar->codec_id = codec;
    st->codecpar->channels = avio_r8(s->pb);
    if (!st->codecpar->channels)
Paul B Mahol's avatar
Paul B Mahol committed
203 204 205
        return AVERROR_INVALIDDATA;

    avio_skip(s->pb, 1); // padding
206

207 208
    st->codecpar->sample_rate = bfstm ? read32(s) : read16(s);
    if (st->codecpar->sample_rate <= 0)
Paul B Mahol's avatar
Paul B Mahol committed
209 210
        return AVERROR_INVALIDDATA;

211
    if (!bfstm)
212
        avio_skip(s->pb, 2); // padding
213 214 215 216

    if (loop) {
        if (av_dict_set_int(&s->metadata, "loop_start",
                            av_rescale(read32(s), AV_TIME_BASE,
217
                                       st->codecpar->sample_rate),
218 219 220 221 222 223
                            0) < 0)
            return AVERROR(ENOMEM);
    } else {
        avio_skip(s->pb, 4);
    }

Paul B Mahol's avatar
Paul B Mahol committed
224
    st->start_time = 0;
225
    st->duration = read32(s);
226
    avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
Paul B Mahol's avatar
Paul B Mahol committed
227

228
    if (!bfstm)
229
        start = read32(s);
Paul B Mahol's avatar
Paul B Mahol committed
230
    b->current_block = 0;
231
    b->block_count = read32(s);
Paul B Mahol's avatar
Paul B Mahol committed
232 233 234 235 236
    if (b->block_count > UINT16_MAX) {
        av_log(s, AV_LOG_WARNING, "too many blocks: %u\n", b->block_count);
        return AVERROR_INVALIDDATA;
    }

237
    b->block_size = read32(s);
238
    if (b->block_size > UINT32_MAX / st->codecpar->channels)
Paul B Mahol's avatar
Paul B Mahol committed
239 240
        return AVERROR_INVALIDDATA;

241 242
    b->samples_per_block = read32(s);
    b->last_block_used_bytes = read32(s);
243 244
    b->last_block_samples = read32(s);
    b->last_block_size = read32(s);
245
    if (b->last_block_size > UINT32_MAX / st->codecpar->channels)
246 247
        return AVERROR_INVALIDDATA;
    if (b->last_block_used_bytes > b->last_block_size)
Paul B Mahol's avatar
Paul B Mahol committed
248 249 250
        return AVERROR_INVALIDDATA;


251
    if (codec == AV_CODEC_ID_ADPCM_THP || codec == AV_CODEC_ID_ADPCM_THP_LE) {
Paul B Mahol's avatar
Paul B Mahol committed
252 253 254
        int ch;

        avio_skip(s->pb, pos + toffset - avio_tell(s->pb));
255
        if (!bfstm)
256
            toffset = read32(s) + 16LL;
257
        else
258
            toffset = toffset + read32(s) + st->codecpar->channels * 8 - 8;
Paul B Mahol's avatar
Paul B Mahol committed
259 260 261 262
        if (toffset > size)
            return AVERROR_INVALIDDATA;

        avio_skip(s->pb, pos + toffset - avio_tell(s->pb));
263
        b->table = av_mallocz(32 * st->codecpar->channels);
Paul B Mahol's avatar
Paul B Mahol committed
264 265 266
        if (!b->table)
            return AVERROR(ENOMEM);

267
        for (ch = 0; ch < st->codecpar->channels; ch++) {
Paul B Mahol's avatar
Paul B Mahol committed
268 269 270 271
            if (avio_read(s->pb, b->table + ch * 32, 32) != 32) {
                ret = AVERROR_INVALIDDATA;
                goto fail;
            }
272
            avio_skip(s->pb, bfstm ? 14 : 24);
Paul B Mahol's avatar
Paul B Mahol committed
273 274 275 276 277 278 279
        }
    }

    if (size < (avio_tell(s->pb) - pos)) {
        ret = AVERROR_INVALIDDATA;
        goto fail;
    }
280

281
    avio_skip(s->pb, size - (avio_tell(s->pb) - pos));
Paul B Mahol's avatar
Paul B Mahol committed
282

283
    while (!avio_feof(s->pb)) {
Paul B Mahol's avatar
Paul B Mahol committed
284
        chunk = avio_rl32(s->pb);
285
        size  = read32(s);
Paul B Mahol's avatar
Paul B Mahol committed
286 287 288 289 290 291
        if (size < 8) {
            ret = AVERROR_INVALIDDATA;
            goto fail;
        }
        size -= 8;
        switch (chunk) {
292
        case MKTAG('S','E','E','K'):
Paul B Mahol's avatar
Paul B Mahol committed
293
        case MKTAG('A','D','P','C'):
294 295
            if (codec != AV_CODEC_ID_ADPCM_THP &&
                codec != AV_CODEC_ID_ADPCM_THP_LE)
Paul B Mahol's avatar
Paul B Mahol committed
296 297
                goto skip;

298
            asize = b->block_count * st->codecpar->channels * 4;
Paul B Mahol's avatar
Paul B Mahol committed
299 300 301 302 303
            if (size < asize) {
                ret = AVERROR_INVALIDDATA;
                goto fail;
            }
            if (b->adpc) {
Lou Logan's avatar
Lou Logan committed
304
                av_log(s, AV_LOG_WARNING, "skipping additional ADPC chunk\n");
Paul B Mahol's avatar
Paul B Mahol committed
305 306 307 308 309 310 311
                goto skip;
            } else {
                b->adpc = av_mallocz(asize);
                if (!b->adpc) {
                    ret = AVERROR(ENOMEM);
                    goto fail;
                }
312 313 314 315 316 317 318 319 320 321 322
                if (bfstm && codec != AV_CODEC_ID_ADPCM_THP_LE) {
                    // Big-endian BFSTMs have little-endian SEEK tables
                    // for some strange reason.
                    int i;
                    for (i = 0; i < asize; i += 2) {
                        b->adpc[i+1] = avio_r8(s->pb);
                        b->adpc[i]   = avio_r8(s->pb);
                    }
                } else {
                    avio_read(s->pb, b->adpc, asize);
                }
Paul B Mahol's avatar
Paul B Mahol committed
323 324 325 326 327
                avio_skip(s->pb, size - asize);
            }
            break;
        case MKTAG('D','A','T','A'):
            if ((start < avio_tell(s->pb)) ||
328
                (!b->adpc && (codec == AV_CODEC_ID_ADPCM_THP ||
329
                              codec == AV_CODEC_ID_ADPCM_THP_LE))) {
Paul B Mahol's avatar
Paul B Mahol committed
330 331 332 333
                ret = AVERROR_INVALIDDATA;
                goto fail;
            }
            avio_skip(s->pb, start - avio_tell(s->pb));
334

335 336 337 338
            if (bfstm && (codec == AV_CODEC_ID_ADPCM_THP ||
                          codec == AV_CODEC_ID_ADPCM_THP_LE))
                avio_skip(s->pb, 24);

339 340
            b->data_start = avio_tell(s->pb);

341
            if (!bfstm && (major != 1 || minor))
342
                avpriv_request_sample(s, "Version %d.%d", major, minor);
343

Paul B Mahol's avatar
Paul B Mahol committed
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
            return 0;
        default:
            av_log(s, AV_LOG_WARNING, "skipping unknown chunk: %X\n", chunk);
skip:
            avio_skip(s->pb, size);
        }
    }

fail:
    read_close(s);

    return ret;
}

static int read_packet(AVFormatContext *s, AVPacket *pkt)
{
360
    AVCodecParameters *par = s->streams[0]->codecpar;
Paul B Mahol's avatar
Paul B Mahol committed
361
    BRSTMDemuxContext *b = s->priv_data;
362 363
    uint32_t samples, size, skip = 0;
    int ret, i;
Paul B Mahol's avatar
Paul B Mahol committed
364

365
    if (avio_feof(s->pb))
Paul B Mahol's avatar
Paul B Mahol committed
366 367 368 369
        return AVERROR_EOF;
    b->current_block++;
    if (b->current_block == b->block_count) {
        size    = b->last_block_used_bytes;
370 371
        samples = b->last_block_samples;
        skip    = b->last_block_size - b->last_block_used_bytes;
372 373 374 375 376 377 378 379 380

        if (samples < size * 14 / 8) {
            uint32_t adjusted_size = samples / 14 * 8;
            if (samples % 14)
                adjusted_size += (samples % 14 + 1) / 2 + 1;

            skip += size - adjusted_size;
            size = adjusted_size;
        }
Paul B Mahol's avatar
Paul B Mahol committed
381 382 383 384 385 386 387
    } else if (b->current_block < b->block_count) {
        size    = b->block_size;
        samples = b->samples_per_block;
    } else {
        return AVERROR_EOF;
    }

388 389
    if (par->codec_id == AV_CODEC_ID_ADPCM_THP ||
        par->codec_id == AV_CODEC_ID_ADPCM_THP_LE) {
Paul B Mahol's avatar
Paul B Mahol committed
390 391
        uint8_t *dst;

392 393 394
        if (!b->adpc) {
            av_log(s, AV_LOG_ERROR, "adpcm_thp requires ADPC chunk, but none was found.\n");
            return AVERROR_INVALIDDATA;
395
        }
396
        if (!b->table) {
397
            b->table = av_mallocz(32 * par->channels);
398 399
            if (!b->table)
                return AVERROR(ENOMEM);
400 401
        }

402
        if (size > (INT_MAX - 32 - 4) ||
403 404
            (32 + 4 + size) > (INT_MAX / par->channels) ||
            (32 + 4 + size) * par->channels > INT_MAX - 8)
405
            return AVERROR_INVALIDDATA;
406
        if (av_new_packet(pkt, 8 + (32 + 4 + size) * par->channels) < 0)
Paul B Mahol's avatar
Paul B Mahol committed
407 408
            return AVERROR(ENOMEM);
        dst = pkt->data;
409 410
        if (par->codec_id == AV_CODEC_ID_ADPCM_THP_LE) {
            bytestream_put_le32(&dst, size * par->channels);
411 412
            bytestream_put_le32(&dst, samples);
        } else {
413
            bytestream_put_be32(&dst, size * par->channels);
414 415
            bytestream_put_be32(&dst, samples);
        }
416 417 418
        bytestream_put_buffer(&dst, b->table, 32 * par->channels);
        bytestream_put_buffer(&dst, b->adpc + 4 * par->channels *
                                    (b->current_block - 1), 4 * par->channels);
Paul B Mahol's avatar
Paul B Mahol committed
419

420
        for (i = 0; i < par->channels; i++) {
421 422 423 424
            ret = avio_read(s->pb, dst, size);
            dst += size;
            avio_skip(s->pb, skip);
            if (ret != size) {
425
                av_packet_unref(pkt);
426 427 428
                break;
            }
        }
Paul B Mahol's avatar
Paul B Mahol committed
429 430
        pkt->duration = samples;
    } else {
431
        size *= par->channels;
Paul B Mahol's avatar
Paul B Mahol committed
432 433 434 435 436
        ret = av_get_packet(s->pb, pkt, size);
    }

    pkt->stream_index = 0;

437 438 439
    if (ret != size)
        ret = AVERROR(EIO);

Paul B Mahol's avatar
Paul B Mahol committed
440 441 442
    return ret;
}

443 444 445 446 447 448 449 450 451
static int read_seek(AVFormatContext *s, int stream_index,
                     int64_t timestamp, int flags)
{
    AVStream *st = s->streams[stream_index];
    BRSTMDemuxContext *b = s->priv_data;
    int64_t ret = 0;

    timestamp /= b->samples_per_block;
    ret = avio_seek(s->pb, b->data_start + timestamp * b->block_size *
452
                           st->codecpar->channels, SEEK_SET);
453 454 455 456 457 458 459 460
    if (ret < 0)
        return ret;

    b->current_block = timestamp;
    ff_update_cur_dts(s, st, timestamp * b->samples_per_block);
    return 0;
}

Paul B Mahol's avatar
Paul B Mahol committed
461 462 463 464 465 466 467 468
AVInputFormat ff_brstm_demuxer = {
    .name           = "brstm",
    .long_name      = NULL_IF_CONFIG_SMALL("BRSTM (Binary Revolution Stream)"),
    .priv_data_size = sizeof(BRSTMDemuxContext),
    .read_probe     = probe,
    .read_header    = read_header,
    .read_packet    = read_packet,
    .read_close     = read_close,
469
    .read_seek      = read_seek,
Paul B Mahol's avatar
Paul B Mahol committed
470 471
    .extensions     = "brstm",
};
472 473 474 475 476 477 478 479 480

AVInputFormat ff_bfstm_demuxer = {
    .name           = "bfstm",
    .long_name      = NULL_IF_CONFIG_SMALL("BFSTM (Binary Cafe Stream)"),
    .priv_data_size = sizeof(BRSTMDemuxContext),
    .read_probe     = probe_bfstm,
    .read_header    = read_header,
    .read_packet    = read_packet,
    .read_close     = read_close,
481
    .read_seek      = read_seek,
482
    .extensions     = "bfstm,bcstm",
483
};