Monkey Audio decoder
[libav.git] / libavformat / ape.c
1 /*
2 * Monkey's Audio APE demuxer
3 * Copyright (c) 2007 Benjamin Zores <ben@geexbox.org>
4 * based upon libdemac from Dave Chapman.
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 <stdio.h>
24
25 #include "avformat.h"
26
27 /* The earliest and latest file formats supported by this library */
28 #define APE_MIN_VERSION 3970
29 #define APE_MAX_VERSION 3990
30
31 #define MAC_FORMAT_FLAG_8_BIT 1 // is 8-bit [OBSOLETE]
32 #define MAC_FORMAT_FLAG_CRC 2 // uses the new CRC32 error detection [OBSOLETE]
33 #define MAC_FORMAT_FLAG_HAS_PEAK_LEVEL 4 // uint32 nPeakLevel after the header [OBSOLETE]
34 #define MAC_FORMAT_FLAG_24_BIT 8 // is 24-bit [OBSOLETE]
35 #define MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS 16 // has the number of seek elements after the peak level
36 #define MAC_FORMAT_FLAG_CREATE_WAV_HEADER 32 // create the wave header on decompression (not stored)
37
38 #define MAC_SUBFRAME_SIZE 4608
39
40 #define APE_EXTRADATA_SIZE 6
41
42 typedef struct {
43 int64_t pos;
44 int nblocks;
45 int size;
46 int skip;
47 int64_t pts;
48 } APEFrame;
49
50 typedef struct {
51 /* Derived fields */
52 uint32_t junklength;
53 uint32_t firstframe;
54 uint32_t totalsamples;
55 int currentframe;
56 APEFrame *frames;
57
58 /* Info from Descriptor Block */
59 char magic[4];
60 int16_t fileversion;
61 int16_t padding1;
62 uint32_t descriptorlength;
63 uint32_t headerlength;
64 uint32_t seektablelength;
65 uint32_t wavheaderlength;
66 uint32_t audiodatalength;
67 uint32_t audiodatalength_high;
68 uint32_t wavtaillength;
69 uint8_t md5[16];
70
71 /* Info from Header Block */
72 uint16_t compressiontype;
73 uint16_t formatflags;
74 uint32_t blocksperframe;
75 uint32_t finalframeblocks;
76 uint32_t totalframes;
77 uint16_t bps;
78 uint16_t channels;
79 uint32_t samplerate;
80
81 /* Seektable */
82 uint32_t *seektable;
83 } APEContext;
84
85 static int ape_probe(AVProbeData * p)
86 {
87 if (p->buf[0] == 'M' && p->buf[1] == 'A' && p->buf[2] == 'C' && p->buf[3] == ' ')
88 return AVPROBE_SCORE_MAX;
89
90 return 0;
91 }
92
93 static void ape_dumpinfo(APEContext * ape_ctx)
94 {
95 int i;
96
97 av_log(NULL, AV_LOG_DEBUG, "Descriptor Block:\n\n");
98 av_log(NULL, AV_LOG_DEBUG, "magic = \"%c%c%c%c\"\n", ape_ctx->magic[0], ape_ctx->magic[1], ape_ctx->magic[2], ape_ctx->magic[3]);
99 av_log(NULL, AV_LOG_DEBUG, "fileversion = %d\n", ape_ctx->fileversion);
100 av_log(NULL, AV_LOG_DEBUG, "descriptorlength = %d\n", ape_ctx->descriptorlength);
101 av_log(NULL, AV_LOG_DEBUG, "headerlength = %d\n", ape_ctx->headerlength);
102 av_log(NULL, AV_LOG_DEBUG, "seektablelength = %d\n", ape_ctx->seektablelength);
103 av_log(NULL, AV_LOG_DEBUG, "wavheaderlength = %d\n", ape_ctx->wavheaderlength);
104 av_log(NULL, AV_LOG_DEBUG, "audiodatalength = %d\n", ape_ctx->audiodatalength);
105 av_log(NULL, AV_LOG_DEBUG, "audiodatalength_high = %d\n", ape_ctx->audiodatalength_high);
106 av_log(NULL, AV_LOG_DEBUG, "wavtaillength = %d\n", ape_ctx->wavtaillength);
107 av_log(NULL, AV_LOG_DEBUG, "md5 = ");
108 for (i = 0; i < 16; i++)
109 av_log(NULL, AV_LOG_DEBUG, "%02x", ape_ctx->md5[i]);
110 av_log(NULL, AV_LOG_DEBUG, "\n");
111
112 av_log(NULL, AV_LOG_DEBUG, "\nHeader Block:\n\n");
113
114 av_log(NULL, AV_LOG_DEBUG, "compressiontype = %d\n", ape_ctx->compressiontype);
115 av_log(NULL, AV_LOG_DEBUG, "formatflags = %d\n", ape_ctx->formatflags);
116 av_log(NULL, AV_LOG_DEBUG, "blocksperframe = %d\n", ape_ctx->blocksperframe);
117 av_log(NULL, AV_LOG_DEBUG, "finalframeblocks = %d\n", ape_ctx->finalframeblocks);
118 av_log(NULL, AV_LOG_DEBUG, "totalframes = %d\n", ape_ctx->totalframes);
119 av_log(NULL, AV_LOG_DEBUG, "bps = %d\n", ape_ctx->bps);
120 av_log(NULL, AV_LOG_DEBUG, "channels = %d\n", ape_ctx->channels);
121 av_log(NULL, AV_LOG_DEBUG, "samplerate = %d\n", ape_ctx->samplerate);
122
123 av_log(NULL, AV_LOG_DEBUG, "\nSeektable\n\n");
124 if ((ape_ctx->seektablelength / sizeof(uint32_t)) != ape_ctx->totalframes) {
125 av_log(NULL, AV_LOG_DEBUG, "No seektable\n");
126 } else {
127 for (i = 0; i < ape_ctx->seektablelength / sizeof(uint32_t); i++) {
128 if (i < ape_ctx->totalframes - 1) {
129 av_log(NULL, AV_LOG_DEBUG, "%8d %d (%d bytes)\n", i, ape_ctx->seektable[i], ape_ctx->seektable[i + 1] - ape_ctx->seektable[i]);
130 } else {
131 av_log(NULL, AV_LOG_DEBUG, "%8d %d\n", i, ape_ctx->seektable[i]);
132 }
133 }
134 }
135
136 av_log(NULL, AV_LOG_DEBUG, "\nFrames\n\n");
137 for (i = 0; i < ape_ctx->totalframes; i++)
138 av_log(NULL, AV_LOG_DEBUG, "%8d %8lld %8d (%d samples)\n", i, ape_ctx->frames[i].pos, ape_ctx->frames[i].size, ape_ctx->frames[i].nblocks);
139
140 av_log(NULL, AV_LOG_DEBUG, "\nCalculated information:\n\n");
141 av_log(NULL, AV_LOG_DEBUG, "junklength = %d\n", ape_ctx->junklength);
142 av_log(NULL, AV_LOG_DEBUG, "firstframe = %d\n", ape_ctx->firstframe);
143 av_log(NULL, AV_LOG_DEBUG, "totalsamples = %d\n", ape_ctx->totalsamples);
144 }
145
146 static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap)
147 {
148 ByteIOContext *pb = &s->pb;
149 APEContext *ape = s->priv_data;
150 AVStream *st;
151 uint32_t tag;
152 int i;
153 int total_blocks;
154 int64_t pts;
155
156 /* TODO: Skip any leading junk such as id3v2 tags */
157 ape->junklength = 0;
158
159 tag = get_le32(pb);
160 if (tag != MKTAG('M', 'A', 'C', ' '))
161 return -1;
162
163 ape->fileversion = get_le16(pb);
164
165 if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) {
166 av_log(s, AV_LOG_ERROR, "Unsupported file version - %d.%02d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10);
167 return -1;
168 }
169
170 if (ape->fileversion >= 3980) {
171 ape->padding1 = get_le16(pb);
172 ape->descriptorlength = get_le32(pb);
173 ape->headerlength = get_le32(pb);
174 ape->seektablelength = get_le32(pb);
175 ape->wavheaderlength = get_le32(pb);
176 ape->audiodatalength = get_le32(pb);
177 ape->audiodatalength_high = get_le32(pb);
178 ape->wavtaillength = get_le32(pb);
179 get_buffer(pb, ape->md5, 16);
180
181 /* Skip any unknown bytes at the end of the descriptor.
182 This is for future compatibility */
183 if (ape->descriptorlength > 52)
184 url_fseek(pb, ape->descriptorlength - 52, SEEK_CUR);
185
186 /* Read header data */
187 ape->compressiontype = get_le16(pb);
188 ape->formatflags = get_le16(pb);
189 ape->blocksperframe = get_le32(pb);
190 ape->finalframeblocks = get_le32(pb);
191 ape->totalframes = get_le32(pb);
192 ape->bps = get_le16(pb);
193 ape->channels = get_le16(pb);
194 ape->samplerate = get_le32(pb);
195 } else {
196 ape->descriptorlength = 0;
197 ape->headerlength = 32;
198
199 ape->compressiontype = get_le16(pb);
200 ape->formatflags = get_le16(pb);
201 ape->channels = get_le16(pb);
202 ape->samplerate = get_le32(pb);
203 ape->wavheaderlength = get_le32(pb);
204 ape->wavtaillength = get_le32(pb);
205 ape->totalframes = get_le32(pb);
206 ape->finalframeblocks = get_le32(pb);
207
208 if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) {
209 url_fseek(pb, 4, SEEK_CUR); /* Skip the peak level */
210 ape->headerlength += 4;
211 }
212
213 if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) {
214 ape->seektablelength = get_le32(pb);
215 ape->headerlength += 4;
216 ape->seektablelength *= sizeof(int32_t);
217 } else
218 ape->seektablelength = ape->totalframes * sizeof(int32_t);
219
220 if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT)
221 ape->bps = 8;
222 else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT)
223 ape->bps = 24;
224 else
225 ape->bps = 16;
226
227 if (ape->fileversion >= 3950)
228 ape->blocksperframe = 73728 * 4;
229 else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800 && ape->compressiontype >= 4000))
230 ape->blocksperframe = 73728;
231 else
232 ape->blocksperframe = 9216;
233
234 /* Skip any stored wav header */
235 if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER))
236 url_fskip(pb, ape->wavheaderlength);
237 }
238
239 if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){
240 av_log(s, AV_LOG_ERROR, "Too many frames: %d\n", ape->totalframes);
241 return -1;
242 }
243 ape->frames = av_malloc(ape->totalframes * sizeof(APEFrame));
244 if(!ape->frames)
245 return AVERROR_NOMEM;
246 ape->firstframe = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength;
247 ape->currentframe = 0;
248
249
250 ape->totalsamples = ape->finalframeblocks;
251 if (ape->totalframes > 1)
252 ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1);
253
254 if (ape->seektablelength > 0) {
255 ape->seektable = av_malloc(ape->seektablelength);
256 for (i = 0; i < ape->seektablelength / sizeof(uint32_t); i++)
257 ape->seektable[i] = get_le32(pb);
258 }
259
260 ape->frames[0].pos = ape->firstframe;
261 ape->frames[0].nblocks = ape->blocksperframe;
262 ape->frames[0].skip = 0;
263 for (i = 1; i < ape->totalframes; i++) {
264 ape->frames[i].pos = ape->seektable[i]; //ape->frames[i-1].pos + ape->blocksperframe;
265 ape->frames[i].nblocks = ape->blocksperframe;
266 ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos;
267 ape->frames[i].skip = (ape->frames[i].pos - ape->frames[0].pos) & 3;
268 }
269 ape->frames[ape->totalframes - 1].size = ape->finalframeblocks * 4;
270 ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks;
271
272 for (i = 0; i < ape->totalframes; i++) {
273 if(ape->frames[i].skip){
274 ape->frames[i].pos -= ape->frames[i].skip;
275 ape->frames[i].size += ape->frames[i].skip;
276 }
277 ape->frames[i].size = (ape->frames[i].size + 3) & ~3;
278 }
279
280
281 ape_dumpinfo(ape);
282
283 av_log(s, AV_LOG_DEBUG, "Decoding file - v%d.%02d, compression level %d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10, ape->compressiontype);
284
285 /* now we are ready: build format streams */
286 st = av_new_stream(s, 0);
287 if (!st)
288 return -1;
289
290 total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks;
291
292 st->codec->codec_type = CODEC_TYPE_AUDIO;
293 st->codec->codec_id = CODEC_ID_APE;
294 st->codec->codec_tag = MKTAG('A', 'P', 'E', ' ');
295 st->codec->channels = ape->channels;
296 st->codec->sample_rate = ape->samplerate;
297 st->codec->bits_per_sample = ape->bps;
298 st->codec->frame_size = MAC_SUBFRAME_SIZE;
299
300 st->nb_frames = ape->totalframes;
301 s->start_time = 0;
302 s->duration = (int64_t) total_blocks * AV_TIME_BASE / ape->samplerate;
303 av_set_pts_info(st, 64, MAC_SUBFRAME_SIZE, ape->samplerate);
304
305 st->codec->extradata = av_malloc(APE_EXTRADATA_SIZE);
306 st->codec->extradata_size = APE_EXTRADATA_SIZE;
307 AV_WL16(st->codec->extradata + 0, ape->fileversion);
308 AV_WL16(st->codec->extradata + 2, ape->compressiontype);
309 AV_WL16(st->codec->extradata + 4, ape->formatflags);
310
311 pts = 0;
312 for (i = 0; i < ape->totalframes; i++) {
313 ape->frames[i].pts = pts;
314 av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME);
315 pts += ape->blocksperframe / MAC_SUBFRAME_SIZE;
316 }
317
318 return 0;
319 }
320
321 static int ape_read_packet(AVFormatContext * s, AVPacket * pkt)
322 {
323 int ret;
324 int nblocks;
325 APEContext *ape = s->priv_data;
326 uint32_t extra_size = 8;
327
328 if (url_feof(&s->pb))
329 return AVERROR_IO;
330 if (ape->currentframe > ape->totalframes)
331 return AVERROR_IO;
332
333 url_fseek (&s->pb, ape->frames[ape->currentframe].pos, SEEK_SET);
334
335 /* Calculate how many blocks there are in this frame */
336 if (ape->currentframe == (ape->totalframes - 1))
337 nblocks = ape->finalframeblocks;
338 else
339 nblocks = ape->blocksperframe;
340
341 if (av_new_packet(pkt, ape->frames[ape->currentframe].size + extra_size) < 0)
342 return AVERROR_NOMEM;
343
344 AV_WL32(pkt->data , nblocks);
345 AV_WL32(pkt->data + 4, ape->frames[ape->currentframe].skip);
346 ret = get_buffer(&s->pb, pkt->data + extra_size, ape->frames[ape->currentframe].size);
347
348 pkt->pts = ape->frames[ape->currentframe].pts;
349 pkt->stream_index = 0;
350
351 /* note: we need to modify the packet size here to handle the last
352 packet */
353 pkt->size = ret + extra_size;
354
355 ape->currentframe++;
356
357 return 0;
358 }
359
360 static int ape_read_close(AVFormatContext * s)
361 {
362 APEContext *ape = s->priv_data;
363
364 av_freep(&ape->frames);
365 av_freep(&ape->seektable);
366 return 0;
367 }
368
369 static int ape_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
370 {
371 AVStream *st = s->streams[stream_index];
372 APEContext *ape = s->priv_data;
373 int index = av_index_search_timestamp(st, timestamp, flags);
374
375 if (index < 0)
376 return -1;
377
378 ape->currentframe = index;
379 return 0;
380 }
381
382 AVInputFormat ape_demuxer = {
383 "ape",
384 "Monkey's Audio",
385 sizeof(APEContext),
386 ape_probe,
387 ape_read_header,
388 ape_read_packet,
389 ape_read_close,
390 ape_read_seek,
391 .extensions = "ape,apl,mac"
392 };