FFmpeg
apm.c
Go to the documentation of this file.
1 /*
2  * Rayman 2 APM (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 "rawenc.h"
25 #include "libavutil/avassert.h"
26 #include "libavutil/internal.h"
27 #include "libavutil/intreadwrite.h"
28 
29 #define APM_FILE_HEADER_SIZE 20
30 #define APM_FILE_EXTRADATA_SIZE 80
31 #define APM_EXTRADATA_SIZE 28
32 
33 #define APM_MAX_READ_SIZE 4096
34 
35 #define APM_TAG_CODEC 0x2000
36 #define APM_TAG_VS12 MKTAG('v', 's', '1', '2')
37 #define APM_TAG_DATA MKTAG('D', 'A', 'T', 'A')
38 
39 typedef struct APMState {
47 } APMState;
48 
49 typedef struct APMExtraData {
50  uint32_t magic;
51  uint32_t file_size;
52  uint32_t data_size;
53  uint32_t unk1;
54  uint32_t unk2;
56  uint32_t unk3[7];
57  uint32_t data;
58 } APMExtraData;
59 
60 #if CONFIG_APM_DEMUXER
61 static void apm_parse_extradata(APMExtraData *ext, const uint8_t *buf)
62 {
63  ext->magic = AV_RL32(buf + 0);
64  ext->file_size = AV_RL32(buf + 4);
65  ext->data_size = AV_RL32(buf + 8);
66  ext->unk1 = AV_RL32(buf + 12);
67  ext->unk2 = AV_RL32(buf + 16);
68 
69  ext->state.has_saved = AV_RL32(buf + 20);
70  ext->state.predictor_r = AV_RL32(buf + 24);
71  ext->state.step_index_r = AV_RL32(buf + 28);
72  ext->state.saved_r = AV_RL32(buf + 32);
73  ext->state.predictor_l = AV_RL32(buf + 36);
74  ext->state.step_index_l = AV_RL32(buf + 40);
75  ext->state.saved_l = AV_RL32(buf + 44);
76 
77  for (int i = 0; i < FF_ARRAY_ELEMS(ext->unk3); i++)
78  ext->unk3[i] = AV_RL32(buf + 48 + (i * 4));
79 
80  ext->data = AV_RL32(buf + 76);
81 }
82 
83 static int apm_probe(const AVProbeData *p)
84 {
85  if (AV_RL16(p->buf) != APM_TAG_CODEC)
86  return 0;
87 
88  if (p->buf_size < 100)
89  return 0;
90 
91  if (AV_RL32(p->buf + 20) != APM_TAG_VS12)
92  return 0;
93 
94  if (AV_RL32(p->buf + 96) != APM_TAG_DATA)
95  return 0;
96 
97  return AVPROBE_SCORE_MAX - 1;
98 }
99 
100 static int apm_read_header(AVFormatContext *s)
101 {
102  int64_t ret;
103  AVStream *st;
104  APMExtraData extradata;
105  AVCodecParameters *par;
107 
108  if (!(st = avformat_new_stream(s, NULL)))
109  return AVERROR(ENOMEM);
110 
111  /*
112  * This is 98% a WAVEFORMATEX, but there's something screwy with the extradata
113  * that ff_get_wav_header() can't (and shouldn't) handle properly.
114  */
115  if (avio_rl16(s->pb) != APM_TAG_CODEC)
116  return AVERROR_INVALIDDATA;
117 
118  par = st->codecpar;
119  par->channels = avio_rl16(s->pb);
120  par->sample_rate = avio_rl32(s->pb);
121 
122  /* Skip the bitrate, it's usually wrong anyway. */
123  if ((ret = avio_skip(s->pb, 4)) < 0)
124  return ret;
125 
126  par->block_align = avio_rl16(s->pb);
128 
130  return AVERROR_INVALIDDATA;
131 
132  /* 8 = bits per sample * max channels */
133  if (par->sample_rate > (INT_MAX / 8))
134  return AVERROR_INVALIDDATA;
135 
136  if (par->bits_per_coded_sample != 4)
137  return AVERROR_INVALIDDATA;
138 
139  if (par->channels == 2)
141  else if (par->channels == 1)
143  else
144  return AVERROR_INVALIDDATA;
145 
148  par->format = AV_SAMPLE_FMT_S16;
149  par->bits_per_raw_sample = 16;
150  par->bit_rate = par->channels *
151  par->sample_rate *
153 
154  if ((ret = avio_read(s->pb, buf, APM_FILE_EXTRADATA_SIZE)) < 0)
155  return ret;
156  else if (ret != APM_FILE_EXTRADATA_SIZE)
157  return AVERROR(EIO);
158 
159  apm_parse_extradata(&extradata, buf);
160 
161  if (extradata.magic != APM_TAG_VS12 || extradata.data != APM_TAG_DATA)
162  return AVERROR_INVALIDDATA;
163 
164  if (extradata.state.has_saved) {
165  avpriv_request_sample(s, "Saved Samples");
166  return AVERROR_PATCHWELCOME;
167  }
168 
169  if ((ret = ff_alloc_extradata(par, APM_EXTRADATA_SIZE)) < 0)
170  return ret;
171 
172  /* Use the entire state as extradata. */
173  memcpy(par->extradata, buf + 20, APM_EXTRADATA_SIZE);
174 
175  avpriv_set_pts_info(st, 64, 1, par->sample_rate);
176  st->start_time = 0;
177  st->duration = extradata.data_size *
178  (8 / par->bits_per_coded_sample) /
179  par->channels;
180  return 0;
181 }
182 
183 static int apm_read_packet(AVFormatContext *s, AVPacket *pkt)
184 {
185  int ret;
186  AVCodecParameters *par = s->streams[0]->codecpar;
187 
188  /*
189  * For future reference: if files with the `has_saved` field set ever
190  * surface, `saved_l`, and `saved_r` will each contain 8 "saved" samples
191  * that should be sent to the decoder before the actual data.
192  */
193 
194  if ((ret = av_get_packet(s->pb, pkt, APM_MAX_READ_SIZE)) < 0)
195  return ret;
196 
197  pkt->flags &= ~AV_PKT_FLAG_CORRUPT;
198  pkt->stream_index = 0;
199  pkt->duration = ret * (8 / par->bits_per_coded_sample) / par->channels;
200 
201  return 0;
202 }
203 
205  .name = "apm",
206  .long_name = NULL_IF_CONFIG_SMALL("Ubisoft Rayman 2 APM"),
207  .read_probe = apm_probe,
208  .read_header = apm_read_header,
209  .read_packet = apm_read_packet
210 };
211 #endif
212 
213 #if CONFIG_APM_MUXER
214 static int apm_write_init(AVFormatContext *s)
215 {
216  AVCodecParameters *par;
217 
218  if (s->nb_streams != 1) {
219  av_log(s, AV_LOG_ERROR, "APM files have exactly one stream\n");
220  return AVERROR(EINVAL);
221  }
222 
223  par = s->streams[0]->codecpar;
224 
225  if (par->codec_id != AV_CODEC_ID_ADPCM_IMA_APM) {
226  av_log(s, AV_LOG_ERROR, "%s codec not supported\n",
227  avcodec_get_name(par->codec_id));
228  return AVERROR(EINVAL);
229  }
230 
231  if (par->channels > 2) {
232  av_log(s, AV_LOG_ERROR, "APM files only support up to 2 channels\n");
233  return AVERROR(EINVAL);
234  }
235 
236  if (par->sample_rate > (INT_MAX / 8)) {
237  av_log(s, AV_LOG_ERROR, "Sample rate too large\n");
238  return AVERROR(EINVAL);
239  }
240 
241  if (par->extradata_size != APM_EXTRADATA_SIZE) {
242  av_log(s, AV_LOG_ERROR, "Invalid/missing extradata\n");
243  return AVERROR(EINVAL);
244  }
245 
246  if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
247  av_log(s, AV_LOG_ERROR, "Stream not seekable, unable to write output file\n");
248  return AVERROR(EINVAL);
249  }
250 
251  return 0;
252 }
253 
254 static int apm_write_header(AVFormatContext *s)
255 {
256  uint8_t buf[APM_FILE_EXTRADATA_SIZE] = { 0 };
257  AVCodecParameters *par = s->streams[0]->codecpar;
258 
259  /*
260  * Bodge a WAVEFORMATEX manually, ff_put_wav_header() can't
261  * be used because of the extra 2 bytes.
262  */
264  avio_wl16(s->pb, par->channels);
265  avio_wl32(s->pb, par->sample_rate);
266  /* This is the wrong calculation, but it's what the orginal files have. */
267  avio_wl32(s->pb, par->sample_rate * par->channels * 2);
268  avio_wl16(s->pb, par->block_align);
271 
272  /*
273  * Build the extradata. Assume the codec's given us correct data.
274  * File and data sizes are fixed later.
275  */
276  AV_WL32(buf + 0, APM_TAG_VS12); /* magic */
277  AV_WL32(buf + 12, 0xFFFFFFFF); /* unk1 */
278  memcpy( buf + 20, par->extradata, APM_EXTRADATA_SIZE);
279  AV_WL32(buf + 76, APM_TAG_DATA); /* data */
280 
282  return 0;
283 }
284 
285 static int apm_write_trailer(AVFormatContext *s)
286 {
287  int64_t file_size, data_size;
288 
289  file_size = avio_tell(s->pb);
290  data_size = file_size - (APM_FILE_HEADER_SIZE + APM_FILE_EXTRADATA_SIZE);
291 
292  if (file_size >= UINT32_MAX) {
293  av_log(s, AV_LOG_ERROR,
294  "Filesize %"PRId64" invalid for APM, output file will be broken\n",
295  file_size);
296  return AVERROR(ERANGE);
297  }
298 
299  avio_seek(s->pb, 24, SEEK_SET);
300  avio_wl32(s->pb, (uint32_t)file_size);
301  avio_wl32(s->pb, (uint32_t)data_size);
302 
303  return 0;
304 }
305 
307  .name = "apm",
308  .long_name = NULL_IF_CONFIG_SMALL("Ubisoft Rayman 2 APM"),
309  .extensions = "apm",
310  .audio_codec = AV_CODEC_ID_ADPCM_IMA_APM,
311  .video_codec = AV_CODEC_ID_NONE,
312  .init = apm_write_init,
313  .write_header = apm_write_header,
314  .write_packet = ff_raw_write_packet,
315  .write_trailer = apm_write_trailer
316 };
317 #endif
APMState state
Definition: apm.c:55
#define NULL
Definition: coverity.c:32
void avio_wl16(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:459
int32_t has_saved
Definition: apm.c:40
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
int32_t saved_r
Definition: apm.c:43
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:4900
uint32_t unk3[7]
Definition: apm.c:56
#define avpriv_request_sample(...)
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: codec_par.h:60
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:253
uint32_t data
Definition: apm.c:57
uint32_t unk1
Definition: apm.c:53
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: aviobuf.c:341
static AVPacket pkt
#define AV_CH_LAYOUT_STEREO
Definition: apm.c:39
#define APM_TAG_CODEC
Definition: apm.c:35
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_RL16
Definition: bytestream.h:91
This struct describes the properties of an encoded stream.
Definition: codec_par.h:52
#define APM_EXTRADATA_SIZE
Definition: apm.c:31
int32_t step_index_l
Definition: apm.c:45
int32_t predictor_l
Definition: apm.c:44
Format I/O context.
Definition: avformat.h:1239
int32_t predictor_r
Definition: apm.c:41
void avio_wl32(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:379
uint8_t
#define APM_FILE_HEADER_SIZE
Definition: apm.c:29
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: packet.h:381
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:4481
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1307
uint32_t data_size
Definition: apm.c:52
int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
Allocate and read the payload of a packet and initialize its fields with default values.
Definition: utils.c:310
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:557
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:225
uint64_t channel_layout
Audio only.
Definition: codec_par.h:162
#define av_log(a,...)
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:637
int64_t bit_rate
The average bitrate of the encoded data (in bits per second).
Definition: codec_par.h:89
int32_t saved_l
Definition: apm.c:46
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:194
unsigned int avio_rl32(AVIOContext *s)
Definition: aviobuf.c:754
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:115
enum AVMediaType codec_type
General type of the encoded data.
Definition: codec_par.h:56
uint32_t unk2
Definition: apm.c:54
simple assert() macros that are a bit more flexible than ISO C assert().
int flags
A combination of AV_PKT_FLAG values.
Definition: packet.h:369
AVInputFormat ff_apm_demuxer
int extradata_size
Size of the extradata content in bytes.
Definition: codec_par.h:78
int buf_size
Size of buf except extra allocated bytes.
Definition: avformat.h:444
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:443
common internal API header
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1295
int block_align
Audio only.
Definition: codec_par.h:177
uint32_t magic
Definition: apm.c:50
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:260
int ff_alloc_extradata(AVCodecParameters *par, int size)
Allocate extradata with additional AV_INPUT_BUFFER_PADDING_SIZE at end which is always set to 0...
Definition: utils.c:3286
#define APM_TAG_DATA
Definition: apm.c:37
#define APM_MAX_READ_SIZE
Definition: apm.c:33
const char * name
Definition: avformat.h:500
int32_t
#define s(width, name)
Definition: cbs_vp9.c:257
int ff_raw_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: rawenc.c:29
#define FF_ARRAY_ELEMS(a)
Stream structure.
Definition: avformat.h:880
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
#define AVIO_SEEKABLE_NORMAL
Seeking works like for a local file.
Definition: avio.h:40
uint32_t file_size
Definition: apm.c:51
AVIOContext * pb
I/O context.
Definition: avformat.h:1281
AVOutputFormat ff_apm_muxer
This structure contains the data a format has to probe a file.
Definition: avformat.h:441
int bits_per_raw_sample
This is the number of valid bits in each output sample.
Definition: codec_par.h:115
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:929
int sample_rate
Audio only.
Definition: codec_par.h:170
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:453
unsigned int avio_rl16(AVIOContext *s)
Definition: aviobuf.c:738
Main libavformat public API header.
int64_t start_time
Decoding: pts of the first frame of the stream in presentation order, in stream time base...
Definition: avformat.h:919
signed 16 bits
Definition: samplefmt.h:61
const char * avcodec_get_name(enum AVCodecID id)
Get the name of a codec.
Definition: utils.c:1236
#define AV_PKT_FLAG_CORRUPT
The packet content is corrupted.
Definition: packet.h:402
int bits_per_coded_sample
The number of bits per sample in the codedwords.
Definition: codec_par.h:102
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: codec_par.h:74
int channels
Audio only.
Definition: codec_par.h:166
#define APM_FILE_EXTRADATA_SIZE
Definition: apm.c:30
#define APM_TAG_VS12
Definition: apm.c:36
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:652
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:1045
int stream_index
Definition: packet.h:365
int32_t step_index_r
Definition: apm.c:42
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later.That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another.Frame references ownership and permissions
#define AV_CH_LAYOUT_MONO
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_RL32
Definition: bytestream.h:91
This structure stores compressed data.
Definition: packet.h:340
int i
Definition: input.c:407
#define AV_WL32(p, v)
Definition: intreadwrite.h:426