]> git.sesse.net Git - ffmpeg/blob - libavformat/argo_asf.c
avformat/argo_asf: bail if invalid tag
[ffmpeg] / libavformat / argo_asf.c
1 /*
2  * Argonaut Games ASF (de)muxer
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 #include "avformat.h"
23 #include "internal.h"
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/avassert.h"
26 #include "libavutil/opt.h"
27
28 #define ASF_TAG                 MKTAG('A', 'S', 'F', '\0')
29 #define ASF_FILE_HEADER_SIZE    24
30 #define ASF_CHUNK_HEADER_SIZE   20
31 #define ASF_SAMPLE_COUNT        32
32
33 typedef struct ArgoASFFileHeader {
34     uint32_t    magic;          /*< Magic Number, {'A', 'S', 'F', '\0'} */
35     uint16_t    version_major;  /*< File Major Version. */
36     uint16_t    version_minor;  /*< File Minor Version. */
37     uint32_t    num_chunks;     /*< No. chunks in the file. */
38     uint32_t    chunk_offset;   /*< Offset to the first chunk from the start of the file. */
39     int8_t      name[8];        /*< Name. */
40 } ArgoASFFileHeader;
41
42 typedef struct ArgoASFChunkHeader {
43     uint32_t    num_blocks;     /*< No. blocks in the chunk. */
44     uint32_t    num_samples;    /*< No. samples per channel in a block. Always 32. */
45     uint32_t    unk1;           /*< Unknown */
46     uint16_t    sample_rate;    /*< Sample rate. */
47     uint16_t    unk2;           /*< Unknown. */
48     uint32_t    flags;          /*< Stream flags. */
49 } ArgoASFChunkHeader;
50
51 enum {
52     ASF_CF_BITS_PER_SAMPLE  = (1 << 0), /*< 16-bit if set, 8 otherwise.      */
53     ASF_CF_STEREO           = (1 << 1), /*< Stereo if set, mono otherwise.   */
54     ASF_CF_ALWAYS1_1        = (1 << 2), /*< Unknown, always seems to be set. */
55     ASF_CF_ALWAYS1_2        = (1 << 3), /*< Unknown, always seems to be set. */
56
57     ASF_CF_ALWAYS1          = ASF_CF_ALWAYS1_1 | ASF_CF_ALWAYS1_2,
58     ASF_CF_ALWAYS0          = ~(ASF_CF_BITS_PER_SAMPLE | ASF_CF_STEREO | ASF_CF_ALWAYS1)
59 };
60
61 typedef struct ArgoASFDemuxContext {
62     ArgoASFFileHeader   fhdr;
63     ArgoASFChunkHeader  ckhdr;
64     uint32_t            blocks_read;
65 } ArgoASFDemuxContext;
66
67 typedef struct ArgoASFMuxContext {
68     const AVClass *class;
69     int            version_major;
70     int            version_minor;
71     const char    *name;
72 } ArgoASFMuxContext;
73
74 #if CONFIG_ARGO_ASF_DEMUXER
75 static void argo_asf_parse_file_header(ArgoASFFileHeader *hdr, const uint8_t *buf)
76 {
77     hdr->magic          = AV_RL32(buf + 0);
78     hdr->version_major  = AV_RL16(buf + 4);
79     hdr->version_minor  = AV_RL16(buf + 6);
80     hdr->num_chunks     = AV_RL32(buf + 8);
81     hdr->chunk_offset   = AV_RL32(buf + 12);
82     for (int i = 0; i < FF_ARRAY_ELEMS(hdr->name); i++)
83         hdr->name[i]    = AV_RL8(buf + 16 + i);
84 }
85
86 static void argo_asf_parse_chunk_header(ArgoASFChunkHeader *hdr, const uint8_t *buf)
87 {
88     hdr->num_blocks     = AV_RL32(buf + 0);
89     hdr->num_samples    = AV_RL32(buf + 4);
90     hdr->unk1           = AV_RL32(buf + 8);
91     hdr->sample_rate    = AV_RL16(buf + 12);
92     hdr->unk2           = AV_RL16(buf + 14);
93     hdr->flags          = AV_RL32(buf + 16);
94 }
95
96 /*
97  * Known versions:
98  * 1.1: https://samples.ffmpeg.org/game-formats/brender/part2.zip
99  *      FX Fighter
100  * 1.2: Croc! Legend of the Gobbos
101  * 2.1: Croc 2
102  *      The Emperor's New Groove
103  *      Disney's Aladdin in Nasira's Revenge
104  */
105 static int argo_asf_is_known_version(const ArgoASFFileHeader *hdr)
106 {
107     return (hdr->version_major == 1 && hdr->version_minor == 1) ||
108            (hdr->version_major == 1 && hdr->version_minor == 2) ||
109            (hdr->version_major == 2 && hdr->version_minor == 1);
110 }
111
112 static int argo_asf_probe(const AVProbeData *p)
113 {
114     ArgoASFFileHeader hdr;
115
116     av_assert0(AVPROBE_PADDING_SIZE >= ASF_FILE_HEADER_SIZE);
117
118     argo_asf_parse_file_header(&hdr, p->buf);
119
120     if (hdr.magic != ASF_TAG)
121         return 0;
122
123     if (!argo_asf_is_known_version(&hdr))
124         return AVPROBE_SCORE_EXTENSION / 2;
125
126     return AVPROBE_SCORE_EXTENSION + 1;
127 }
128
129 static int argo_asf_read_header(AVFormatContext *s)
130 {
131     int64_t ret;
132     AVIOContext *pb = s->pb;
133     AVStream *st;
134     ArgoASFDemuxContext *asf = s->priv_data;
135     uint8_t buf[FFMAX(ASF_FILE_HEADER_SIZE, ASF_CHUNK_HEADER_SIZE)];
136
137     if (!(st = avformat_new_stream(s, NULL)))
138         return AVERROR(ENOMEM);
139
140     if ((ret = avio_read(pb, buf, ASF_FILE_HEADER_SIZE)) < 0)
141         return ret;
142     else if (ret != ASF_FILE_HEADER_SIZE)
143         return AVERROR(EIO);
144
145     argo_asf_parse_file_header(&asf->fhdr, buf);
146
147     if (asf->fhdr.magic != ASF_TAG)
148         return AVERROR_INVALIDDATA;
149
150     if (asf->fhdr.num_chunks == 0) {
151         return AVERROR_INVALIDDATA;
152     } else if (asf->fhdr.num_chunks > 1) {
153         avpriv_request_sample(s, ">1 chunk");
154         return AVERROR_PATCHWELCOME;
155     }
156
157     if (asf->fhdr.chunk_offset < ASF_FILE_HEADER_SIZE)
158         return AVERROR_INVALIDDATA;
159
160     if ((ret = avio_skip(pb, asf->fhdr.chunk_offset - ASF_FILE_HEADER_SIZE)) < 0)
161         return ret;
162
163     if ((ret = avio_read(pb, buf, ASF_CHUNK_HEADER_SIZE)) < 0)
164         return ret;
165     else if (ret != ASF_CHUNK_HEADER_SIZE)
166         return AVERROR(EIO);
167
168     argo_asf_parse_chunk_header(&asf->ckhdr, buf);
169
170     if (asf->ckhdr.num_samples != ASF_SAMPLE_COUNT) {
171         av_log(s, AV_LOG_ERROR, "Invalid sample count. Got %u, expected %d\n",
172                asf->ckhdr.num_samples, ASF_SAMPLE_COUNT);
173         return AVERROR_INVALIDDATA;
174     }
175
176     if ((asf->ckhdr.flags & ASF_CF_ALWAYS1) != ASF_CF_ALWAYS1 || (asf->ckhdr.flags & ASF_CF_ALWAYS0) != 0) {
177         avpriv_request_sample(s, "Nonstandard flags (0x%08X)", asf->ckhdr.flags);
178         return AVERROR_PATCHWELCOME;
179     }
180
181     st->codecpar->codec_type                = AVMEDIA_TYPE_AUDIO;
182     st->codecpar->codec_id                  = AV_CODEC_ID_ADPCM_ARGO;
183     st->codecpar->format                    = AV_SAMPLE_FMT_S16P;
184
185     if (asf->ckhdr.flags & ASF_CF_STEREO) {
186         st->codecpar->channel_layout        = AV_CH_LAYOUT_STEREO;
187         st->codecpar->channels              = 2;
188     } else {
189         st->codecpar->channel_layout        = AV_CH_LAYOUT_MONO;
190         st->codecpar->channels              = 1;
191     }
192
193     /* v1.1 files (FX Fighter) are all marked as 44100, but are actually 22050. */
194     if (asf->fhdr.version_major == 1 && asf->fhdr.version_minor == 1)
195         st->codecpar->sample_rate           = 22050;
196     else
197         st->codecpar->sample_rate           = asf->ckhdr.sample_rate;
198
199     st->codecpar->bits_per_coded_sample     = 4;
200
201     if (asf->ckhdr.flags & ASF_CF_BITS_PER_SAMPLE)
202         st->codecpar->bits_per_raw_sample   = 16;
203     else
204         st->codecpar->bits_per_raw_sample   = 8;
205
206     if (st->codecpar->bits_per_raw_sample != 16) {
207         /* The header allows for these, but I've never seen any files with them. */
208         avpriv_request_sample(s, "Non 16-bit samples");
209         return AVERROR_PATCHWELCOME;
210     }
211
212     /*
213      * (nchannel control bytes) + ((bytes_per_channel) * nchannel)
214      * For mono, this is 17. For stereo, this is 34.
215      */
216     st->codecpar->frame_size            = st->codecpar->channels +
217                                           (asf->ckhdr.num_samples / 2) *
218                                           st->codecpar->channels;
219
220     st->codecpar->block_align           = st->codecpar->frame_size;
221
222     st->codecpar->bit_rate              = st->codecpar->channels *
223                                           st->codecpar->sample_rate *
224                                           st->codecpar->bits_per_coded_sample;
225
226     avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
227     st->start_time      = 0;
228     st->duration        = asf->ckhdr.num_blocks * asf->ckhdr.num_samples;
229     st->nb_frames       = asf->ckhdr.num_blocks;
230     return 0;
231 }
232
233 static int argo_asf_read_packet(AVFormatContext *s, AVPacket *pkt)
234 {
235     ArgoASFDemuxContext *asf = s->priv_data;
236
237     AVStream *st = s->streams[0];
238     AVIOContext *pb = s->pb;
239     int ret;
240
241     if (asf->blocks_read >= asf->ckhdr.num_blocks)
242         return AVERROR_EOF;
243
244     if ((ret = av_get_packet(pb, pkt, st->codecpar->frame_size)) < 0)
245         return ret;
246     else if (ret != st->codecpar->frame_size)
247         return AVERROR_INVALIDDATA;
248
249     pkt->stream_index   = st->index;
250     pkt->duration       = asf->ckhdr.num_samples;
251
252     ++asf->blocks_read;
253     return 0;
254 }
255
256 /*
257  * Not actually sure what ASF stands for.
258  * - Argonaut Sound File?
259  * - Audio Stream File?
260  */
261 AVInputFormat ff_argo_asf_demuxer = {
262     .name           = "argo_asf",
263     .long_name      = NULL_IF_CONFIG_SMALL("Argonaut Games ASF"),
264     .priv_data_size = sizeof(ArgoASFDemuxContext),
265     .read_probe     = argo_asf_probe,
266     .read_header    = argo_asf_read_header,
267     .read_packet    = argo_asf_read_packet
268 };
269 #endif
270
271 #if CONFIG_ARGO_ASF_MUXER
272 static int argo_asf_write_init(AVFormatContext *s)
273 {
274     ArgoASFMuxContext *ctx = s->priv_data;
275     const AVCodecParameters *par;
276
277     if (s->nb_streams != 1) {
278         av_log(s, AV_LOG_ERROR, "ASF files have exactly one stream\n");
279         return AVERROR(EINVAL);
280     }
281
282     par = s->streams[0]->codecpar;
283
284     if (par->codec_id != AV_CODEC_ID_ADPCM_ARGO) {
285         av_log(s, AV_LOG_ERROR, "%s codec not supported\n",
286                avcodec_get_name(par->codec_id));
287         return AVERROR(EINVAL);
288     }
289
290     if (ctx->version_major == 1 && ctx->version_minor == 1 && par->sample_rate != 22050) {
291         av_log(s, AV_LOG_ERROR, "ASF v1.1 files only support a sample rate of 22050\n");
292         return AVERROR(EINVAL);
293     }
294
295     if (par->channels > 2) {
296         av_log(s, AV_LOG_ERROR, "ASF files only support up to 2 channels\n");
297         return AVERROR(EINVAL);
298     }
299
300     if (par->sample_rate > UINT16_MAX) {
301         av_log(s, AV_LOG_ERROR, "Sample rate too large\n");
302         return AVERROR(EINVAL);
303     }
304
305     if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
306         av_log(s, AV_LOG_ERROR, "Stream not seekable, unable to write output file\n");
307         return AVERROR(EINVAL);
308     }
309
310     return 0;
311 }
312
313 static void argo_asf_write_file_header(const ArgoASFFileHeader *fhdr, AVIOContext *pb)
314 {
315     avio_wl32( pb, fhdr->magic);
316     avio_wl16( pb, fhdr->version_major);
317     avio_wl16( pb, fhdr->version_minor);
318     avio_wl32( pb, fhdr->num_chunks);
319     avio_wl32( pb, fhdr->chunk_offset);
320     avio_write(pb, fhdr->name, sizeof(fhdr->name));
321 }
322
323 static void argo_asf_write_chunk_header(const ArgoASFChunkHeader *ckhdr, AVIOContext *pb)
324 {
325     avio_wl32(pb, ckhdr->num_blocks);
326     avio_wl32(pb, ckhdr->num_samples);
327     avio_wl32(pb, ckhdr->unk1);
328     avio_wl16(pb, ckhdr->sample_rate);
329     avio_wl16(pb, ckhdr->unk2);
330     avio_wl32(pb, ckhdr->flags);
331 }
332
333 static int argo_asf_write_header(AVFormatContext *s)
334 {
335     const AVCodecParameters  *par = s->streams[0]->codecpar;
336     ArgoASFMuxContext        *ctx = s->priv_data;
337     ArgoASFFileHeader  fhdr;
338     ArgoASFChunkHeader chdr;
339
340     fhdr.magic         = ASF_TAG;
341     fhdr.version_major = (uint16_t)ctx->version_major;
342     fhdr.version_minor = (uint16_t)ctx->version_minor;
343     fhdr.num_chunks    = 1;
344     fhdr.chunk_offset  = ASF_FILE_HEADER_SIZE;
345     /*
346      * If the user specified a name, use it as is. Otherwise take the
347      * basename and lop off the extension (if any).
348      */
349     if (ctx->name) {
350         strncpy(fhdr.name, ctx->name, sizeof(fhdr.name));
351     } else {
352         const char *start = av_basename(s->url);
353         const char *end   = strrchr(start, '.');
354         size_t      len;
355
356         if(end)
357             len = end - start;
358         else
359             len = strlen(start);
360
361         memcpy(fhdr.name, start, FFMIN(len, sizeof(fhdr.name)));
362     }
363
364     chdr.num_blocks    = 0;
365     chdr.num_samples   = ASF_SAMPLE_COUNT;
366     chdr.unk1          = 0;
367
368     if (ctx->version_major == 1 && ctx->version_minor == 1)
369         chdr.sample_rate = 44100;
370     else
371         chdr.sample_rate = par->sample_rate;
372
373     chdr.unk2          = ~0;
374     chdr.flags         = ASF_CF_BITS_PER_SAMPLE | ASF_CF_ALWAYS1;
375
376     if (par->channels == 2)
377         chdr.flags |= ASF_CF_STEREO;
378
379     argo_asf_write_file_header(&fhdr, s->pb);
380     argo_asf_write_chunk_header(&chdr, s->pb);
381     return 0;
382 }
383
384 static int argo_asf_write_packet(AVFormatContext *s, AVPacket *pkt)
385 {
386     if (pkt->size != 17 * s->streams[0]->codecpar->channels)
387         return AVERROR_INVALIDDATA;
388
389     if (s->streams[0]->nb_frames >= UINT32_MAX)
390         return AVERROR_INVALIDDATA;
391
392     avio_write(s->pb, pkt->data, pkt->size);
393     return 0;
394 }
395
396 static int argo_asf_write_trailer(AVFormatContext *s)
397 {
398     int64_t ret;
399
400     if ((ret = avio_seek(s->pb, ASF_FILE_HEADER_SIZE, SEEK_SET) < 0))
401         return ret;
402
403     avio_wl32(s->pb, (uint32_t)s->streams[0]->nb_frames);
404     return 0;
405 }
406
407 static const AVOption argo_asf_options[] = {
408     {
409         .name        = "version_major",
410         .help        = "override file major version",
411         .offset      = offsetof(ArgoASFMuxContext, version_major),
412         .type        = AV_OPT_TYPE_INT,
413         .default_val = {.i64 = 2},
414         .min         = 0,
415         .max         = UINT16_MAX,
416         .flags       = AV_OPT_FLAG_ENCODING_PARAM
417     },
418     {
419         .name        = "version_minor",
420         .help        = "override file minor version",
421         .offset      = offsetof(ArgoASFMuxContext, version_minor),
422         .type        = AV_OPT_TYPE_INT,
423         .default_val = {.i64 = 1},
424         .min         = 0,
425         .max         = UINT16_MAX,
426         .flags       = AV_OPT_FLAG_ENCODING_PARAM
427     },
428     {
429         .name        = "name",
430         .help        = "embedded file name (max 8 characters)",
431         .offset      = offsetof(ArgoASFMuxContext, name),
432         .type        = AV_OPT_TYPE_STRING,
433         .default_val = {.str = NULL},
434         .flags       = AV_OPT_FLAG_ENCODING_PARAM
435     },
436     { NULL }
437 };
438
439 static const AVClass argo_asf_muxer_class = {
440     .class_name = "argo_asf_muxer",
441     .item_name  = av_default_item_name,
442     .option     = argo_asf_options,
443     .version    = LIBAVUTIL_VERSION_INT
444 };
445
446 AVOutputFormat ff_argo_asf_muxer = {
447     .name           = "argo_asf",
448     .long_name      = NULL_IF_CONFIG_SMALL("Argonaut Games ASF"),
449     /*
450      * NB: Can't do this as it conflicts with the actual ASF format.
451      * .extensions  = "asf",
452      */
453     .audio_codec    = AV_CODEC_ID_ADPCM_ARGO,
454     .video_codec    = AV_CODEC_ID_NONE,
455     .init           = argo_asf_write_init,
456     .write_header   = argo_asf_write_header,
457     .write_packet   = argo_asf_write_packet,
458     .write_trailer  = argo_asf_write_trailer,
459     .priv_class     = &argo_asf_muxer_class,
460     .priv_data_size = sizeof(ArgoASFMuxContext)
461 };
462 #endif