libavformat/brstm.c
9a319979
 /*
  * 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;
70a39bcf
     uint32_t    last_block_size;
     uint32_t    last_block_samples;
9c9cf395
     uint32_t    data_start;
9a319979
     uint8_t     *table;
     uint8_t     *adpc;
d4c9eced
     int         little_endian;
9a319979
 } BRSTMDemuxContext;
 
4d8875ec
 static int probe(const AVProbeData *p)
9a319979
 {
     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;
 }
 
4d8875ec
 static int probe_bfstm(const AVProbeData *p)
bb42a7d4
 {
d4c9eced
     if ((AV_RL32(p->buf) == MKTAG('F','S','T','M') ||
          AV_RL32(p->buf) == MKTAG('C','S','T','M')) &&
bb42a7d4
         (AV_RL16(p->buf + 4) == 0xFFFE ||
          AV_RL16(p->buf + 4) == 0xFEFF))
         return AVPROBE_SCORE_MAX / 3 * 2;
     return 0;
 }
 
9a319979
 static int read_close(AVFormatContext *s)
 {
     BRSTMDemuxContext *b = s->priv_data;
 
     av_freep(&b->table);
     av_freep(&b->adpc);
 
     return 0;
 }
 
d4c9eced
 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);
 }
 
9a319979
 static int read_header(AVFormatContext *s)
 {
     BRSTMDemuxContext *b = s->priv_data;
     int bom, major, minor, codec, chunk;
70a39bcf
     int64_t h1offset, pos, toffset;
     uint32_t size, asize, start = 0;
9a319979
     AVStream *st;
     int ret = AVERROR_EOF;
0643b4bf
     int loop = 0;
6c56827e
     int bfstm = !strcmp("bfstm", s->iformat->name);
bb42a7d4
 
9a319979
     st = avformat_new_stream(s, NULL);
     if (!st)
         return AVERROR(ENOMEM);
6f69f7a8
     st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
9a319979
 
     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;
     }
d4c9eced
 
     if (bom == 0xFFFE)
         b->little_endian = 1;
9a319979
 
6c56827e
     if (!bfstm) {
bb42a7d4
         major = avio_r8(s->pb);
         minor = avio_r8(s->pb);
         avio_skip(s->pb, 4); // size of file
d4c9eced
         size = read16(s);
bb42a7d4
         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 {
cdb0d7e4
         uint32_t info_offset = 0;
bb42a7d4
         uint16_t section_count, header_size, i;
 
d4c9eced
         header_size = read16(s); // 6
bb42a7d4
 
         avio_skip(s->pb, 4); // Unknown constant 0x00030000
         avio_skip(s->pb, 4); // size of file
d4c9eced
         section_count = read16(s);
bb42a7d4
         avio_skip(s->pb, 2); // padding
         for (i = 0; avio_tell(s->pb) < header_size
70a39bcf
                     && !(start && info_offset)
bb42a7d4
                     && i < section_count; i++) {
d4c9eced
             uint16_t flag = read16(s);
             avio_skip(s->pb, 2);
bb42a7d4
             switch (flag) {
d4c9eced
             case 0x4000:
                 info_offset = read32(s);
cdb0d7e4
                 /*info_size =*/ read32(s);
bb42a7d4
                 break;
d4c9eced
             case 0x4001:
bb42a7d4
                 avio_skip(s->pb, 4); // seek offset
                 avio_skip(s->pb, 4); // seek size
                 break;
d4c9eced
             case 0x4002:
70a39bcf
                 start = read32(s) + 8;
d4c9eced
                 avio_skip(s->pb, 4); //data_size = read32(s);
bb42a7d4
                 break;
d4c9eced
             case 0x4003:
bb42a7d4
                 avio_skip(s->pb, 4); // REGN offset
                 avio_skip(s->pb, 4); // REGN size
                 break;
             }
         }
 
70a39bcf
         if (!info_offset || !start)
bb42a7d4
             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;
     }
9a319979
 
d4c9eced
     size = read32(s);
76466ab2
     if (size < 40)
9a319979
         return AVERROR_INVALIDDATA;
     avio_skip(s->pb, 4); // unknown
d4c9eced
     h1offset = read32(s);
9a319979
     if (h1offset > size)
         return AVERROR_INVALIDDATA;
     avio_skip(s->pb, 12);
d4c9eced
     toffset = read32(s) + 16LL;
9a319979
     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;
a49154e9
     case 1: codec = b->little_endian ?
                     AV_CODEC_ID_PCM_S16LE_PLANAR :
                     AV_CODEC_ID_PCM_S16BE_PLANAR; break;
d4c9eced
     case 2: codec = b->little_endian ?
                     AV_CODEC_ID_ADPCM_THP_LE :
                     AV_CODEC_ID_ADPCM_THP;        break;
9a319979
     default:
a9b42487
         avpriv_request_sample(s, "codec %d", codec);
9a319979
         return AVERROR_PATCHWELCOME;
     }
 
0643b4bf
     loop = avio_r8(s->pb); // loop flag
6f69f7a8
     st->codecpar->codec_id = codec;
     st->codecpar->channels = avio_r8(s->pb);
     if (!st->codecpar->channels)
9a319979
         return AVERROR_INVALIDDATA;
 
     avio_skip(s->pb, 1); // padding
bb42a7d4
 
6f69f7a8
     st->codecpar->sample_rate = bfstm ? read32(s) : read16(s);
     if (st->codecpar->sample_rate <= 0)
9a319979
         return AVERROR_INVALIDDATA;
 
6c56827e
     if (!bfstm)
bb42a7d4
         avio_skip(s->pb, 2); // padding
0643b4bf
 
     if (loop) {
         if (av_dict_set_int(&s->metadata, "loop_start",
                             av_rescale(read32(s), AV_TIME_BASE,
6f69f7a8
                                        st->codecpar->sample_rate),
0643b4bf
                             0) < 0)
             return AVERROR(ENOMEM);
     } else {
         avio_skip(s->pb, 4);
     }
 
9a319979
     st->start_time = 0;
d4c9eced
     st->duration = read32(s);
6f69f7a8
     avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
9a319979
 
6c56827e
     if (!bfstm)
d4c9eced
         start = read32(s);
9a319979
     b->current_block = 0;
d4c9eced
     b->block_count = read32(s);
9a319979
     if (b->block_count > UINT16_MAX) {
54904525
         av_log(s, AV_LOG_WARNING, "too many blocks: %"PRIu32"\n", b->block_count);
9a319979
         return AVERROR_INVALIDDATA;
     }
 
d4c9eced
     b->block_size = read32(s);
6f69f7a8
     if (b->block_size > UINT32_MAX / st->codecpar->channels)
9a319979
         return AVERROR_INVALIDDATA;
 
d4c9eced
     b->samples_per_block = read32(s);
     b->last_block_used_bytes = read32(s);
70a39bcf
     b->last_block_samples = read32(s);
     b->last_block_size = read32(s);
6f69f7a8
     if (b->last_block_size > UINT32_MAX / st->codecpar->channels)
70a39bcf
         return AVERROR_INVALIDDATA;
     if (b->last_block_used_bytes > b->last_block_size)
9a319979
         return AVERROR_INVALIDDATA;
 
 
d4c9eced
     if (codec == AV_CODEC_ID_ADPCM_THP || codec == AV_CODEC_ID_ADPCM_THP_LE) {
9a319979
         int ch;
 
         avio_skip(s->pb, pos + toffset - avio_tell(s->pb));
6c56827e
         if (!bfstm)
d4c9eced
             toffset = read32(s) + 16LL;
bb42a7d4
         else
6f69f7a8
             toffset = toffset + read32(s) + st->codecpar->channels * 8 - 8;
9a319979
         if (toffset > size)
             return AVERROR_INVALIDDATA;
 
         avio_skip(s->pb, pos + toffset - avio_tell(s->pb));
6f69f7a8
         b->table = av_mallocz(32 * st->codecpar->channels);
9a319979
         if (!b->table)
             return AVERROR(ENOMEM);
 
6f69f7a8
         for (ch = 0; ch < st->codecpar->channels; ch++) {
9a319979
             if (avio_read(s->pb, b->table + ch * 32, 32) != 32) {
                 ret = AVERROR_INVALIDDATA;
                 goto fail;
             }
70a39bcf
             avio_skip(s->pb, bfstm ? 14 : 24);
9a319979
         }
     }
 
     if (size < (avio_tell(s->pb) - pos)) {
         ret = AVERROR_INVALIDDATA;
         goto fail;
     }
bb42a7d4
 
6c56827e
     avio_skip(s->pb, size - (avio_tell(s->pb) - pos));
9a319979
 
d34ec64a
     while (!avio_feof(s->pb)) {
9a319979
         chunk = avio_rl32(s->pb);
d4c9eced
         size  = read32(s);
9a319979
         if (size < 8) {
             ret = AVERROR_INVALIDDATA;
             goto fail;
         }
         size -= 8;
         switch (chunk) {
70a39bcf
         case MKTAG('S','E','E','K'):
9a319979
         case MKTAG('A','D','P','C'):
d4c9eced
             if (codec != AV_CODEC_ID_ADPCM_THP &&
                 codec != AV_CODEC_ID_ADPCM_THP_LE)
9a319979
                 goto skip;
 
6f69f7a8
             asize = b->block_count * st->codecpar->channels * 4;
9a319979
             if (size < asize) {
                 ret = AVERROR_INVALIDDATA;
                 goto fail;
             }
             if (b->adpc) {
88f2586a
                 av_log(s, AV_LOG_WARNING, "skipping additional ADPC chunk\n");
9a319979
                 goto skip;
             } else {
                 b->adpc = av_mallocz(asize);
                 if (!b->adpc) {
                     ret = AVERROR(ENOMEM);
                     goto fail;
                 }
d2ce1009
                 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);
                 }
9a319979
                 avio_skip(s->pb, size - asize);
             }
             break;
         case MKTAG('D','A','T','A'):
             if ((start < avio_tell(s->pb)) ||
d4c9eced
                 (!b->adpc && (codec == AV_CODEC_ID_ADPCM_THP ||
70a39bcf
                               codec == AV_CODEC_ID_ADPCM_THP_LE))) {
9a319979
                 ret = AVERROR_INVALIDDATA;
                 goto fail;
             }
             avio_skip(s->pb, start - avio_tell(s->pb));
de89dff8
 
70a39bcf
             if (bfstm && (codec == AV_CODEC_ID_ADPCM_THP ||
                           codec == AV_CODEC_ID_ADPCM_THP_LE))
                 avio_skip(s->pb, 24);
 
9c9cf395
             b->data_start = avio_tell(s->pb);
 
58d7dde0
             if (!bfstm && (major != 1 || minor))
a9b42487
                 avpriv_request_sample(s, "Version %d.%d", major, minor);
de89dff8
 
9a319979
             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)
 {
6f69f7a8
     AVCodecParameters *par = s->streams[0]->codecpar;
9a319979
     BRSTMDemuxContext *b = s->priv_data;
70a39bcf
     uint32_t samples, size, skip = 0;
     int ret, i;
9a319979
 
d34ec64a
     if (avio_feof(s->pb))
9a319979
         return AVERROR_EOF;
     b->current_block++;
     if (b->current_block == b->block_count) {
         size    = b->last_block_used_bytes;
70a39bcf
         samples = b->last_block_samples;
         skip    = b->last_block_size - b->last_block_used_bytes;
68f00fb4
 
         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;
         }
9a319979
     } else if (b->current_block < b->block_count) {
         size    = b->block_size;
         samples = b->samples_per_block;
     } else {
         return AVERROR_EOF;
     }
 
6f69f7a8
     if (par->codec_id == AV_CODEC_ID_ADPCM_THP ||
         par->codec_id == AV_CODEC_ID_ADPCM_THP_LE) {
9a319979
         uint8_t *dst;
 
d7d37c47
         if (!b->adpc) {
             av_log(s, AV_LOG_ERROR, "adpcm_thp requires ADPC chunk, but none was found.\n");
             return AVERROR_INVALIDDATA;
1cb2331e
         }
bcf4ee26
         if (!b->table) {
6f69f7a8
             b->table = av_mallocz(32 * par->channels);
bcf4ee26
             if (!b->table)
                 return AVERROR(ENOMEM);
d7d37c47
         }
 
3441fef0
         if (size > (INT_MAX - 32 - 4) ||
6f69f7a8
             (32 + 4 + size) > (INT_MAX / par->channels) ||
             (32 + 4 + size) * par->channels > INT_MAX - 8)
3441fef0
             return AVERROR_INVALIDDATA;
c1e439d7
         if ((ret = av_new_packet(pkt, 8 + (32 + 4 + size) * par->channels)) < 0)
             return ret;
9a319979
         dst = pkt->data;
6f69f7a8
         if (par->codec_id == AV_CODEC_ID_ADPCM_THP_LE) {
             bytestream_put_le32(&dst, size * par->channels);
70a39bcf
             bytestream_put_le32(&dst, samples);
         } else {
6f69f7a8
             bytestream_put_be32(&dst, size * par->channels);
70a39bcf
             bytestream_put_be32(&dst, samples);
         }
6f69f7a8
         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);
9a319979
 
6f69f7a8
         for (i = 0; i < par->channels; i++) {
70a39bcf
             ret = avio_read(s->pb, dst, size);
             dst += size;
             avio_skip(s->pb, skip);
             if (ret != size) {
6a67d518
                 return AVERROR(EIO);
70a39bcf
             }
         }
9a319979
         pkt->duration = samples;
     } else {
6f69f7a8
         size *= par->channels;
9a319979
         ret = av_get_packet(s->pb, pkt, size);
     }
 
     pkt->stream_index = 0;
 
fe63d413
     if (ret != size)
         ret = AVERROR(EIO);
 
9a319979
     return ret;
 }
 
9c9cf395
 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 *
6f69f7a8
                            st->codecpar->channels, SEEK_SET);
9c9cf395
     if (ret < 0)
         return ret;
 
     b->current_block = timestamp;
     ff_update_cur_dts(s, st, timestamp * b->samples_per_block);
     return 0;
 }
 
9a319979
 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,
9c9cf395
     .read_seek      = read_seek,
9a319979
     .extensions     = "brstm",
 };
bb42a7d4
 
 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,
9c9cf395
     .read_seek      = read_seek,
d4c9eced
     .extensions     = "bfstm,bcstm",
bb42a7d4
 };