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