]> git.sesse.net Git - ffmpeg/blob - libavformat/argo_asf.c
avformat/argo_asf: fix handling of v1.1 files
[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.num_chunks == 0) {
148         return AVERROR_INVALIDDATA;
149     } else if (asf->fhdr.num_chunks > 1) {
150         avpriv_request_sample(s, ">1 chunk");
151         return AVERROR_PATCHWELCOME;
152     }
153
154     if (asf->fhdr.chunk_offset < ASF_FILE_HEADER_SIZE)
155         return AVERROR_INVALIDDATA;
156
157     if ((ret = avio_skip(pb, asf->fhdr.chunk_offset - ASF_FILE_HEADER_SIZE)) < 0)
158         return ret;
159
160     if ((ret = avio_read(pb, buf, ASF_CHUNK_HEADER_SIZE)) < 0)
161         return ret;
162     else if (ret != ASF_CHUNK_HEADER_SIZE)
163         return AVERROR(EIO);
164
165     argo_asf_parse_chunk_header(&asf->ckhdr, buf);
166
167     if (asf->ckhdr.num_samples != ASF_SAMPLE_COUNT) {
168         av_log(s, AV_LOG_ERROR, "Invalid sample count. Got %u, expected %d\n",
169                asf->ckhdr.num_samples, ASF_SAMPLE_COUNT);
170         return AVERROR_INVALIDDATA;
171     }
172
173     if ((asf->ckhdr.flags & ASF_CF_ALWAYS1) != ASF_CF_ALWAYS1 || (asf->ckhdr.flags & ASF_CF_ALWAYS0) != 0) {
174         avpriv_request_sample(s, "Nonstandard flags (0x%08X)", asf->ckhdr.flags);
175         return AVERROR_PATCHWELCOME;
176     }
177
178     st->codecpar->codec_type                = AVMEDIA_TYPE_AUDIO;
179     st->codecpar->codec_id                  = AV_CODEC_ID_ADPCM_ARGO;
180     st->codecpar->format                    = AV_SAMPLE_FMT_S16P;
181
182     if (asf->ckhdr.flags & ASF_CF_STEREO) {
183         st->codecpar->channel_layout        = AV_CH_LAYOUT_STEREO;
184         st->codecpar->channels              = 2;
185     } else {
186         st->codecpar->channel_layout        = AV_CH_LAYOUT_MONO;
187         st->codecpar->channels              = 1;
188     }
189
190     /* v1.1 files (FX Fighter) are all marked as 44100, but are actually 22050. */
191     if (asf->fhdr.version_major == 1 && asf->fhdr.version_minor == 1)
192         st->codecpar->sample_rate           = 22050;
193     else
194         st->codecpar->sample_rate           = asf->ckhdr.sample_rate;
195
196     st->codecpar->bits_per_coded_sample     = 4;
197
198     if (asf->ckhdr.flags & ASF_CF_BITS_PER_SAMPLE)
199         st->codecpar->bits_per_raw_sample   = 16;
200     else
201         st->codecpar->bits_per_raw_sample   = 8;
202
203     if (st->codecpar->bits_per_raw_sample != 16) {
204         /* The header allows for these, but I've never seen any files with them. */
205         avpriv_request_sample(s, "Non 16-bit samples");
206         return AVERROR_PATCHWELCOME;
207     }
208
209     /*
210      * (nchannel control bytes) + ((bytes_per_channel) * nchannel)
211      * For mono, this is 17. For stereo, this is 34.
212      */
213     st->codecpar->frame_size            = st->codecpar->channels +
214                                           (asf->ckhdr.num_samples / 2) *
215                                           st->codecpar->channels;
216
217     st->codecpar->block_align           = st->codecpar->frame_size;
218
219     st->codecpar->bit_rate              = st->codecpar->channels *
220                                           st->codecpar->sample_rate *
221                                           st->codecpar->bits_per_coded_sample;
222
223     avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
224     st->start_time      = 0;
225     st->duration        = asf->ckhdr.num_blocks * asf->ckhdr.num_samples;
226     st->nb_frames       = asf->ckhdr.num_blocks;
227     return 0;
228 }
229
230 static int argo_asf_read_packet(AVFormatContext *s, AVPacket *pkt)
231 {
232     ArgoASFDemuxContext *asf = s->priv_data;
233
234     AVStream *st = s->streams[0];
235     AVIOContext *pb = s->pb;
236     int ret;
237
238     if (asf->blocks_read >= asf->ckhdr.num_blocks)
239         return AVERROR_EOF;
240
241     if ((ret = av_get_packet(pb, pkt, st->codecpar->frame_size)) < 0)
242         return ret;
243     else if (ret != st->codecpar->frame_size)
244         return AVERROR_INVALIDDATA;
245
246     pkt->stream_index   = st->index;
247     pkt->duration       = asf->ckhdr.num_samples;
248
249     ++asf->blocks_read;
250     return 0;
251 }
252
253 /*
254  * Not actually sure what ASF stands for.
255  * - Argonaut Sound File?
256  * - Audio Stream File?
257  */
258 AVInputFormat ff_argo_asf_demuxer = {
259     .name           = "argo_asf",
260     .long_name      = NULL_IF_CONFIG_SMALL("Argonaut Games ASF"),
261     .priv_data_size = sizeof(ArgoASFDemuxContext),
262     .read_probe     = argo_asf_probe,
263     .read_header    = argo_asf_read_header,
264     .read_packet    = argo_asf_read_packet
265 };
266 #endif
267
268 #if CONFIG_ARGO_ASF_MUXER
269 static int argo_asf_write_init(AVFormatContext *s)
270 {
271     ArgoASFMuxContext *ctx = s->priv_data;
272     const AVCodecParameters *par;
273
274     if (s->nb_streams != 1) {
275         av_log(s, AV_LOG_ERROR, "ASF files have exactly one stream\n");
276         return AVERROR(EINVAL);
277     }
278
279     par = s->streams[0]->codecpar;
280
281     if (par->codec_id != AV_CODEC_ID_ADPCM_ARGO) {
282         av_log(s, AV_LOG_ERROR, "%s codec not supported\n",
283                avcodec_get_name(par->codec_id));
284         return AVERROR(EINVAL);
285     }
286
287     if (ctx->version_major == 1 && ctx->version_minor == 1 && par->sample_rate != 22050) {
288         av_log(s, AV_LOG_ERROR, "ASF v1.1 files only support a sample rate of 22050\n");
289         return AVERROR(EINVAL);
290     }
291
292     if (par->channels > 2) {
293         av_log(s, AV_LOG_ERROR, "ASF files only support up to 2 channels\n");
294         return AVERROR(EINVAL);
295     }
296
297     if (par->sample_rate > UINT16_MAX) {
298         av_log(s, AV_LOG_ERROR, "Sample rate too large\n");
299         return AVERROR(EINVAL);
300     }
301
302     if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
303         av_log(s, AV_LOG_ERROR, "Stream not seekable, unable to write output file\n");
304         return AVERROR(EINVAL);
305     }
306
307     return 0;
308 }
309
310 static void argo_asf_write_file_header(const ArgoASFFileHeader *fhdr, AVIOContext *pb)
311 {
312     avio_wl32( pb, fhdr->magic);
313     avio_wl16( pb, fhdr->version_major);
314     avio_wl16( pb, fhdr->version_minor);
315     avio_wl32( pb, fhdr->num_chunks);
316     avio_wl32( pb, fhdr->chunk_offset);
317     avio_write(pb, fhdr->name, sizeof(fhdr->name));
318 }
319
320 static void argo_asf_write_chunk_header(const ArgoASFChunkHeader *ckhdr, AVIOContext *pb)
321 {
322     avio_wl32(pb, ckhdr->num_blocks);
323     avio_wl32(pb, ckhdr->num_samples);
324     avio_wl32(pb, ckhdr->unk1);
325     avio_wl16(pb, ckhdr->sample_rate);
326     avio_wl16(pb, ckhdr->unk2);
327     avio_wl32(pb, ckhdr->flags);
328 }
329
330 static int argo_asf_write_header(AVFormatContext *s)
331 {
332     const AVCodecParameters  *par = s->streams[0]->codecpar;
333     ArgoASFMuxContext        *ctx = s->priv_data;
334     ArgoASFFileHeader  fhdr;
335     ArgoASFChunkHeader chdr;
336
337     fhdr.magic         = ASF_TAG;
338     fhdr.version_major = (uint16_t)ctx->version_major;
339     fhdr.version_minor = (uint16_t)ctx->version_minor;
340     fhdr.num_chunks    = 1;
341     fhdr.chunk_offset  = ASF_FILE_HEADER_SIZE;
342     /*
343      * If the user specified a name, use it as is. Otherwise take the
344      * basename and lop off the extension (if any).
345      */
346     if (ctx->name) {
347         strncpy(fhdr.name, ctx->name, sizeof(fhdr.name));
348     } else {
349         const char *start = av_basename(s->url);
350         const char *end   = strrchr(start, '.');
351         size_t      len;
352
353         if(end)
354             len = end - start;
355         else
356             len = strlen(start);
357
358         memcpy(fhdr.name, start, FFMIN(len, sizeof(fhdr.name)));
359     }
360
361     chdr.num_blocks    = 0;
362     chdr.num_samples   = ASF_SAMPLE_COUNT;
363     chdr.unk1          = 0;
364
365     if (ctx->version_major == 1 && ctx->version_minor == 1)
366         chdr.sample_rate = 44100;
367     else
368         chdr.sample_rate = par->sample_rate;
369
370     chdr.unk2          = ~0;
371     chdr.flags         = ASF_CF_BITS_PER_SAMPLE | ASF_CF_ALWAYS1;
372
373     if (par->channels == 2)
374         chdr.flags |= ASF_CF_STEREO;
375
376     argo_asf_write_file_header(&fhdr, s->pb);
377     argo_asf_write_chunk_header(&chdr, s->pb);
378     return 0;
379 }
380
381 static int argo_asf_write_packet(AVFormatContext *s, AVPacket *pkt)
382 {
383     if (pkt->size != 17 * s->streams[0]->codecpar->channels)
384         return AVERROR_INVALIDDATA;
385
386     if (s->streams[0]->nb_frames >= UINT32_MAX)
387         return AVERROR_INVALIDDATA;
388
389     avio_write(s->pb, pkt->data, pkt->size);
390     return 0;
391 }
392
393 static int argo_asf_write_trailer(AVFormatContext *s)
394 {
395     int64_t ret;
396
397     if ((ret = avio_seek(s->pb, ASF_FILE_HEADER_SIZE, SEEK_SET) < 0))
398         return ret;
399
400     avio_wl32(s->pb, (uint32_t)s->streams[0]->nb_frames);
401     return 0;
402 }
403
404 static const AVOption argo_asf_options[] = {
405     {
406         .name        = "version_major",
407         .help        = "override file major version",
408         .offset      = offsetof(ArgoASFMuxContext, version_major),
409         .type        = AV_OPT_TYPE_INT,
410         .default_val = {.i64 = 2},
411         .min         = 0,
412         .max         = UINT16_MAX,
413         .flags       = AV_OPT_FLAG_ENCODING_PARAM
414     },
415     {
416         .name        = "version_minor",
417         .help        = "override file minor version",
418         .offset      = offsetof(ArgoASFMuxContext, version_minor),
419         .type        = AV_OPT_TYPE_INT,
420         .default_val = {.i64 = 1},
421         .min         = 0,
422         .max         = UINT16_MAX,
423         .flags       = AV_OPT_FLAG_ENCODING_PARAM
424     },
425     {
426         .name        = "name",
427         .help        = "embedded file name (max 8 characters)",
428         .offset      = offsetof(ArgoASFMuxContext, name),
429         .type        = AV_OPT_TYPE_STRING,
430         .default_val = {.str = NULL},
431         .flags       = AV_OPT_FLAG_ENCODING_PARAM
432     },
433     { NULL }
434 };
435
436 static const AVClass argo_asf_muxer_class = {
437     .class_name = "argo_asf_muxer",
438     .item_name  = av_default_item_name,
439     .option     = argo_asf_options,
440     .version    = LIBAVUTIL_VERSION_INT
441 };
442
443 AVOutputFormat ff_argo_asf_muxer = {
444     .name           = "argo_asf",
445     .long_name      = NULL_IF_CONFIG_SMALL("Argonaut Games ASF"),
446     /*
447      * NB: Can't do this as it conflicts with the actual ASF format.
448      * .extensions  = "asf",
449      */
450     .audio_codec    = AV_CODEC_ID_ADPCM_ARGO,
451     .video_codec    = AV_CODEC_ID_NONE,
452     .init           = argo_asf_write_init,
453     .write_header   = argo_asf_write_header,
454     .write_packet   = argo_asf_write_packet,
455     .write_trailer  = argo_asf_write_trailer,
456     .priv_class     = &argo_asf_muxer_class,
457     .priv_data_size = sizeof(ArgoASFMuxContext)
458 };
459 #endif