]> git.sesse.net Git - ffmpeg/blob - libavformat/brstm.c
avformat/brstm: fix decoding brstm with custom coeff offsets
[ffmpeg] / libavformat / brstm.c
1 /*
2  * BRSTM demuxer
3  * Copyright (c) 2012 Paul B Mahol
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 "libavutil/intreadwrite.h"
23 #include "libavcodec/bytestream.h"
24 #include "avformat.h"
25 #include "internal.h"
26
27 typedef struct BRSTMCoeffOffset {
28     uint8_t  channel;
29     uint32_t offset;
30 } BRSTMCoeffOffset;
31
32 typedef struct BRSTMDemuxContext {
33     uint32_t    block_size;
34     uint32_t    block_count;
35     uint32_t    current_block;
36     uint32_t    samples_per_block;
37     uint32_t    last_block_used_bytes;
38     uint32_t    last_block_size;
39     uint32_t    last_block_samples;
40     uint32_t    data_start;
41     uint8_t     *table;
42     uint8_t     *adpc;
43     BRSTMCoeffOffset offsets[256];
44     int         little_endian;
45 } BRSTMDemuxContext;
46
47 static int probe(const AVProbeData *p)
48 {
49     if (AV_RL32(p->buf) == MKTAG('R','S','T','M') &&
50         (AV_RL16(p->buf + 4) == 0xFFFE ||
51          AV_RL16(p->buf + 4) == 0xFEFF))
52         return AVPROBE_SCORE_MAX / 3 * 2;
53     return 0;
54 }
55
56 static int probe_bfstm(const AVProbeData *p)
57 {
58     if ((AV_RL32(p->buf) == MKTAG('F','S','T','M') ||
59          AV_RL32(p->buf) == MKTAG('C','S','T','M')) &&
60         (AV_RL16(p->buf + 4) == 0xFFFE ||
61          AV_RL16(p->buf + 4) == 0xFEFF))
62         return AVPROBE_SCORE_MAX / 3 * 2;
63     return 0;
64 }
65
66 static int read_close(AVFormatContext *s)
67 {
68     BRSTMDemuxContext *b = s->priv_data;
69
70     av_freep(&b->table);
71     av_freep(&b->adpc);
72
73     return 0;
74 }
75
76 static int sort_offsets(const void *a, const void *b)
77 {
78     const BRSTMCoeffOffset *s1 = a;
79     const BRSTMCoeffOffset *s2 = b;
80     return FFDIFFSIGN(s1->offset, s2->offset);
81 }
82
83 static av_always_inline unsigned int read16(AVFormatContext *s)
84 {
85     BRSTMDemuxContext *b = s->priv_data;
86     if (b->little_endian)
87         return avio_rl16(s->pb);
88     else
89         return avio_rb16(s->pb);
90 }
91
92 static av_always_inline unsigned int read32(AVFormatContext *s)
93 {
94     BRSTMDemuxContext *b = s->priv_data;
95     if (b->little_endian)
96         return avio_rl32(s->pb);
97     else
98         return avio_rb32(s->pb);
99 }
100
101 static int read_header(AVFormatContext *s)
102 {
103     BRSTMDemuxContext *b = s->priv_data;
104     int bom, major, minor, codec, chunk;
105     int64_t h1offset, pos, toffset;
106     uint32_t size, asize, start = 0;
107     AVStream *st;
108     int ret = AVERROR_EOF;
109     int loop = 0;
110     int bfstm = !strcmp("bfstm", s->iformat->name);
111
112     st = avformat_new_stream(s, NULL);
113     if (!st)
114         return AVERROR(ENOMEM);
115     st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
116
117     avio_skip(s->pb, 4);
118
119     bom = avio_rb16(s->pb);
120     if (bom != 0xFEFF && bom != 0xFFFE) {
121         av_log(s, AV_LOG_ERROR, "invalid byte order: %X\n", bom);
122         return AVERROR_INVALIDDATA;
123     }
124
125     if (bom == 0xFFFE)
126         b->little_endian = 1;
127
128     if (!bfstm) {
129         major = avio_r8(s->pb);
130         minor = avio_r8(s->pb);
131         avio_skip(s->pb, 4); // size of file
132         size = read16(s);
133         if (size < 14)
134             return AVERROR_INVALIDDATA;
135
136         avio_skip(s->pb, size - 14);
137         pos = avio_tell(s->pb);
138         if (avio_rl32(s->pb) != MKTAG('H','E','A','D'))
139             return AVERROR_INVALIDDATA;
140     } else {
141         uint32_t info_offset = 0;
142         uint16_t section_count, header_size, i;
143
144         header_size = read16(s); // 6
145
146         avio_skip(s->pb, 4); // Unknown constant 0x00030000
147         avio_skip(s->pb, 4); // size of file
148         section_count = read16(s);
149         avio_skip(s->pb, 2); // padding
150         for (i = 0; avio_tell(s->pb) < header_size
151                     && !(start && info_offset)
152                     && i < section_count; i++) {
153             uint16_t flag = read16(s);
154             avio_skip(s->pb, 2);
155             switch (flag) {
156             case 0x4000:
157                 info_offset = read32(s);
158                 /*info_size =*/ read32(s);
159                 break;
160             case 0x4001:
161                 avio_skip(s->pb, 4); // seek offset
162                 avio_skip(s->pb, 4); // seek size
163                 break;
164             case 0x4002:
165                 start = read32(s) + 8;
166                 avio_skip(s->pb, 4); //data_size = read32(s);
167                 break;
168             case 0x4003:
169                 avio_skip(s->pb, 4); // REGN offset
170                 avio_skip(s->pb, 4); // REGN size
171                 break;
172             }
173         }
174
175         if (!info_offset || !start)
176             return AVERROR_INVALIDDATA;
177
178         avio_skip(s->pb, info_offset - avio_tell(s->pb));
179         pos = avio_tell(s->pb);
180         if (avio_rl32(s->pb) != MKTAG('I','N','F','O'))
181             return AVERROR_INVALIDDATA;
182     }
183
184     size = read32(s);
185     if (size < 40)
186         return AVERROR_INVALIDDATA;
187     avio_skip(s->pb, 4); // unknown
188     h1offset = read32(s);
189     if (h1offset > size)
190         return AVERROR_INVALIDDATA;
191     avio_skip(s->pb, 12);
192     toffset = read32(s) + 16LL;
193     if (toffset > size)
194         return AVERROR_INVALIDDATA;
195
196     avio_skip(s->pb, pos + h1offset + 8 - avio_tell(s->pb));
197     codec = avio_r8(s->pb);
198
199     switch (codec) {
200     case 0: codec = AV_CODEC_ID_PCM_S8_PLANAR;    break;
201     case 1: codec = b->little_endian ?
202                     AV_CODEC_ID_PCM_S16LE_PLANAR :
203                     AV_CODEC_ID_PCM_S16BE_PLANAR; break;
204     case 2: codec = b->little_endian ?
205                     AV_CODEC_ID_ADPCM_THP_LE :
206                     AV_CODEC_ID_ADPCM_THP;        break;
207     default:
208         avpriv_request_sample(s, "codec %d", codec);
209         return AVERROR_PATCHWELCOME;
210     }
211
212     loop = avio_r8(s->pb); // loop flag
213     st->codecpar->codec_id = codec;
214     st->codecpar->channels = avio_r8(s->pb);
215     if (!st->codecpar->channels)
216         return AVERROR_INVALIDDATA;
217
218     avio_skip(s->pb, 1); // padding
219
220     st->codecpar->sample_rate = bfstm ? read32(s) : read16(s);
221     if (st->codecpar->sample_rate <= 0)
222         return AVERROR_INVALIDDATA;
223
224     if (!bfstm)
225         avio_skip(s->pb, 2); // padding
226
227     if (loop) {
228         if (av_dict_set_int(&s->metadata, "loop_start",
229                             av_rescale(read32(s), AV_TIME_BASE,
230                                        st->codecpar->sample_rate),
231                             0) < 0)
232             return AVERROR(ENOMEM);
233     } else {
234         avio_skip(s->pb, 4);
235     }
236
237     st->start_time = 0;
238     st->duration = read32(s);
239     avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
240
241     if (!bfstm)
242         start = read32(s);
243     b->current_block = 0;
244     b->block_count = read32(s);
245     if (b->block_count > UINT16_MAX) {
246         av_log(s, AV_LOG_WARNING, "too many blocks: %"PRIu32"\n", b->block_count);
247         return AVERROR_INVALIDDATA;
248     }
249
250     b->block_size = read32(s);
251     if (b->block_size > UINT32_MAX / st->codecpar->channels)
252         return AVERROR_INVALIDDATA;
253
254     b->samples_per_block = read32(s);
255     b->last_block_used_bytes = read32(s);
256     b->last_block_samples = read32(s);
257     b->last_block_size = read32(s);
258     if (b->last_block_size > UINT32_MAX / st->codecpar->channels)
259         return AVERROR_INVALIDDATA;
260     if (b->last_block_used_bytes > b->last_block_size)
261         return AVERROR_INVALIDDATA;
262
263
264     if (codec == AV_CODEC_ID_ADPCM_THP || codec == AV_CODEC_ID_ADPCM_THP_LE) {
265         int ch;
266
267         avio_skip(s->pb, pos + toffset - avio_tell(s->pb));
268         if (!bfstm)
269             toffset = read32(s) + 16LL;
270         else
271             toffset = toffset + read32(s) + st->codecpar->channels * 8 - 8;
272         if (toffset > size)
273             return AVERROR_INVALIDDATA;
274
275         if (!bfstm) {
276             avio_skip(s->pb, pos + toffset - avio_tell(s->pb) - 8LL * (st->codecpar->channels + 1));
277             for (ch = 0; ch < st->codecpar->channels; ch++) {
278                 avio_skip(s->pb, 4);
279                 b->offsets[ch].channel = ch;
280                 b->offsets[ch].offset = read32(s);
281             }
282
283             qsort(b->offsets, st->codecpar->channels, sizeof(*b->offsets), sort_offsets);
284         }
285
286         avio_skip(s->pb, pos + toffset - avio_tell(s->pb));
287         b->table = av_mallocz(32 * st->codecpar->channels);
288         if (!b->table)
289             return AVERROR(ENOMEM);
290
291         for (ch = 0; ch < st->codecpar->channels; ch++) {
292             if (!bfstm)
293                 avio_skip(s->pb, pos + 16LL + b->offsets[ch].offset - avio_tell(s->pb));
294
295             if (avio_read(s->pb, b->table + ch * 32, 32) != 32) {
296                 ret = AVERROR_INVALIDDATA;
297                 goto fail;
298             }
299
300             if (bfstm)
301                 avio_skip(s->pb, 14);
302         }
303     }
304
305     if (size < (avio_tell(s->pb) - pos)) {
306         ret = AVERROR_INVALIDDATA;
307         goto fail;
308     }
309
310     avio_skip(s->pb, size - (avio_tell(s->pb) - pos));
311
312     while (!avio_feof(s->pb)) {
313         chunk = avio_rl32(s->pb);
314         size  = read32(s);
315         if (size < 8) {
316             ret = AVERROR_INVALIDDATA;
317             goto fail;
318         }
319         size -= 8;
320         switch (chunk) {
321         case MKTAG('S','E','E','K'):
322         case MKTAG('A','D','P','C'):
323             if (codec != AV_CODEC_ID_ADPCM_THP &&
324                 codec != AV_CODEC_ID_ADPCM_THP_LE)
325                 goto skip;
326
327             asize = b->block_count * st->codecpar->channels * 4;
328             if (size < asize) {
329                 ret = AVERROR_INVALIDDATA;
330                 goto fail;
331             }
332             if (b->adpc) {
333                 av_log(s, AV_LOG_WARNING, "skipping additional ADPC chunk\n");
334                 goto skip;
335             } else {
336                 b->adpc = av_mallocz(asize);
337                 if (!b->adpc) {
338                     ret = AVERROR(ENOMEM);
339                     goto fail;
340                 }
341                 if (bfstm && codec != AV_CODEC_ID_ADPCM_THP_LE) {
342                     // Big-endian BFSTMs have little-endian SEEK tables
343                     // for some strange reason.
344                     int i;
345                     for (i = 0; i < asize; i += 2) {
346                         b->adpc[i+1] = avio_r8(s->pb);
347                         b->adpc[i]   = avio_r8(s->pb);
348                     }
349                 } else {
350                     avio_read(s->pb, b->adpc, asize);
351                 }
352                 avio_skip(s->pb, size - asize);
353             }
354             break;
355         case MKTAG('D','A','T','A'):
356             if ((start < avio_tell(s->pb)) ||
357                 (!b->adpc && (codec == AV_CODEC_ID_ADPCM_THP ||
358                               codec == AV_CODEC_ID_ADPCM_THP_LE))) {
359                 ret = AVERROR_INVALIDDATA;
360                 goto fail;
361             }
362             avio_skip(s->pb, start - avio_tell(s->pb));
363
364             if (bfstm && (codec == AV_CODEC_ID_ADPCM_THP ||
365                           codec == AV_CODEC_ID_ADPCM_THP_LE))
366                 avio_skip(s->pb, 24);
367
368             b->data_start = avio_tell(s->pb);
369
370             if (!bfstm && (major != 1 || minor))
371                 avpriv_request_sample(s, "Version %d.%d", major, minor);
372
373             return 0;
374         default:
375             av_log(s, AV_LOG_WARNING, "skipping unknown chunk: %X\n", chunk);
376 skip:
377             avio_skip(s->pb, size);
378         }
379     }
380
381 fail:
382     read_close(s);
383
384     return ret;
385 }
386
387 static int read_packet(AVFormatContext *s, AVPacket *pkt)
388 {
389     AVCodecParameters *par = s->streams[0]->codecpar;
390     BRSTMDemuxContext *b = s->priv_data;
391     uint32_t samples, size, skip = 0;
392     int ret, i;
393
394     if (avio_feof(s->pb))
395         return AVERROR_EOF;
396     b->current_block++;
397     if (b->current_block == b->block_count) {
398         size    = b->last_block_used_bytes;
399         samples = b->last_block_samples;
400         skip    = b->last_block_size - b->last_block_used_bytes;
401
402         if (samples < size * 14 / 8) {
403             uint32_t adjusted_size = samples / 14 * 8;
404             if (samples % 14)
405                 adjusted_size += (samples % 14 + 1) / 2 + 1;
406
407             skip += size - adjusted_size;
408             size = adjusted_size;
409         }
410     } else if (b->current_block < b->block_count) {
411         size    = b->block_size;
412         samples = b->samples_per_block;
413     } else {
414         return AVERROR_EOF;
415     }
416
417     if (par->codec_id == AV_CODEC_ID_ADPCM_THP ||
418         par->codec_id == AV_CODEC_ID_ADPCM_THP_LE) {
419         uint8_t *dst;
420
421         if (!b->adpc) {
422             av_log(s, AV_LOG_ERROR, "adpcm_thp requires ADPC chunk, but none was found.\n");
423             return AVERROR_INVALIDDATA;
424         }
425         if (!b->table) {
426             b->table = av_mallocz(32 * par->channels);
427             if (!b->table)
428                 return AVERROR(ENOMEM);
429         }
430
431         if (size > (INT_MAX - 32 - 4) ||
432             (32 + 4 + size) > (INT_MAX / par->channels) ||
433             (32 + 4 + size) * par->channels > INT_MAX - 8)
434             return AVERROR_INVALIDDATA;
435         if ((ret = av_new_packet(pkt, 8 + (32 + 4 + size) * par->channels)) < 0)
436             return ret;
437         dst = pkt->data;
438         if (par->codec_id == AV_CODEC_ID_ADPCM_THP_LE) {
439             bytestream_put_le32(&dst, size * par->channels);
440             bytestream_put_le32(&dst, samples);
441         } else {
442             bytestream_put_be32(&dst, size * par->channels);
443             bytestream_put_be32(&dst, samples);
444         }
445         bytestream_put_buffer(&dst, b->table, 32 * par->channels);
446         bytestream_put_buffer(&dst, b->adpc + 4 * par->channels *
447                                     (b->current_block - 1), 4 * par->channels);
448
449         for (i = 0; i < par->channels; i++) {
450             ret = avio_read(s->pb, dst, size);
451             dst += size;
452             avio_skip(s->pb, skip);
453             if (ret != size) {
454                 return AVERROR(EIO);
455             }
456         }
457         pkt->duration = samples;
458     } else {
459         size *= par->channels;
460         ret = av_get_packet(s->pb, pkt, size);
461     }
462
463     pkt->stream_index = 0;
464
465     if (ret != size)
466         ret = AVERROR(EIO);
467
468     return ret;
469 }
470
471 static int read_seek(AVFormatContext *s, int stream_index,
472                      int64_t timestamp, int flags)
473 {
474     AVStream *st = s->streams[stream_index];
475     BRSTMDemuxContext *b = s->priv_data;
476     int64_t ret = 0;
477
478     if (timestamp < 0)
479         timestamp = 0;
480     timestamp /= b->samples_per_block;
481     if (timestamp >= b->block_count)
482         timestamp = b->block_count - 1;
483     ret = avio_seek(s->pb, b->data_start + timestamp * b->block_size *
484                            st->codecpar->channels, SEEK_SET);
485     if (ret < 0)
486         return ret;
487
488     b->current_block = timestamp;
489     ff_update_cur_dts(s, st, timestamp * b->samples_per_block);
490     return 0;
491 }
492
493 AVInputFormat ff_brstm_demuxer = {
494     .name           = "brstm",
495     .long_name      = NULL_IF_CONFIG_SMALL("BRSTM (Binary Revolution Stream)"),
496     .priv_data_size = sizeof(BRSTMDemuxContext),
497     .read_probe     = probe,
498     .read_header    = read_header,
499     .read_packet    = read_packet,
500     .read_close     = read_close,
501     .read_seek      = read_seek,
502     .extensions     = "brstm",
503 };
504
505 AVInputFormat ff_bfstm_demuxer = {
506     .name           = "bfstm",
507     .long_name      = NULL_IF_CONFIG_SMALL("BFSTM (Binary Cafe Stream)"),
508     .priv_data_size = sizeof(BRSTMDemuxContext),
509     .read_probe     = probe_bfstm,
510     .read_header    = read_header,
511     .read_packet    = read_packet,
512     .read_close     = read_close,
513     .read_seek      = read_seek,
514     .extensions     = "bfstm,bcstm",
515 };