]> git.sesse.net Git - ffmpeg/blob - libavformat/argo_brp.c
avformat/argo_brp: use header frame counts
[ffmpeg] / libavformat / argo_brp.c
1 /*
2  * Argonaut Games BRP Demuxer
3  *
4  * Copyright (C) 2020 Zane van Iperen (zane@zanevaniperen.com)
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 #include "avformat.h"
24 #include "internal.h"
25 #include "libavutil/intreadwrite.h"
26 #include "libavutil/avassert.h"
27 #include "libavutil/internal.h"
28 #include "argo_asf.h"
29
30 #define BRP_TAG                 MKTAG('B', 'R', 'P', 'P')
31 #define BRP_FILE_HEADER_SIZE    12
32 #define BRP_BLOCK_HEADER_SIZE   12
33 #define BRP_STREAM_HEADER_SIZE  20
34 #define BRP_MAX_STREAMS         32 /* Soft cap, but even this is overkill. */
35 #define BRP_BASF_LOOKAHEAD      10 /* How many blocks to search for the first BASF one. */
36 #define BVID_HEADER_SIZE        16
37 #define MASK_HEADER_SIZE        12
38 #define BRP_MIN_BUFFER_SIZE     FFMAX3(FFMAX3(BRP_FILE_HEADER_SIZE,    \
39                                               BRP_BLOCK_HEADER_SIZE,   \
40                                               BRP_STREAM_HEADER_SIZE), \
41                                       BVID_HEADER_SIZE,                \
42                                       MASK_HEADER_SIZE)
43
44 #define BRP_CODEC_ID_BVID       MKTAG('B', 'V', 'I', 'D')
45 #define BRP_CODEC_ID_BASF       MKTAG('B', 'A', 'S', 'F')
46 #define BRP_CODEC_ID_MASK       MKTAG('M', 'A', 'S', 'K')
47
48 typedef struct ArgoBRPFileHeader {
49     uint32_t magic;
50     uint32_t num_streams;
51     uint32_t byte_rate;
52 } ArgoBRPFileHeader;
53
54 typedef struct ArgoBRPBlockHeader {
55     int32_t  stream_id;
56     uint32_t start_ms;
57     uint32_t size;
58 } ArgoBRPBlockHeader;
59
60 typedef struct ArgoBVIDHeader {
61     uint32_t num_frames;
62     uint32_t width;
63     uint32_t height;
64     uint32_t depth;
65 } ArgoBVIDHeader;
66
67 typedef struct ArgoMASKHeader {
68     uint32_t num_frames;
69     uint32_t width;
70     uint32_t height;
71 } ArgoMASKHeader;
72
73 typedef struct ArgoBRPStreamHeader {
74     uint32_t codec_id;
75     uint32_t id;
76     uint32_t duration_ms;
77     uint32_t byte_rate;
78     uint32_t extradata_size;
79     union
80     {
81         /* If codec_id == BRP_CODEC_ID_BVID */
82         ArgoBVIDHeader    bvid;
83         /* If codec_id == BRP_CODEC_ID_BASF */
84         ArgoASFFileHeader basf;
85         /* If codec_id == BRP_CODEC_ID_MASK */
86         ArgoMASKHeader    mask;
87     } extradata;
88 } ArgoBRPStreamHeader;
89
90 typedef struct ArgoBRPDemuxContext {
91     ArgoBRPFileHeader   fhdr;
92     ArgoBRPStreamHeader streams[BRP_MAX_STREAMS];
93
94     struct {
95         int                 index;
96         ArgoASFChunkHeader  ckhdr;
97     } basf;
98 } ArgoBRPDemuxContext;
99
100 static int argo_brp_probe(const AVProbeData *p)
101 {
102     if (AV_RL32(p->buf) != BRP_TAG)
103         return 0;
104
105     return AVPROBE_SCORE_EXTENSION + 1;
106 }
107
108 static int read_extradata(AVFormatContext *s, const ArgoBRPStreamHeader *hdr,
109                           void *buf, size_t bufsz)
110 {
111     const char *name;
112     uint32_t size;
113     int64_t ret;
114
115     if (hdr->codec_id == BRP_CODEC_ID_BVID) {
116         name = "BVID";
117         size = BVID_HEADER_SIZE;
118     } else if (hdr->codec_id == BRP_CODEC_ID_BASF) {
119         name = "BASF";
120         size = ASF_FILE_HEADER_SIZE;
121     } else if (hdr->codec_id == BRP_CODEC_ID_MASK) {
122         name = "MASK";
123         size = MASK_HEADER_SIZE;
124     } else {
125         avpriv_request_sample(s, "BRP codec id 0x%x", hdr->codec_id);
126
127         if ((ret = avio_skip(s->pb, hdr->extradata_size)) < 0)
128             return ret;
129
130         return 1;
131     }
132
133     if (hdr->extradata_size != size) {
134         av_log(s, AV_LOG_ERROR, "Invalid %s extradata size %u, expected %u\n",
135                name, hdr->extradata_size, size);
136         return AVERROR_INVALIDDATA;
137     }
138
139     av_assert0(bufsz >= size);
140
141     if ((ret = avio_read(s->pb, buf, size)) < 0)
142         return ret;
143
144     if (ret != size)
145         return AVERROR(EIO);
146
147     return 0;
148 }
149
150 static int argo_brp_read_header(AVFormatContext *s)
151 {
152     int64_t ret;
153     AVIOContext *pb = s->pb;
154     ArgoBRPDemuxContext *brp = s->priv_data;
155     uint8_t buf[FFMAX(BRP_MIN_BUFFER_SIZE, ASF_MIN_BUFFER_SIZE)];
156
157     if ((ret = avio_read(pb, buf, BRP_FILE_HEADER_SIZE)) < 0)
158         return ret;
159     else if (ret != BRP_FILE_HEADER_SIZE)
160         return AVERROR(EIO);
161
162     brp->fhdr.magic       = AV_RL32(buf + 0);
163     brp->fhdr.num_streams = AV_RL32(buf + 4);
164     brp->fhdr.byte_rate   = AV_RL32(buf + 8);
165
166     if (brp->fhdr.magic != BRP_TAG)
167         return AVERROR_INVALIDDATA;
168
169     if (brp->fhdr.num_streams > BRP_MAX_STREAMS) {
170         avpriv_request_sample(s, ">%d streams", BRP_MAX_STREAMS);
171         return AVERROR_PATCHWELCOME;
172     }
173
174     /* Build the stream info. */
175     brp->basf.index = -1;
176     for (uint32_t i = 0; i < brp->fhdr.num_streams; i++) {
177         ArgoBRPStreamHeader *hdr = brp->streams + i;
178         AVStream *st;
179
180         if (!(st = avformat_new_stream(s, NULL)))
181             return AVERROR(ENOMEM);
182
183         if ((ret = avio_read(pb, buf, BRP_STREAM_HEADER_SIZE)) < 0)
184             return ret;
185         else if (ret != BRP_STREAM_HEADER_SIZE)
186             return AVERROR(EIO);
187
188         hdr->codec_id       = AV_RL32(buf + 0);
189         hdr->id             = AV_RL32(buf + 4);
190         hdr->duration_ms    = AV_RL32(buf + 8);
191         hdr->byte_rate      = AV_RL32(buf + 12);
192         hdr->extradata_size = AV_RL32(buf + 16);
193
194         /* This should always be the case. */
195         if (hdr->id != i)
196             return AVERROR_INVALIDDATA;
197
198         /* Timestamps are in milliseconds. */
199         avpriv_set_pts_info(st, 64, 1, 1000);
200         st->duration           = hdr->duration_ms;
201         st->codecpar->bit_rate = hdr->byte_rate * 8;
202
203         if ((ret = read_extradata(s, hdr, buf, sizeof(buf))) < 0) {
204             return ret;
205         } else if (ret > 0) {
206             st->codecpar->codec_type = AVMEDIA_TYPE_UNKNOWN;
207             continue;
208         }
209
210         if (hdr->codec_id == BRP_CODEC_ID_BVID) {
211             ArgoBVIDHeader *bvid = &hdr->extradata.bvid;
212
213             st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
214
215             /* No decoder for this yet. */
216             st->codecpar->codec_id   = AV_CODEC_ID_NONE;
217
218             bvid->num_frames = AV_RL32(buf +  0);
219             bvid->width      = AV_RL32(buf +  4);
220             bvid->height     = AV_RL32(buf +  8);
221             bvid->depth      = AV_RL32(buf + 12);
222
223             /* These are from 1990's games, sanity check this. */
224             if (bvid->width >= 65536 || bvid->height >= 65536 ||
225                 bvid->depth > 24     || bvid->depth % 8 != 0) {
226                 return AVERROR_INVALIDDATA;
227             }
228
229             st->codecpar->width  = bvid->width;
230             st->codecpar->height = bvid->height;
231
232             if (bvid->depth == 8) {
233                 st->codecpar->format = AV_PIX_FMT_PAL8;
234             } else if (bvid->depth == 24) {
235                 st->codecpar->format = AV_PIX_FMT_RGB24;
236             } else {
237                 avpriv_request_sample(s, "depth == %u", bvid->depth);
238                 return AVERROR_PATCHWELCOME;
239             }
240
241             st->nb_frames = bvid->num_frames;
242         } else if (hdr->codec_id == BRP_CODEC_ID_BASF) {
243             /*
244              * It would make the demuxer significantly more complicated
245              * to support multiple BASF streams. I've never seen a file
246              * with more than one.
247              */
248             if (brp->basf.index >= 0) {
249                 avpriv_request_sample(s, "Multiple BASF streams");
250                 return AVERROR_PATCHWELCOME;
251             }
252
253             st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
254             st->codecpar->codec_id   = AV_CODEC_ID_ADPCM_ARGO;
255             brp->basf.index          = i;
256             ff_argo_asf_parse_file_header(&hdr->extradata.basf, buf);
257
258             if ((ret = ff_argo_asf_validate_file_header(s, &hdr->extradata.basf)) < 0)
259                 return ret;
260
261             st->nb_frames = hdr->extradata.basf.num_chunks;
262         } else if (hdr->codec_id == BRP_CODEC_ID_MASK) {
263             ArgoMASKHeader *mask = &hdr->extradata.mask;
264
265             st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
266
267             mask->num_frames = AV_RL32(buf + 0);
268             mask->width      = AV_RL32(buf + 4);
269             mask->height     = AV_RL32(buf + 8);
270
271             st->nb_frames    = mask->num_frames;
272         } else {
273             av_assert0(0); /* Caught above, should never happen. */
274         }
275     }
276
277     /* Try to find the first BASF chunk. */
278     if (brp->basf.index >= 0) {
279         AVStream *st = s->streams[brp->basf.index];
280         ArgoBRPStreamHeader *hdr = brp->streams + brp->basf.index;
281         ArgoBRPBlockHeader blk;
282         int64_t offset;
283         int i;
284
285         av_assert0(st->codecpar->codec_id == AV_CODEC_ID_ADPCM_ARGO);
286         av_assert0(brp->streams[brp->basf.index].extradata_size == ASF_FILE_HEADER_SIZE);
287
288         if ((ret = avio_tell(s->pb)) < 0)
289             return ret;
290
291         offset = ret;
292
293         av_log(s, AV_LOG_TRACE, "Searching %d blocks for BASF...", BRP_BASF_LOOKAHEAD);
294
295         for (i = 0; i < BRP_BASF_LOOKAHEAD; i++) {
296             if ((ret = avio_read(pb, buf, BRP_BLOCK_HEADER_SIZE)) < 0)
297                 return ret;
298             else if (ret != BRP_BLOCK_HEADER_SIZE)
299                 return AVERROR(EIO);
300
301             blk.stream_id = AV_RL32(buf + 0);
302             blk.start_ms  = AV_RL32(buf + 4);
303             blk.size      = AV_RL32(buf + 8);
304
305             if (blk.stream_id == brp->basf.index || blk.stream_id == -1)
306                 break;
307
308             if ((ret = avio_skip(pb, blk.size)) < 0)
309                 return ret;
310         }
311
312         if (i == BRP_BASF_LOOKAHEAD || blk.stream_id == -1) {
313             /* Don't error here, as there may still be a valid video stream. */
314             av_log(s, AV_LOG_TRACE, "not found\n");
315             goto done;
316         }
317
318         av_log(s, AV_LOG_TRACE, "found at index %d\n", i);
319
320         if (blk.size < ASF_CHUNK_HEADER_SIZE)
321             return AVERROR_INVALIDDATA;
322
323         if ((ret = avio_read(pb, buf, ASF_CHUNK_HEADER_SIZE)) < 0)
324             return ret;
325         else if (ret != ASF_CHUNK_HEADER_SIZE)
326             return AVERROR(EIO);
327
328         ff_argo_asf_parse_chunk_header(&brp->basf.ckhdr, buf);
329
330         /*
331          * Special Case Hack. It seems that in files where the BASF block isn't first,
332          * v1.1 streams are allowed to be non-22050...
333          * Bump the version to 1.2 so ff_argo_asf_fill_stream() doesn't "correct" it.
334          *
335          * Found in Alien Odyssey games files in:
336          * ./GRAPHICS/COMMBUNK/{{COMADD1,COMM2_{1,2,3E},COMM3_{2,3,4,5,6}},FADE{1,2}}.BRP
337          *
338          * Either this format really inconsistent, or FX Fighter and Croc just ignored the
339          * sample rate field...
340          */
341         if (i != 0 && hdr->extradata.basf.version_major == 1 && hdr->extradata.basf.version_minor == 1)
342             hdr->extradata.basf.version_minor = 2;
343
344         if ((ret = ff_argo_asf_fill_stream(s, st, &hdr->extradata.basf, &brp->basf.ckhdr)) < 0)
345             return ret;
346
347         /* Convert ms to samples. */
348         st->start_time = av_rescale_rnd(blk.start_ms, st->codecpar->sample_rate, 1000, AV_ROUND_UP);
349         st->duration   = av_rescale_rnd(hdr->duration_ms, st->codecpar->sample_rate, 1000, AV_ROUND_UP);
350
351 done:
352         if ((ret = avio_seek(s->pb, offset, SEEK_SET)) < 0)
353             return ret;
354     }
355     return 0;
356 }
357
358 static int argo_brp_read_packet(AVFormatContext *s, AVPacket *pkt)
359 {
360     ArgoBRPDemuxContext *brp = s->priv_data;
361     ArgoBRPBlockHeader blk;
362     const ArgoBRPStreamHeader *shdr;
363     AVStream *st;
364     uint8_t buf[BRP_MIN_BUFFER_SIZE];
365     ArgoASFChunkHeader ckhdr;
366     int ret;
367
368     if ((ret = avio_read(s->pb, buf, BRP_BLOCK_HEADER_SIZE)) < 0)
369         return ret;
370     else if (ret != BRP_BLOCK_HEADER_SIZE)
371         return AVERROR(EIO);
372
373     blk.stream_id = AV_RL32(buf + 0);
374     blk.start_ms  = AV_RL32(buf + 4);
375     blk.size      = AV_RL32(buf + 8);
376
377     if (blk.stream_id == -1)
378         return AVERROR_EOF;
379
380     if (blk.stream_id < -1 || blk.stream_id >= s->nb_streams)
381         return AVERROR_INVALIDDATA;
382
383     st = s->streams[blk.stream_id];
384     shdr = brp->streams + blk.stream_id;
385
386     if (blk.stream_id == brp->basf.index) {
387         if (blk.size < ASF_CHUNK_HEADER_SIZE)
388             return AVERROR_INVALIDDATA;
389
390         if ((ret = avio_read(s->pb, buf, ASF_CHUNK_HEADER_SIZE)) < 0)
391             return ret;
392
393         ff_argo_asf_parse_chunk_header(&ckhdr, buf);
394
395         /* Ensure the chunk attributes are the same. */
396         if (ckhdr.sample_rate != brp->basf.ckhdr.sample_rate ||
397             ckhdr.flags       != brp->basf.ckhdr.flags       ||
398             ckhdr.unk1        != brp->basf.ckhdr.unk1        ||
399             ckhdr.unk2        != brp->basf.ckhdr.unk2)
400             return AVERROR_INVALIDDATA;
401
402         blk.size -= ASF_CHUNK_HEADER_SIZE;
403
404         if (blk.size % st->codecpar->block_align != 0)
405             return AVERROR_INVALIDDATA;
406     }
407
408     if ((ret = av_get_packet(s->pb, pkt, blk.size)) < 0)
409         return ret;
410     else if (ret != blk.size)
411         return AVERROR_INVALIDDATA;
412
413     if (blk.stream_id == brp->basf.index) {
414         pkt->duration = ckhdr.num_samples * ckhdr.num_blocks;
415         pkt->pts      = av_rescale_rnd(blk.start_ms, ckhdr.sample_rate, 1000, AV_ROUND_UP);
416     } else if (shdr->codec_id == BRP_CODEC_ID_BVID) {
417         pkt->duration = av_rescale_rnd(1, st->duration, shdr->extradata.bvid.num_frames, AV_ROUND_UP);
418         pkt->pts      = blk.start_ms;
419     } else {
420         pkt->pts      = blk.start_ms;
421     }
422
423     pkt->stream_index = blk.stream_id;
424     return 0;
425 }
426
427 AVInputFormat ff_argo_brp_demuxer = {
428     .name           = "argo_brp",
429     .long_name      = NULL_IF_CONFIG_SMALL("Argonaut Games BRP"),
430     .priv_data_size = sizeof(ArgoBRPDemuxContext),
431     .read_probe     = argo_brp_probe,
432     .read_header    = argo_brp_read_header,
433     .read_packet    = argo_brp_read_packet,
434 };