1 /*
2  * LEGO Racers ALP (.tun & .pcm) (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 
23 #include "config_components.h"
24 
25 #include "libavutil/channel_layout.h"
26 #include "avformat.h"
27 #include "internal.h"
28 #include "rawenc.h"
29 #include "libavutil/intreadwrite.h"
30 #include "libavutil/internal.h"
31 #include "libavutil/opt.h"
32 
33 #define ALP_TAG            MKTAG('A', 'L', 'P', ' ')
34 #define ALP_MAX_READ_SIZE  4096
35 
36 typedef struct ALPHeader {
37     uint32_t    magic;          /*< Magic Number, {'A', 'L', 'P', ' '} */
38     uint32_t    header_size;    /*< Header size (after this). */
39     char        adpcm[6];       /*< "ADPCM" */
40     uint8_t     unk1;           /*< Unknown */
41     uint8_t     num_channels;   /*< Channel Count. */
42     uint32_t    sample_rate;    /*< Sample rate, only if header_size >= 12. */
43 } ALPHeader;
44 
45 typedef enum ALPType {
46     ALP_TYPE_AUTO = 0, /*< Autodetect based on file extension. */
47     ALP_TYPE_TUN  = 1, /*< Force a .TUN file. */
48     ALP_TYPE_PCM  = 2, /*< Force a .PCM file. */
49 } ALPType;
50 
51 typedef struct ALPMuxContext {
52     const AVClass *class;
53     ALPType type;
54 } ALPMuxContext;
55 
56 #if CONFIG_ALP_DEMUXER
alp_probe(const AVProbeData *p)57 static int alp_probe(const AVProbeData *p)
58 {
59     uint32_t i;
60 
61     if (AV_RL32(p->buf) != ALP_TAG)
62         return 0;
63 
64     /* Only allowed header sizes are 8 and 12. */
65     i = AV_RL32(p->buf + 4);
66     if (i != 8 && i != 12)
67         return 0;
68 
69     if (strncmp("ADPCM", p->buf + 8, 6) != 0)
70         return 0;
71 
72     return AVPROBE_SCORE_MAX - 1;
73 }
74 
alp_read_header(AVFormatContext *s)75 static int alp_read_header(AVFormatContext *s)
76 {
77     int ret;
78     AVStream *st;
79     ALPHeader *hdr = s->priv_data;
80     AVCodecParameters *par;
81 
82     if ((hdr->magic = avio_rl32(s->pb)) != ALP_TAG)
83         return AVERROR_INVALIDDATA;
84 
85     hdr->header_size = avio_rl32(s->pb);
86 
87     if (hdr->header_size != 8 && hdr->header_size != 12) {
88         return AVERROR_INVALIDDATA;
89     }
90 
91     if ((ret = avio_read(s->pb, hdr->adpcm, sizeof(hdr->adpcm))) < 0)
92         return ret;
93     else if (ret != sizeof(hdr->adpcm))
94         return AVERROR(EIO);
95 
96     if (strncmp("ADPCM", hdr->adpcm, sizeof(hdr->adpcm)) != 0)
97         return AVERROR_INVALIDDATA;
98 
99     hdr->unk1                   = avio_r8(s->pb);
100     hdr->num_channels           = avio_r8(s->pb);
101 
102     if (hdr->header_size == 8) {
103         /* .TUN music file */
104         hdr->sample_rate        = 22050;
105 
106     } else {
107         /* .PCM sound file */
108         hdr->sample_rate        = avio_rl32(s->pb);
109     }
110 
111     if (hdr->sample_rate > 44100) {
112         avpriv_request_sample(s, "Sample Rate > 44100");
113         return AVERROR_PATCHWELCOME;
114     }
115 
116     if (!(st = avformat_new_stream(s, NULL)))
117         return AVERROR(ENOMEM);
118 
119     par                         = st->codecpar;
120     par->codec_type             = AVMEDIA_TYPE_AUDIO;
121     par->codec_id               = AV_CODEC_ID_ADPCM_IMA_ALP;
122     par->format                 = AV_SAMPLE_FMT_S16;
123     par->sample_rate            = hdr->sample_rate;
124 
125     if (hdr->num_channels > 2 || hdr->num_channels == 0)
126         return AVERROR_INVALIDDATA;
127 
128     av_channel_layout_default(&par->ch_layout, hdr->num_channels);
129     par->bits_per_coded_sample  = 4;
130     par->block_align            = 1;
131     par->bit_rate               = par->ch_layout.nb_channels *
132                                   par->sample_rate *
133                                   par->bits_per_coded_sample;
134 
135     avpriv_set_pts_info(st, 64, 1, par->sample_rate);
136     return 0;
137 }
138 
alp_read_packet(AVFormatContext *s, AVPacket *pkt)139 static int alp_read_packet(AVFormatContext *s, AVPacket *pkt)
140 {
141     int ret;
142     AVCodecParameters *par = s->streams[0]->codecpar;
143 
144     if ((ret = av_get_packet(s->pb, pkt, ALP_MAX_READ_SIZE)) < 0)
145         return ret;
146 
147     pkt->flags         &= ~AV_PKT_FLAG_CORRUPT;
148     pkt->stream_index   = 0;
149     pkt->duration       = ret * 2 / par->ch_layout.nb_channels;
150 
151     return 0;
152 }
153 
alp_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags)154 static int alp_seek(AVFormatContext *s, int stream_index,
155                      int64_t pts, int flags)
156 {
157     const ALPHeader *hdr = s->priv_data;
158 
159     if (pts != 0)
160         return AVERROR(EINVAL);
161 
162     return avio_seek(s->pb, hdr->header_size + 8, SEEK_SET);
163 }
164 
165 const AVInputFormat ff_alp_demuxer = {
166     .name           = "alp",
167     .long_name      = NULL_IF_CONFIG_SMALL("LEGO Racers ALP"),
168     .priv_data_size = sizeof(ALPHeader),
169     .read_probe     = alp_probe,
170     .read_header    = alp_read_header,
171     .read_packet    = alp_read_packet,
172     .read_seek      = alp_seek,
173 };
174 #endif
175 
176 #if CONFIG_ALP_MUXER
177 
alp_write_init(AVFormatContext *s)178 static int alp_write_init(AVFormatContext *s)
179 {
180     ALPMuxContext *alp = s->priv_data;
181     AVCodecParameters *par;
182 
183     if (alp->type == ALP_TYPE_AUTO) {
184         if (av_match_ext(s->url, "pcm"))
185             alp->type = ALP_TYPE_PCM;
186         else
187             alp->type = ALP_TYPE_TUN;
188     }
189 
190     if (s->nb_streams != 1) {
191         av_log(s, AV_LOG_ERROR, "Too many streams\n");
192         return AVERROR(EINVAL);
193     }
194 
195     par = s->streams[0]->codecpar;
196 
197     if (par->codec_id != AV_CODEC_ID_ADPCM_IMA_ALP) {
198         av_log(s, AV_LOG_ERROR, "%s codec not supported\n",
199                avcodec_get_name(par->codec_id));
200         return AVERROR(EINVAL);
201     }
202 
203     if (par->ch_layout.nb_channels > 2) {
204         av_log(s, AV_LOG_ERROR, "A maximum of 2 channels are supported\n");
205         return AVERROR(EINVAL);
206     }
207 
208     if (par->sample_rate > 44100) {
209         av_log(s, AV_LOG_ERROR, "Sample rate too large\n");
210         return AVERROR(EINVAL);
211     }
212 
213     if (alp->type == ALP_TYPE_TUN && par->sample_rate != 22050) {
214         av_log(s, AV_LOG_ERROR, "Sample rate must be 22050 for TUN files\n");
215         return AVERROR(EINVAL);
216     }
217     return 0;
218 }
219 
alp_write_header(AVFormatContext *s)220 static int alp_write_header(AVFormatContext *s)
221 {
222     ALPMuxContext *alp = s->priv_data;
223     AVCodecParameters *par = s->streams[0]->codecpar;
224 
225     avio_wl32(s->pb,  ALP_TAG);
226     avio_wl32(s->pb,  alp->type == ALP_TYPE_PCM ? 12 : 8);
227     avio_write(s->pb, "ADPCM", 6);
228     avio_w8(s->pb,    0);
229     avio_w8(s->pb,    par->ch_layout.nb_channels);
230     if (alp->type == ALP_TYPE_PCM)
231         avio_wl32(s->pb, par->sample_rate);
232 
233     return 0;
234 }
235 
236 enum { AE = AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM };
237 
238 static const AVOption alp_options[] = {
239     {
240         .name        = "type",
241         .help        = "set file type",
242         .offset      = offsetof(ALPMuxContext, type),
243         .type        = AV_OPT_TYPE_INT,
244         .default_val = {.i64 = ALP_TYPE_AUTO},
245         .min         = ALP_TYPE_AUTO,
246         .max         = ALP_TYPE_PCM,
247         .flags       = AE,
248         .unit        = "type",
249     },
250     {
251         .name        = "auto",
252         .help        = "autodetect based on file extension",
253         .offset      = 0,
254         .type        = AV_OPT_TYPE_CONST,
255         .default_val = {.i64 = ALP_TYPE_AUTO},
256         .min         = 0,
257         .max         = 0,
258         .flags       = AE,
259         .unit        = "type"
260     },
261     {
262         .name        = "tun",
263         .help        = "force .tun, used for music",
264         .offset      = 0,
265         .type        = AV_OPT_TYPE_CONST,
266         .default_val = {.i64 = ALP_TYPE_TUN},
267         .min         = 0,
268         .max         = 0,
269         .flags       = AE,
270         .unit        = "type"
271     },
272     {
273         .name        = "pcm",
274         .help        = "force .pcm, used for sfx",
275         .offset      = 0,
276         .type        = AV_OPT_TYPE_CONST,
277         .default_val = {.i64 = ALP_TYPE_PCM},
278         .min         = 0,
279         .max         = 0,
280         .flags       = AE,
281         .unit        = "type"
282     },
283     { NULL }
284 };
285 
286 static const AVClass alp_muxer_class = {
287     .class_name = "alp",
288     .item_name  = av_default_item_name,
289     .option     = alp_options,
290     .version    = LIBAVUTIL_VERSION_INT
291 };
292 
293 const AVOutputFormat ff_alp_muxer = {
294     .name           = "alp",
295     .long_name      = NULL_IF_CONFIG_SMALL("LEGO Racers ALP"),
296     .extensions     = "tun,pcm",
297     .audio_codec    = AV_CODEC_ID_ADPCM_IMA_ALP,
298     .video_codec    = AV_CODEC_ID_NONE,
299     .init           = alp_write_init,
300     .write_header   = alp_write_header,
301     .write_packet   = ff_raw_write_packet,
302     .priv_class     = &alp_muxer_class,
303     .priv_data_size = sizeof(ALPMuxContext)
304 };
305 #endif
306