]> git.sesse.net Git - ffmpeg/blob - libavformat/argo_asf.c
avformat/argo_asf: add version_major and version_minor options
[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 } ArgoASFMuxContext;
72
73 #if CONFIG_ARGO_ASF_DEMUXER
74 static void argo_asf_parse_file_header(ArgoASFFileHeader *hdr, const uint8_t *buf)
75 {
76     hdr->magic          = AV_RL32(buf + 0);
77     hdr->version_major  = AV_RL16(buf + 4);
78     hdr->version_minor  = AV_RL16(buf + 6);
79     hdr->num_chunks     = AV_RL32(buf + 8);
80     hdr->chunk_offset   = AV_RL32(buf + 12);
81     for (int i = 0; i < FF_ARRAY_ELEMS(hdr->name); i++)
82         hdr->name[i]    = AV_RL8(buf + 16 + i);
83 }
84
85 static void argo_asf_parse_chunk_header(ArgoASFChunkHeader *hdr, const uint8_t *buf)
86 {
87     hdr->num_blocks     = AV_RL32(buf + 0);
88     hdr->num_samples    = AV_RL32(buf + 4);
89     hdr->unk1           = AV_RL32(buf + 8);
90     hdr->sample_rate    = AV_RL16(buf + 12);
91     hdr->unk2           = AV_RL16(buf + 14);
92     hdr->flags          = AV_RL32(buf + 16);
93 }
94
95 /*
96  * Known versions:
97  * 1.1: https://samples.ffmpeg.org/game-formats/brender/part2.zip
98  *      FX Fighter
99  * 1.2: Croc! Legend of the Gobbos
100  * 2.1: Croc 2
101  *      The Emperor's New Groove
102  *      Disney's Aladdin in Nasira's Revenge
103  */
104 static int argo_asf_is_known_version(const ArgoASFFileHeader *hdr)
105 {
106     return (hdr->version_major == 1 && hdr->version_minor == 1) ||
107            (hdr->version_major == 1 && hdr->version_minor == 2) ||
108            (hdr->version_major == 2 && hdr->version_minor == 1);
109 }
110
111 static int argo_asf_probe(const AVProbeData *p)
112 {
113     ArgoASFFileHeader hdr;
114
115     av_assert0(AVPROBE_PADDING_SIZE >= ASF_FILE_HEADER_SIZE);
116
117     argo_asf_parse_file_header(&hdr, p->buf);
118
119     if (hdr.magic != ASF_TAG)
120         return 0;
121
122     if (!argo_asf_is_known_version(&hdr))
123         return AVPROBE_SCORE_EXTENSION / 2;
124
125     return AVPROBE_SCORE_EXTENSION + 1;
126 }
127
128 static int argo_asf_read_header(AVFormatContext *s)
129 {
130     int64_t ret;
131     AVIOContext *pb = s->pb;
132     AVStream *st;
133     ArgoASFDemuxContext *asf = s->priv_data;
134     uint8_t buf[FFMAX(ASF_FILE_HEADER_SIZE, ASF_CHUNK_HEADER_SIZE)];
135
136     if (!(st = avformat_new_stream(s, NULL)))
137         return AVERROR(ENOMEM);
138
139     if ((ret = avio_read(pb, buf, ASF_FILE_HEADER_SIZE)) < 0)
140         return ret;
141     else if (ret != ASF_FILE_HEADER_SIZE)
142         return AVERROR(EIO);
143
144     argo_asf_parse_file_header(&asf->fhdr, buf);
145
146     if (asf->fhdr.num_chunks == 0) {
147         return AVERROR_INVALIDDATA;
148     } else if (asf->fhdr.num_chunks > 1) {
149         avpriv_request_sample(s, ">1 chunk");
150         return AVERROR_PATCHWELCOME;
151     }
152
153     if (asf->fhdr.chunk_offset < ASF_FILE_HEADER_SIZE)
154         return AVERROR_INVALIDDATA;
155
156     if ((ret = avio_skip(pb, asf->fhdr.chunk_offset - ASF_FILE_HEADER_SIZE)) < 0)
157         return ret;
158
159     if ((ret = avio_read(pb, buf, ASF_CHUNK_HEADER_SIZE)) < 0)
160         return ret;
161     else if (ret != ASF_CHUNK_HEADER_SIZE)
162         return AVERROR(EIO);
163
164     argo_asf_parse_chunk_header(&asf->ckhdr, buf);
165
166     if (asf->ckhdr.num_samples != ASF_SAMPLE_COUNT) {
167         av_log(s, AV_LOG_ERROR, "Invalid sample count. Got %u, expected %d\n",
168                asf->ckhdr.num_samples, ASF_SAMPLE_COUNT);
169         return AVERROR_INVALIDDATA;
170     }
171
172     if ((asf->ckhdr.flags & ASF_CF_ALWAYS1) != ASF_CF_ALWAYS1 || (asf->ckhdr.flags & ASF_CF_ALWAYS0) != 0) {
173         avpriv_request_sample(s, "Nonstandard flags (0x%08X)", asf->ckhdr.flags);
174         return AVERROR_PATCHWELCOME;
175     }
176
177     st->codecpar->codec_type                = AVMEDIA_TYPE_AUDIO;
178     st->codecpar->codec_id                  = AV_CODEC_ID_ADPCM_ARGO;
179     st->codecpar->format                    = AV_SAMPLE_FMT_S16P;
180
181     if (asf->ckhdr.flags & ASF_CF_STEREO) {
182         st->codecpar->channel_layout        = AV_CH_LAYOUT_STEREO;
183         st->codecpar->channels              = 2;
184     } else {
185         st->codecpar->channel_layout        = AV_CH_LAYOUT_MONO;
186         st->codecpar->channels              = 1;
187     }
188
189     st->codecpar->sample_rate               = asf->ckhdr.sample_rate;
190
191     st->codecpar->bits_per_coded_sample     = 4;
192
193     if (asf->ckhdr.flags & ASF_CF_BITS_PER_SAMPLE)
194         st->codecpar->bits_per_raw_sample   = 16;
195     else
196         st->codecpar->bits_per_raw_sample   = 8;
197
198     if (st->codecpar->bits_per_raw_sample != 16) {
199         /* The header allows for these, but I've never seen any files with them. */
200         avpriv_request_sample(s, "Non 16-bit samples");
201         return AVERROR_PATCHWELCOME;
202     }
203
204     /*
205      * (nchannel control bytes) + ((bytes_per_channel) * nchannel)
206      * For mono, this is 17. For stereo, this is 34.
207      */
208     st->codecpar->frame_size            = st->codecpar->channels +
209                                           (asf->ckhdr.num_samples / 2) *
210                                           st->codecpar->channels;
211
212     st->codecpar->block_align           = st->codecpar->frame_size;
213
214     st->codecpar->bit_rate              = st->codecpar->channels *
215                                           st->codecpar->sample_rate *
216                                           st->codecpar->bits_per_coded_sample;
217
218     avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
219     st->start_time      = 0;
220     st->duration        = asf->ckhdr.num_blocks * asf->ckhdr.num_samples;
221     st->nb_frames       = asf->ckhdr.num_blocks;
222     return 0;
223 }
224
225 static int argo_asf_read_packet(AVFormatContext *s, AVPacket *pkt)
226 {
227     ArgoASFDemuxContext *asf = s->priv_data;
228
229     AVStream *st = s->streams[0];
230     AVIOContext *pb = s->pb;
231     int ret;
232
233     if (asf->blocks_read >= asf->ckhdr.num_blocks)
234         return AVERROR_EOF;
235
236     if ((ret = av_get_packet(pb, pkt, st->codecpar->frame_size)) < 0)
237         return ret;
238     else if (ret != st->codecpar->frame_size)
239         return AVERROR_INVALIDDATA;
240
241     pkt->stream_index   = st->index;
242     pkt->duration       = asf->ckhdr.num_samples;
243
244     ++asf->blocks_read;
245     return 0;
246 }
247
248 /*
249  * Not actually sure what ASF stands for.
250  * - Argonaut Sound File?
251  * - Audio Stream File?
252  */
253 AVInputFormat ff_argo_asf_demuxer = {
254     .name           = "argo_asf",
255     .long_name      = NULL_IF_CONFIG_SMALL("Argonaut Games ASF"),
256     .priv_data_size = sizeof(ArgoASFDemuxContext),
257     .read_probe     = argo_asf_probe,
258     .read_header    = argo_asf_read_header,
259     .read_packet    = argo_asf_read_packet
260 };
261 #endif
262
263 #if CONFIG_ARGO_ASF_MUXER
264 static int argo_asf_write_init(AVFormatContext *s)
265 {
266     const AVCodecParameters *par;
267
268     if (s->nb_streams != 1) {
269         av_log(s, AV_LOG_ERROR, "ASF files have exactly one stream\n");
270         return AVERROR(EINVAL);
271     }
272
273     par = s->streams[0]->codecpar;
274
275     if (par->codec_id != AV_CODEC_ID_ADPCM_ARGO) {
276         av_log(s, AV_LOG_ERROR, "%s codec not supported\n",
277                avcodec_get_name(par->codec_id));
278         return AVERROR(EINVAL);
279     }
280
281     if (par->channels > 2) {
282         av_log(s, AV_LOG_ERROR, "ASF files only support up to 2 channels\n");
283         return AVERROR(EINVAL);
284     }
285
286     if (par->sample_rate > UINT16_MAX) {
287         av_log(s, AV_LOG_ERROR, "Sample rate too large\n");
288         return AVERROR(EINVAL);
289     }
290
291     if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
292         av_log(s, AV_LOG_ERROR, "Stream not seekable, unable to write output file\n");
293         return AVERROR(EINVAL);
294     }
295
296     return 0;
297 }
298
299 static void argo_asf_write_file_header(const ArgoASFFileHeader *fhdr, AVIOContext *pb)
300 {
301     avio_wl32( pb, fhdr->magic);
302     avio_wl16( pb, fhdr->version_major);
303     avio_wl16( pb, fhdr->version_minor);
304     avio_wl32( pb, fhdr->num_chunks);
305     avio_wl32( pb, fhdr->chunk_offset);
306     avio_write(pb, fhdr->name, sizeof(fhdr->name));
307 }
308
309 static void argo_asf_write_chunk_header(const ArgoASFChunkHeader *ckhdr, AVIOContext *pb)
310 {
311     avio_wl32(pb, ckhdr->num_blocks);
312     avio_wl32(pb, ckhdr->num_samples);
313     avio_wl32(pb, ckhdr->unk1);
314     avio_wl16(pb, ckhdr->sample_rate);
315     avio_wl16(pb, ckhdr->unk2);
316     avio_wl32(pb, ckhdr->flags);
317 }
318
319 static int argo_asf_write_header(AVFormatContext *s)
320 {
321     const AVCodecParameters  *par = s->streams[0]->codecpar;
322     ArgoASFMuxContext        *ctx = s->priv_data;
323     ArgoASFFileHeader  fhdr;
324     ArgoASFChunkHeader chdr;
325
326     fhdr.magic         = ASF_TAG;
327     fhdr.version_major = (uint16_t)ctx->version_major;
328     fhdr.version_minor = (uint16_t)ctx->version_minor;
329     fhdr.num_chunks    = 1;
330     fhdr.chunk_offset  = ASF_FILE_HEADER_SIZE;
331     strncpy(fhdr.name, av_basename(s->url), FF_ARRAY_ELEMS(fhdr.name));
332
333     chdr.num_blocks    = 0;
334     chdr.num_samples   = ASF_SAMPLE_COUNT;
335     chdr.unk1          = 0;
336     chdr.sample_rate   = par->sample_rate;
337     chdr.unk2          = ~0;
338     chdr.flags         = ASF_CF_BITS_PER_SAMPLE | ASF_CF_ALWAYS1;
339
340     if (par->channels == 2)
341         chdr.flags |= ASF_CF_STEREO;
342
343     argo_asf_write_file_header(&fhdr, s->pb);
344     argo_asf_write_chunk_header(&chdr, s->pb);
345     return 0;
346 }
347
348 static int argo_asf_write_packet(AVFormatContext *s, AVPacket *pkt)
349 {
350     if (pkt->size != 17 * s->streams[0]->codecpar->channels)
351         return AVERROR_INVALIDDATA;
352
353     if (s->streams[0]->nb_frames >= UINT32_MAX)
354         return AVERROR_INVALIDDATA;
355
356     avio_write(s->pb, pkt->data, pkt->size);
357     return 0;
358 }
359
360 static int argo_asf_write_trailer(AVFormatContext *s)
361 {
362     int64_t ret;
363
364     if ((ret = avio_seek(s->pb, ASF_FILE_HEADER_SIZE, SEEK_SET) < 0))
365         return ret;
366
367     avio_wl32(s->pb, (uint32_t)s->streams[0]->nb_frames);
368     return 0;
369 }
370
371 static const AVOption argo_asf_options[] = {
372     {
373         .name        = "version_major",
374         .help        = "override file major version",
375         .offset      = offsetof(ArgoASFMuxContext, version_major),
376         .type        = AV_OPT_TYPE_INT,
377         .default_val = {.i64 = 2},
378         .min         = 0,
379         .max         = UINT16_MAX,
380         .flags       = AV_OPT_FLAG_ENCODING_PARAM
381     },
382     {
383         .name        = "version_minor",
384         .help        = "override file minor version",
385         .offset      = offsetof(ArgoASFMuxContext, version_minor),
386         .type        = AV_OPT_TYPE_INT,
387         .default_val = {.i64 = 1},
388         .min         = 0,
389         .max         = UINT16_MAX,
390         .flags       = AV_OPT_FLAG_ENCODING_PARAM
391     },
392     { NULL }
393 };
394
395 static const AVClass argo_asf_muxer_class = {
396     .class_name = "argo_asf_muxer",
397     .item_name  = av_default_item_name,
398     .option     = argo_asf_options,
399     .version    = LIBAVUTIL_VERSION_INT
400 };
401
402 AVOutputFormat ff_argo_asf_muxer = {
403     .name           = "argo_asf",
404     .long_name      = NULL_IF_CONFIG_SMALL("Argonaut Games ASF"),
405     /*
406      * NB: Can't do this as it conflicts with the actual ASF format.
407      * .extensions  = "asf",
408      */
409     .audio_codec    = AV_CODEC_ID_ADPCM_ARGO,
410     .video_codec    = AV_CODEC_ID_NONE,
411     .init           = argo_asf_write_init,
412     .write_header   = argo_asf_write_header,
413     .write_packet   = argo_asf_write_packet,
414     .write_trailer  = argo_asf_write_trailer,
415     .priv_class     = &argo_asf_muxer_class,
416     .priv_data_size = sizeof(ArgoASFMuxContext)
417 };
418 #endif