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