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 "libavutil/intreadwrite.h"
26 #include "avformat.h"
27 #include "internal.h"
28 #include "apetag.h"
29
30 /* The earliest and latest file formats supported by this library */
31 #define APE_MIN_VERSION 3800
32 #define APE_MAX_VERSION 3990
33
34 #define MAC_FORMAT_FLAG_8_BIT 1 // is 8-bit [OBSOLETE]
35 #define MAC_FORMAT_FLAG_CRC 2 // uses the new CRC32 error detection [OBSOLETE]
36 #define MAC_FORMAT_FLAG_HAS_PEAK_LEVEL 4 // uint32 nPeakLevel after the header [OBSOLETE]
37 #define MAC_FORMAT_FLAG_24_BIT 8 // is 24-bit [OBSOLETE]
38 #define MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS 16 // has the number of seek elements after the peak level
39 #define MAC_FORMAT_FLAG_CREATE_WAV_HEADER 32 // create the wave header on decompression (not stored)
40
41 #define APE_EXTRADATA_SIZE 6
42
43 typedef struct APEFrame {
44 int64_t pos;
45 int nblocks;
46 int size;
47 int skip;
48 int64_t pts;
49 } APEFrame;
50
51 typedef struct APEContext {
52 /* Derived fields */
53 uint32_t junklength;
54 uint32_t firstframe;
55 uint32_t totalsamples;
56 int currentframe;
57 APEFrame *frames;
58
59 /* Info from Descriptor Block */
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 } APEContext;
81
82 static int ape_read_close(AVFormatContext * s);
83
ape_probe(const AVProbeData * p)84 static int ape_probe(const AVProbeData * p)
85 {
86 int version = AV_RL16(p->buf+4);
87 if (AV_RL32(p->buf) != MKTAG('M', 'A', 'C', ' '))
88 return 0;
89
90 if (version < APE_MIN_VERSION || version > APE_MAX_VERSION)
91 return AVPROBE_SCORE_MAX/4;
92
93 return AVPROBE_SCORE_MAX;
94 }
95
ape_dumpinfo(AVFormatContext * s,APEContext * ape_ctx)96 static void ape_dumpinfo(AVFormatContext * s, APEContext * ape_ctx)
97 {
98 #ifdef DEBUG
99 int i;
100
101 av_log(s, AV_LOG_DEBUG, "Descriptor Block:\n\n");
102 av_log(s, AV_LOG_DEBUG, "fileversion = %"PRId16"\n", ape_ctx->fileversion);
103 av_log(s, AV_LOG_DEBUG, "descriptorlength = %"PRIu32"\n", ape_ctx->descriptorlength);
104 av_log(s, AV_LOG_DEBUG, "headerlength = %"PRIu32"\n", ape_ctx->headerlength);
105 av_log(s, AV_LOG_DEBUG, "seektablelength = %"PRIu32"\n", ape_ctx->seektablelength);
106 av_log(s, AV_LOG_DEBUG, "wavheaderlength = %"PRIu32"\n", ape_ctx->wavheaderlength);
107 av_log(s, AV_LOG_DEBUG, "audiodatalength = %"PRIu32"\n", ape_ctx->audiodatalength);
108 av_log(s, AV_LOG_DEBUG, "audiodatalength_high = %"PRIu32"\n", ape_ctx->audiodatalength_high);
109 av_log(s, AV_LOG_DEBUG, "wavtaillength = %"PRIu32"\n", ape_ctx->wavtaillength);
110 av_log(s, AV_LOG_DEBUG, "md5 = ");
111 for (i = 0; i < 16; i++)
112 av_log(s, AV_LOG_DEBUG, "%02x", ape_ctx->md5[i]);
113 av_log(s, AV_LOG_DEBUG, "\n");
114
115 av_log(s, AV_LOG_DEBUG, "\nHeader Block:\n\n");
116
117 av_log(s, AV_LOG_DEBUG, "compressiontype = %"PRIu16"\n", ape_ctx->compressiontype);
118 av_log(s, AV_LOG_DEBUG, "formatflags = %"PRIu16"\n", ape_ctx->formatflags);
119 av_log(s, AV_LOG_DEBUG, "blocksperframe = %"PRIu32"\n", ape_ctx->blocksperframe);
120 av_log(s, AV_LOG_DEBUG, "finalframeblocks = %"PRIu32"\n", ape_ctx->finalframeblocks);
121 av_log(s, AV_LOG_DEBUG, "totalframes = %"PRIu32"\n", ape_ctx->totalframes);
122 av_log(s, AV_LOG_DEBUG, "bps = %"PRIu16"\n", ape_ctx->bps);
123 av_log(s, AV_LOG_DEBUG, "channels = %"PRIu16"\n", ape_ctx->channels);
124 av_log(s, AV_LOG_DEBUG, "samplerate = %"PRIu32"\n", ape_ctx->samplerate);
125
126 av_log(s, AV_LOG_DEBUG, "\nSeektable\n\n");
127 if ((ape_ctx->seektablelength / sizeof(uint32_t)) != ape_ctx->totalframes) {
128 av_log(s, AV_LOG_DEBUG, "No seektable\n");
129 }
130
131 av_log(s, AV_LOG_DEBUG, "\nFrames\n\n");
132 for (i = 0; i < ape_ctx->totalframes; i++)
133 av_log(s, AV_LOG_DEBUG, "%8d %8"PRId64" %8d (%d samples)\n", i,
134 ape_ctx->frames[i].pos, ape_ctx->frames[i].size,
135 ape_ctx->frames[i].nblocks);
136
137 av_log(s, AV_LOG_DEBUG, "\nCalculated information:\n\n");
138 av_log(s, AV_LOG_DEBUG, "junklength = %"PRIu32"\n", ape_ctx->junklength);
139 av_log(s, AV_LOG_DEBUG, "firstframe = %"PRIu32"\n", ape_ctx->firstframe);
140 av_log(s, AV_LOG_DEBUG, "totalsamples = %"PRIu32"\n", ape_ctx->totalsamples);
141 #endif
142 }
143
ape_read_header(AVFormatContext * s)144 static int ape_read_header(AVFormatContext * s)
145 {
146 AVIOContext *pb = s->pb;
147 APEContext *ape = s->priv_data;
148 AVStream *st;
149 uint32_t tag;
150 int i, ret;
151 int total_blocks, final_size = 0;
152 int64_t pts, file_size;
153
154 /* Skip any leading junk such as id3v2 tags */
155 ape->junklength = avio_tell(pb);
156
157 tag = avio_rl32(pb);
158 if (tag != MKTAG('M', 'A', 'C', ' '))
159 return AVERROR_INVALIDDATA;
160
161 ape->fileversion = avio_rl16(pb);
162
163 if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) {
164 av_log(s, AV_LOG_ERROR, "Unsupported file version - %d.%02d\n",
165 ape->fileversion / 1000, (ape->fileversion % 1000) / 10);
166 return AVERROR_PATCHWELCOME;
167 }
168
169 if (ape->fileversion >= 3980) {
170 ape->padding1 = avio_rl16(pb);
171 ape->descriptorlength = avio_rl32(pb);
172 ape->headerlength = avio_rl32(pb);
173 ape->seektablelength = avio_rl32(pb);
174 ape->wavheaderlength = avio_rl32(pb);
175 ape->audiodatalength = avio_rl32(pb);
176 ape->audiodatalength_high = avio_rl32(pb);
177 ape->wavtaillength = avio_rl32(pb);
178 avio_read(pb, ape->md5, 16);
179
180 /* Skip any unknown bytes at the end of the descriptor.
181 This is for future compatibility */
182 if (ape->descriptorlength > 52)
183 avio_skip(pb, ape->descriptorlength - 52);
184
185 /* Read header data */
186 ape->compressiontype = avio_rl16(pb);
187 ape->formatflags = avio_rl16(pb);
188 ape->blocksperframe = avio_rl32(pb);
189 ape->finalframeblocks = avio_rl32(pb);
190 ape->totalframes = avio_rl32(pb);
191 ape->bps = avio_rl16(pb);
192 ape->channels = avio_rl16(pb);
193 ape->samplerate = avio_rl32(pb);
194 } else {
195 ape->descriptorlength = 0;
196 ape->headerlength = 32;
197
198 ape->compressiontype = avio_rl16(pb);
199 ape->formatflags = avio_rl16(pb);
200 ape->channels = avio_rl16(pb);
201 ape->samplerate = avio_rl32(pb);
202 ape->wavheaderlength = avio_rl32(pb);
203 ape->wavtaillength = avio_rl32(pb);
204 ape->totalframes = avio_rl32(pb);
205 ape->finalframeblocks = avio_rl32(pb);
206
207 if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) {
208 avio_skip(pb, 4); /* Skip the peak level */
209 ape->headerlength += 4;
210 }
211
212 if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) {
213 ape->seektablelength = avio_rl32(pb);
214 ape->headerlength += 4;
215 ape->seektablelength *= sizeof(int32_t);
216 } else
217 ape->seektablelength = ape->totalframes * sizeof(int32_t);
218
219 if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT)
220 ape->bps = 8;
221 else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT)
222 ape->bps = 24;
223 else
224 ape->bps = 16;
225
226 if (ape->fileversion >= 3950)
227 ape->blocksperframe = 73728 * 4;
228 else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800 && ape->compressiontype >= 4000))
229 ape->blocksperframe = 73728;
230 else
231 ape->blocksperframe = 9216;
232
233 /* Skip any stored wav header */
234 if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER))
235 avio_skip(pb, ape->wavheaderlength);
236 }
237
238 if(!ape->totalframes || pb->eof_reached){
239 av_log(s, AV_LOG_ERROR, "No frames in the file!\n");
240 return AVERROR(EINVAL);
241 }
242 if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){
243 av_log(s, AV_LOG_ERROR, "Too many frames: %"PRIu32"\n",
244 ape->totalframes);
245 return AVERROR_INVALIDDATA;
246 }
247 if (ape->seektablelength / sizeof(uint32_t) < ape->totalframes) {
248 av_log(s, AV_LOG_ERROR,
249 "Number of seek entries is less than number of frames: %"SIZE_SPECIFIER" vs. %"PRIu32"\n",
250 ape->seektablelength / sizeof(uint32_t), ape->totalframes);
251 return AVERROR_INVALIDDATA;
252 }
253 ape->frames = av_malloc_array(ape->totalframes, sizeof(APEFrame));
254 if(!ape->frames)
255 return AVERROR(ENOMEM);
256 ape->firstframe = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength;
257 if (ape->fileversion < 3810)
258 ape->firstframe += ape->totalframes;
259 ape->currentframe = 0;
260
261
262 ape->totalsamples = ape->finalframeblocks;
263 if (ape->totalframes > 1)
264 ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1);
265
266 ape->frames[0].pos = ape->firstframe;
267 ape->frames[0].nblocks = ape->blocksperframe;
268 ape->frames[0].skip = 0;
269 avio_rl32(pb); // seektable[0]
270 for (i = 1; i < ape->totalframes; i++) {
271 uint32_t seektable_entry = avio_rl32(pb);
272 ape->frames[i].pos = seektable_entry + ape->junklength;
273 ape->frames[i].nblocks = ape->blocksperframe;
274 ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos;
275 ape->frames[i].skip = (ape->frames[i].pos - ape->frames[0].pos) & 3;
276
277 if (pb->eof_reached) {
278 av_log(s, AV_LOG_ERROR, "seektable truncated\n");
279 ret = AVERROR_INVALIDDATA;
280 goto fail;
281 }
282 ff_dlog(s, "seektable: %8d %"PRIu32"\n", i, seektable_entry);
283 }
284 avio_skip(pb, ape->seektablelength / sizeof(uint32_t) - ape->totalframes);
285
286 ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks;
287 /* calculate final packet size from total file size, if available */
288 file_size = avio_size(pb);
289 if (file_size > 0) {
290 final_size = file_size - ape->frames[ape->totalframes - 1].pos -
291 ape->wavtaillength;
292 final_size -= final_size & 3;
293 }
294 if (file_size <= 0 || final_size <= 0)
295 final_size = ape->finalframeblocks * 8;
296 ape->frames[ape->totalframes - 1].size = final_size;
297
298 for (i = 0; i < ape->totalframes; i++) {
299 if(ape->frames[i].skip){
300 ape->frames[i].pos -= ape->frames[i].skip;
301 ape->frames[i].size += ape->frames[i].skip;
302 }
303 ape->frames[i].size = (ape->frames[i].size + 3) & ~3;
304 }
305 if (ape->fileversion < 3810) {
306 for (i = 0; i < ape->totalframes; i++) {
307 int bits = avio_r8(pb);
308 if (i && bits)
309 ape->frames[i - 1].size += 4;
310
311 ape->frames[i].skip <<= 3;
312 ape->frames[i].skip += bits;
313 ff_dlog(s, "bittable: %2d\n", bits);
314 if (pb->eof_reached) {
315 av_log(s, AV_LOG_ERROR, "bittable truncated\n");
316 ret = AVERROR_INVALIDDATA;
317 goto fail;
318 }
319 }
320 }
321
322 ape_dumpinfo(s, ape);
323
324 av_log(s, AV_LOG_VERBOSE, "Decoding file - v%d.%02d, compression level %"PRIu16"\n",
325 ape->fileversion / 1000, (ape->fileversion % 1000) / 10,
326 ape->compressiontype);
327
328 /* now we are ready: build format streams */
329 st = avformat_new_stream(s, NULL);
330 if (!st) {
331 ret = AVERROR(ENOMEM);
332 goto fail;
333 }
334
335 total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks;
336
337 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
338 st->codecpar->codec_id = AV_CODEC_ID_APE;
339 st->codecpar->codec_tag = MKTAG('A', 'P', 'E', ' ');
340 st->codecpar->channels = ape->channels;
341 st->codecpar->sample_rate = ape->samplerate;
342 st->codecpar->bits_per_coded_sample = ape->bps;
343
344 st->nb_frames = ape->totalframes;
345 st->start_time = 0;
346 st->duration = total_blocks;
347 avpriv_set_pts_info(st, 64, 1, ape->samplerate);
348
349 if ((ret = ff_alloc_extradata(st->codecpar, APE_EXTRADATA_SIZE)) < 0)
350 goto fail;
351 AV_WL16(st->codecpar->extradata + 0, ape->fileversion);
352 AV_WL16(st->codecpar->extradata + 2, ape->compressiontype);
353 AV_WL16(st->codecpar->extradata + 4, ape->formatflags);
354
355 pts = 0;
356 for (i = 0; i < ape->totalframes; i++) {
357 ape->frames[i].pts = pts;
358 av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME);
359 pts += ape->blocksperframe;
360 }
361
362 /* try to read APE tags */
363 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
364 ff_ape_parse_tag(s);
365 avio_seek(pb, 0, SEEK_SET);
366 }
367
368 return 0;
369 fail:
370 ape_read_close(s);
371
372 return ret;
373 }
374
ape_read_packet(AVFormatContext * s,AVPacket * pkt)375 static int ape_read_packet(AVFormatContext * s, AVPacket * pkt)
376 {
377 int ret;
378 int nblocks;
379 APEContext *ape = s->priv_data;
380 uint32_t extra_size = 8;
381 int64_t ret64;
382
383 if (avio_feof(s->pb))
384 return AVERROR_EOF;
385 if (ape->currentframe >= ape->totalframes)
386 return AVERROR_EOF;
387
388 ret64 = avio_seek(s->pb, ape->frames[ape->currentframe].pos, SEEK_SET);
389 if (ret64 < 0)
390 return ret64;
391
392 /* Calculate how many blocks there are in this frame */
393 if (ape->currentframe == (ape->totalframes - 1))
394 nblocks = ape->finalframeblocks;
395 else
396 nblocks = ape->blocksperframe;
397
398 if (ape->frames[ape->currentframe].size <= 0 ||
399 ape->frames[ape->currentframe].size > INT_MAX - extra_size) {
400 av_log(s, AV_LOG_ERROR, "invalid packet size: %d\n",
401 ape->frames[ape->currentframe].size);
402 ape->currentframe++;
403 return AVERROR(EIO);
404 }
405
406 ret = av_new_packet(pkt, ape->frames[ape->currentframe].size + extra_size);
407 if (ret < 0)
408 return ret;
409
410 AV_WL32(pkt->data , nblocks);
411 AV_WL32(pkt->data + 4, ape->frames[ape->currentframe].skip);
412 ret = avio_read(s->pb, pkt->data + extra_size, ape->frames[ape->currentframe].size);
413 if (ret < 0) {
414 return ret;
415 }
416
417 pkt->pts = ape->frames[ape->currentframe].pts;
418 pkt->stream_index = 0;
419
420 /* note: we need to modify the packet size here to handle the last
421 packet */
422 pkt->size = ret + extra_size;
423
424 ape->currentframe++;
425
426 return 0;
427 }
428
ape_read_close(AVFormatContext * s)429 static int ape_read_close(AVFormatContext * s)
430 {
431 APEContext *ape = s->priv_data;
432
433 av_freep(&ape->frames);
434 return 0;
435 }
436
ape_read_seek(AVFormatContext * s,int stream_index,int64_t timestamp,int flags)437 static int ape_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
438 {
439 AVStream *st = s->streams[stream_index];
440 APEContext *ape = s->priv_data;
441 int index = av_index_search_timestamp(st, timestamp, flags);
442 int64_t ret;
443
444 if (index < 0)
445 return -1;
446
447 if ((ret = avio_seek(s->pb, st->index_entries[index].pos, SEEK_SET)) < 0)
448 return ret;
449 ape->currentframe = index;
450 return 0;
451 }
452
453 AVInputFormat ff_ape_demuxer = {
454 .name = "ape",
455 .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
456 .priv_data_size = sizeof(APEContext),
457 .read_probe = ape_probe,
458 .read_header = ape_read_header,
459 .read_packet = ape_read_packet,
460 .read_close = ape_read_close,
461 .read_seek = ape_read_seek,
462 .extensions = "ape,apl,mac",
463 };
464