]> git.sesse.net Git - ffmpeg/blob - libavformat/argo_asf.c
avformat/argo_asf: add name option
[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     st->codecpar->sample_rate               = asf->ckhdr.sample_rate;
191
192     st->codecpar->bits_per_coded_sample     = 4;
193
194     if (asf->ckhdr.flags & ASF_CF_BITS_PER_SAMPLE)
195         st->codecpar->bits_per_raw_sample   = 16;
196     else
197         st->codecpar->bits_per_raw_sample   = 8;
198
199     if (st->codecpar->bits_per_raw_sample != 16) {
200         /* The header allows for these, but I've never seen any files with them. */
201         avpriv_request_sample(s, "Non 16-bit samples");
202         return AVERROR_PATCHWELCOME;
203     }
204
205     /*
206      * (nchannel control bytes) + ((bytes_per_channel) * nchannel)
207      * For mono, this is 17. For stereo, this is 34.
208      */
209     st->codecpar->frame_size            = st->codecpar->channels +
210                                           (asf->ckhdr.num_samples / 2) *
211                                           st->codecpar->channels;
212
213     st->codecpar->block_align           = st->codecpar->frame_size;
214
215     st->codecpar->bit_rate              = st->codecpar->channels *
216                                           st->codecpar->sample_rate *
217                                           st->codecpar->bits_per_coded_sample;
218
219     avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
220     st->start_time      = 0;
221     st->duration        = asf->ckhdr.num_blocks * asf->ckhdr.num_samples;
222     st->nb_frames       = asf->ckhdr.num_blocks;
223     return 0;
224 }
225
226 static int argo_asf_read_packet(AVFormatContext *s, AVPacket *pkt)
227 {
228     ArgoASFDemuxContext *asf = s->priv_data;
229
230     AVStream *st = s->streams[0];
231     AVIOContext *pb = s->pb;
232     int ret;
233
234     if (asf->blocks_read >= asf->ckhdr.num_blocks)
235         return AVERROR_EOF;
236
237     if ((ret = av_get_packet(pb, pkt, st->codecpar->frame_size)) < 0)
238         return ret;
239     else if (ret != st->codecpar->frame_size)
240         return AVERROR_INVALIDDATA;
241
242     pkt->stream_index   = st->index;
243     pkt->duration       = asf->ckhdr.num_samples;
244
245     ++asf->blocks_read;
246     return 0;
247 }
248
249 /*
250  * Not actually sure what ASF stands for.
251  * - Argonaut Sound File?
252  * - Audio Stream File?
253  */
254 AVInputFormat ff_argo_asf_demuxer = {
255     .name           = "argo_asf",
256     .long_name      = NULL_IF_CONFIG_SMALL("Argonaut Games ASF"),
257     .priv_data_size = sizeof(ArgoASFDemuxContext),
258     .read_probe     = argo_asf_probe,
259     .read_header    = argo_asf_read_header,
260     .read_packet    = argo_asf_read_packet
261 };
262 #endif
263
264 #if CONFIG_ARGO_ASF_MUXER
265 static int argo_asf_write_init(AVFormatContext *s)
266 {
267     const AVCodecParameters *par;
268
269     if (s->nb_streams != 1) {
270         av_log(s, AV_LOG_ERROR, "ASF files have exactly one stream\n");
271         return AVERROR(EINVAL);
272     }
273
274     par = s->streams[0]->codecpar;
275
276     if (par->codec_id != AV_CODEC_ID_ADPCM_ARGO) {
277         av_log(s, AV_LOG_ERROR, "%s codec not supported\n",
278                avcodec_get_name(par->codec_id));
279         return AVERROR(EINVAL);
280     }
281
282     if (par->channels > 2) {
283         av_log(s, AV_LOG_ERROR, "ASF files only support up to 2 channels\n");
284         return AVERROR(EINVAL);
285     }
286
287     if (par->sample_rate > UINT16_MAX) {
288         av_log(s, AV_LOG_ERROR, "Sample rate too large\n");
289         return AVERROR(EINVAL);
290     }
291
292     if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
293         av_log(s, AV_LOG_ERROR, "Stream not seekable, unable to write output file\n");
294         return AVERROR(EINVAL);
295     }
296
297     return 0;
298 }
299
300 static void argo_asf_write_file_header(const ArgoASFFileHeader *fhdr, AVIOContext *pb)
301 {
302     avio_wl32( pb, fhdr->magic);
303     avio_wl16( pb, fhdr->version_major);
304     avio_wl16( pb, fhdr->version_minor);
305     avio_wl32( pb, fhdr->num_chunks);
306     avio_wl32( pb, fhdr->chunk_offset);
307     avio_write(pb, fhdr->name, sizeof(fhdr->name));
308 }
309
310 static void argo_asf_write_chunk_header(const ArgoASFChunkHeader *ckhdr, AVIOContext *pb)
311 {
312     avio_wl32(pb, ckhdr->num_blocks);
313     avio_wl32(pb, ckhdr->num_samples);
314     avio_wl32(pb, ckhdr->unk1);
315     avio_wl16(pb, ckhdr->sample_rate);
316     avio_wl16(pb, ckhdr->unk2);
317     avio_wl32(pb, ckhdr->flags);
318 }
319
320 static int argo_asf_write_header(AVFormatContext *s)
321 {
322     const AVCodecParameters  *par = s->streams[0]->codecpar;
323     ArgoASFMuxContext        *ctx = s->priv_data;
324     ArgoASFFileHeader  fhdr;
325     ArgoASFChunkHeader chdr;
326
327     fhdr.magic         = ASF_TAG;
328     fhdr.version_major = (uint16_t)ctx->version_major;
329     fhdr.version_minor = (uint16_t)ctx->version_minor;
330     fhdr.num_chunks    = 1;
331     fhdr.chunk_offset  = ASF_FILE_HEADER_SIZE;
332     if (ctx->name)
333         strncpy(fhdr.name, ctx->name, sizeof(fhdr.name));
334     else
335         strncpy(fhdr.name, av_basename(s->url), sizeof(fhdr.name));
336
337     chdr.num_blocks    = 0;
338     chdr.num_samples   = ASF_SAMPLE_COUNT;
339     chdr.unk1          = 0;
340     chdr.sample_rate   = par->sample_rate;
341     chdr.unk2          = ~0;
342     chdr.flags         = ASF_CF_BITS_PER_SAMPLE | ASF_CF_ALWAYS1;
343
344     if (par->channels == 2)
345         chdr.flags |= ASF_CF_STEREO;
346
347     argo_asf_write_file_header(&fhdr, s->pb);
348     argo_asf_write_chunk_header(&chdr, s->pb);
349     return 0;
350 }
351
352 static int argo_asf_write_packet(AVFormatContext *s, AVPacket *pkt)
353 {
354     if (pkt->size != 17 * s->streams[0]->codecpar->channels)
355         return AVERROR_INVALIDDATA;
356
357     if (s->streams[0]->nb_frames >= UINT32_MAX)
358         return AVERROR_INVALIDDATA;
359
360     avio_write(s->pb, pkt->data, pkt->size);
361     return 0;
362 }
363
364 static int argo_asf_write_trailer(AVFormatContext *s)
365 {
366     int64_t ret;
367
368     if ((ret = avio_seek(s->pb, ASF_FILE_HEADER_SIZE, SEEK_SET) < 0))
369         return ret;
370
371     avio_wl32(s->pb, (uint32_t)s->streams[0]->nb_frames);
372     return 0;
373 }
374
375 static const AVOption argo_asf_options[] = {
376     {
377         .name        = "version_major",
378         .help        = "override file major version",
379         .offset      = offsetof(ArgoASFMuxContext, version_major),
380         .type        = AV_OPT_TYPE_INT,
381         .default_val = {.i64 = 2},
382         .min         = 0,
383         .max         = UINT16_MAX,
384         .flags       = AV_OPT_FLAG_ENCODING_PARAM
385     },
386     {
387         .name        = "version_minor",
388         .help        = "override file minor version",
389         .offset      = offsetof(ArgoASFMuxContext, version_minor),
390         .type        = AV_OPT_TYPE_INT,
391         .default_val = {.i64 = 1},
392         .min         = 0,
393         .max         = UINT16_MAX,
394         .flags       = AV_OPT_FLAG_ENCODING_PARAM
395     },
396     {
397         .name        = "name",
398         .help        = "embedded file name (max 8 characters)",
399         .offset      = offsetof(ArgoASFMuxContext, name),
400         .type        = AV_OPT_TYPE_STRING,
401         .default_val = {.str = NULL},
402         .flags       = AV_OPT_FLAG_ENCODING_PARAM
403     },
404     { NULL }
405 };
406
407 static const AVClass argo_asf_muxer_class = {
408     .class_name = "argo_asf_muxer",
409     .item_name  = av_default_item_name,
410     .option     = argo_asf_options,
411     .version    = LIBAVUTIL_VERSION_INT
412 };
413
414 AVOutputFormat ff_argo_asf_muxer = {
415     .name           = "argo_asf",
416     .long_name      = NULL_IF_CONFIG_SMALL("Argonaut Games ASF"),
417     /*
418      * NB: Can't do this as it conflicts with the actual ASF format.
419      * .extensions  = "asf",
420      */
421     .audio_codec    = AV_CODEC_ID_ADPCM_ARGO,
422     .video_codec    = AV_CODEC_ID_NONE,
423     .init           = argo_asf_write_init,
424     .write_header   = argo_asf_write_header,
425     .write_packet   = argo_asf_write_packet,
426     .write_trailer  = argo_asf_write_trailer,
427     .priv_class     = &argo_asf_muxer_class,
428     .priv_data_size = sizeof(ArgoASFMuxContext)
429 };
430 #endif