2 * Monkey's Audio APE demuxer
3 * Copyright (c) 2007 Benjamin Zores <ben@geexbox.org>
4 * based upon libdemac from Dave Chapman.
6 * This file is part of FFmpeg.
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.
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.
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
27 /* The earliest and latest file formats supported by this library */
28 #define APE_MIN_VERSION 3970
29 #define APE_MAX_VERSION 3990
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)
38 #define MAC_SUBFRAME_SIZE 4608
40 #define APE_EXTRADATA_SIZE 6
43 #define APE_TAG_VERSION 2000
44 #define APE_TAG_FOOTER_BYTES 32
45 #define APE_TAG_FLAG_CONTAINS_HEADER (1 << 31)
46 #define APE_TAG_FLAG_IS_HEADER (1 << 29)
48 #define TAG(name, field) {name, offsetof(AVFormatContext, field), sizeof(((AVFormatContext *)0)->field)}
55 TAG("Title" , title ),
56 TAG("Artist" , author ),
57 TAG("Copyright", copyright),
58 TAG("Comment" , comment ),
59 TAG("Album" , album ),
61 TAG("Track" , track ),
62 TAG("Genre" , genre ),
78 uint32_t totalsamples;
82 /* Info from Descriptor Block */
86 uint32_t descriptorlength;
87 uint32_t headerlength;
88 uint32_t seektablelength;
89 uint32_t wavheaderlength;
90 uint32_t audiodatalength;
91 uint32_t audiodatalength_high;
92 uint32_t wavtaillength;
95 /* Info from Header Block */
96 uint16_t compressiontype;
98 uint32_t blocksperframe;
99 uint32_t finalframeblocks;
100 uint32_t totalframes;
109 static void ape_tag_read_field(AVFormatContext *s)
111 ByteIOContext *pb = &s->pb;
116 memset(buf, 0, 1024);
117 size = get_le32(pb); /* field size */
118 url_fskip(pb, 4); /* skip field flags */
120 for (i=0; pb->buf_ptr[i]!='0' && pb->buf_ptr[i]>=0x20 && pb->buf_ptr[i]<=0x7E; i++);
122 get_buffer(pb, buf, FFMIN(i, 1024));
125 for (i=0; tags[i].name; i++)
126 if (!strcmp (buf, tags[i].name)) {
127 if (tags[i].size == sizeof(int)) {
129 get_buffer(pb, tmp, FFMIN(sizeof(tmp), size));
130 *(int *)(((char *)s)+tags[i].offset) = atoi(tmp);
132 get_buffer(pb, ((char *)s) + tags[i].offset,
133 FFMIN(tags[i].size, size));
142 static void ape_parse_tag(AVFormatContext *s)
144 ByteIOContext *pb = &s->pb;
145 int file_size = url_fsize(pb);
146 uint32_t val, fields, tag_bytes;
150 if (file_size < APE_TAG_FOOTER_BYTES)
153 url_fseek(pb, file_size - APE_TAG_FOOTER_BYTES, SEEK_SET);
155 get_buffer(pb, buf, 8); /* APETAGEX */
156 if (strncmp(buf, "APETAGEX", 8)) {
157 av_log(NULL, AV_LOG_ERROR, "Invalid APE Tags\n");
161 val = get_le32(pb); /* APE tag version */
162 if (val > APE_TAG_VERSION) {
163 av_log(NULL, AV_LOG_ERROR, "Unsupported tag version. (>=%d)\n", APE_TAG_VERSION);
167 tag_bytes = get_le32(pb); /* tag size */
168 if (tag_bytes - APE_TAG_FOOTER_BYTES > (1024 * 1024 * 16)) {
169 av_log(NULL, AV_LOG_ERROR, "Tag size is way too big\n");
173 fields = get_le32(pb); /* number of fields */
174 if (fields > 65536) {
175 av_log(NULL, AV_LOG_ERROR, "Too many tag fields (%d)\n", fields);
179 val = get_le32(pb); /* flags */
180 if (val & APE_TAG_FLAG_IS_HEADER) {
181 av_log(NULL, AV_LOG_ERROR, "APE Tag is a header\n");
185 if (val & APE_TAG_FLAG_CONTAINS_HEADER)
186 tag_bytes += 2*APE_TAG_FOOTER_BYTES;
188 url_fseek(pb, file_size - tag_bytes, SEEK_SET);
190 for (i=0; i<fields; i++)
191 ape_tag_read_field(s);
193 av_log(NULL, AV_LOG_DEBUG, "\nAPE Tags:\n\n");
194 av_log(NULL, AV_LOG_DEBUG, "title = %s\n", s->title);
195 av_log(NULL, AV_LOG_DEBUG, "author = %s\n", s->author);
196 av_log(NULL, AV_LOG_DEBUG, "copyright = %s\n", s->copyright);
197 av_log(NULL, AV_LOG_DEBUG, "comment = %s\n", s->comment);
198 av_log(NULL, AV_LOG_DEBUG, "album = %s\n", s->album);
199 av_log(NULL, AV_LOG_DEBUG, "year = %d\n", s->year);
200 av_log(NULL, AV_LOG_DEBUG, "track = %d\n", s->track);
201 av_log(NULL, AV_LOG_DEBUG, "genre = %s\n", s->genre);
204 static int ape_probe(AVProbeData * p)
206 if (p->buf[0] == 'M' && p->buf[1] == 'A' && p->buf[2] == 'C' && p->buf[3] == ' ')
207 return AVPROBE_SCORE_MAX;
212 static void ape_dumpinfo(APEContext * ape_ctx)
216 av_log(NULL, AV_LOG_DEBUG, "Descriptor Block:\n\n");
217 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]);
218 av_log(NULL, AV_LOG_DEBUG, "fileversion = %d\n", ape_ctx->fileversion);
219 av_log(NULL, AV_LOG_DEBUG, "descriptorlength = %d\n", ape_ctx->descriptorlength);
220 av_log(NULL, AV_LOG_DEBUG, "headerlength = %d\n", ape_ctx->headerlength);
221 av_log(NULL, AV_LOG_DEBUG, "seektablelength = %d\n", ape_ctx->seektablelength);
222 av_log(NULL, AV_LOG_DEBUG, "wavheaderlength = %d\n", ape_ctx->wavheaderlength);
223 av_log(NULL, AV_LOG_DEBUG, "audiodatalength = %d\n", ape_ctx->audiodatalength);
224 av_log(NULL, AV_LOG_DEBUG, "audiodatalength_high = %d\n", ape_ctx->audiodatalength_high);
225 av_log(NULL, AV_LOG_DEBUG, "wavtaillength = %d\n", ape_ctx->wavtaillength);
226 av_log(NULL, AV_LOG_DEBUG, "md5 = ");
227 for (i = 0; i < 16; i++)
228 av_log(NULL, AV_LOG_DEBUG, "%02x", ape_ctx->md5[i]);
229 av_log(NULL, AV_LOG_DEBUG, "\n");
231 av_log(NULL, AV_LOG_DEBUG, "\nHeader Block:\n\n");
233 av_log(NULL, AV_LOG_DEBUG, "compressiontype = %d\n", ape_ctx->compressiontype);
234 av_log(NULL, AV_LOG_DEBUG, "formatflags = %d\n", ape_ctx->formatflags);
235 av_log(NULL, AV_LOG_DEBUG, "blocksperframe = %d\n", ape_ctx->blocksperframe);
236 av_log(NULL, AV_LOG_DEBUG, "finalframeblocks = %d\n", ape_ctx->finalframeblocks);
237 av_log(NULL, AV_LOG_DEBUG, "totalframes = %d\n", ape_ctx->totalframes);
238 av_log(NULL, AV_LOG_DEBUG, "bps = %d\n", ape_ctx->bps);
239 av_log(NULL, AV_LOG_DEBUG, "channels = %d\n", ape_ctx->channels);
240 av_log(NULL, AV_LOG_DEBUG, "samplerate = %d\n", ape_ctx->samplerate);
242 av_log(NULL, AV_LOG_DEBUG, "\nSeektable\n\n");
243 if ((ape_ctx->seektablelength / sizeof(uint32_t)) != ape_ctx->totalframes) {
244 av_log(NULL, AV_LOG_DEBUG, "No seektable\n");
246 for (i = 0; i < ape_ctx->seektablelength / sizeof(uint32_t); i++) {
247 if (i < ape_ctx->totalframes - 1) {
248 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]);
250 av_log(NULL, AV_LOG_DEBUG, "%8d %d\n", i, ape_ctx->seektable[i]);
255 av_log(NULL, AV_LOG_DEBUG, "\nFrames\n\n");
256 for (i = 0; i < ape_ctx->totalframes; i++)
257 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);
259 av_log(NULL, AV_LOG_DEBUG, "\nCalculated information:\n\n");
260 av_log(NULL, AV_LOG_DEBUG, "junklength = %d\n", ape_ctx->junklength);
261 av_log(NULL, AV_LOG_DEBUG, "firstframe = %d\n", ape_ctx->firstframe);
262 av_log(NULL, AV_LOG_DEBUG, "totalsamples = %d\n", ape_ctx->totalsamples);
265 static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap)
267 ByteIOContext *pb = &s->pb;
268 APEContext *ape = s->priv_data;
275 /* TODO: Skip any leading junk such as id3v2 tags */
279 if (tag != MKTAG('M', 'A', 'C', ' '))
282 ape->fileversion = get_le16(pb);
284 if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) {
285 av_log(s, AV_LOG_ERROR, "Unsupported file version - %d.%02d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10);
289 if (ape->fileversion >= 3980) {
290 ape->padding1 = get_le16(pb);
291 ape->descriptorlength = get_le32(pb);
292 ape->headerlength = get_le32(pb);
293 ape->seektablelength = get_le32(pb);
294 ape->wavheaderlength = get_le32(pb);
295 ape->audiodatalength = get_le32(pb);
296 ape->audiodatalength_high = get_le32(pb);
297 ape->wavtaillength = get_le32(pb);
298 get_buffer(pb, ape->md5, 16);
300 /* Skip any unknown bytes at the end of the descriptor.
301 This is for future compatibility */
302 if (ape->descriptorlength > 52)
303 url_fseek(pb, ape->descriptorlength - 52, SEEK_CUR);
305 /* Read header data */
306 ape->compressiontype = get_le16(pb);
307 ape->formatflags = get_le16(pb);
308 ape->blocksperframe = get_le32(pb);
309 ape->finalframeblocks = get_le32(pb);
310 ape->totalframes = get_le32(pb);
311 ape->bps = get_le16(pb);
312 ape->channels = get_le16(pb);
313 ape->samplerate = get_le32(pb);
315 ape->descriptorlength = 0;
316 ape->headerlength = 32;
318 ape->compressiontype = get_le16(pb);
319 ape->formatflags = get_le16(pb);
320 ape->channels = get_le16(pb);
321 ape->samplerate = get_le32(pb);
322 ape->wavheaderlength = get_le32(pb);
323 ape->wavtaillength = get_le32(pb);
324 ape->totalframes = get_le32(pb);
325 ape->finalframeblocks = get_le32(pb);
327 if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) {
328 url_fseek(pb, 4, SEEK_CUR); /* Skip the peak level */
329 ape->headerlength += 4;
332 if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) {
333 ape->seektablelength = get_le32(pb);
334 ape->headerlength += 4;
335 ape->seektablelength *= sizeof(int32_t);
337 ape->seektablelength = ape->totalframes * sizeof(int32_t);
339 if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT)
341 else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT)
346 if (ape->fileversion >= 3950)
347 ape->blocksperframe = 73728 * 4;
348 else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800 && ape->compressiontype >= 4000))
349 ape->blocksperframe = 73728;
351 ape->blocksperframe = 9216;
353 /* Skip any stored wav header */
354 if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER))
355 url_fskip(pb, ape->wavheaderlength);
358 if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){
359 av_log(s, AV_LOG_ERROR, "Too many frames: %d\n", ape->totalframes);
362 ape->frames = av_malloc(ape->totalframes * sizeof(APEFrame));
364 return AVERROR_NOMEM;
365 ape->firstframe = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength;
366 ape->currentframe = 0;
369 ape->totalsamples = ape->finalframeblocks;
370 if (ape->totalframes > 1)
371 ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1);
373 if (ape->seektablelength > 0) {
374 ape->seektable = av_malloc(ape->seektablelength);
375 for (i = 0; i < ape->seektablelength / sizeof(uint32_t); i++)
376 ape->seektable[i] = get_le32(pb);
379 ape->frames[0].pos = ape->firstframe;
380 ape->frames[0].nblocks = ape->blocksperframe;
381 ape->frames[0].skip = 0;
382 for (i = 1; i < ape->totalframes; i++) {
383 ape->frames[i].pos = ape->seektable[i]; //ape->frames[i-1].pos + ape->blocksperframe;
384 ape->frames[i].nblocks = ape->blocksperframe;
385 ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos;
386 ape->frames[i].skip = (ape->frames[i].pos - ape->frames[0].pos) & 3;
388 ape->frames[ape->totalframes - 1].size = ape->finalframeblocks * 4;
389 ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks;
391 for (i = 0; i < ape->totalframes; i++) {
392 if(ape->frames[i].skip){
393 ape->frames[i].pos -= ape->frames[i].skip;
394 ape->frames[i].size += ape->frames[i].skip;
396 ape->frames[i].size = (ape->frames[i].size + 3) & ~3;
402 /* try to read APE tags */
403 if (!url_is_streamed(pb)) {
405 url_fseek(pb, 0, SEEK_SET);
408 av_log(s, AV_LOG_DEBUG, "Decoding file - v%d.%02d, compression level %d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10, ape->compressiontype);
410 /* now we are ready: build format streams */
411 st = av_new_stream(s, 0);
415 total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks;
417 st->codec->codec_type = CODEC_TYPE_AUDIO;
418 st->codec->codec_id = CODEC_ID_APE;
419 st->codec->codec_tag = MKTAG('A', 'P', 'E', ' ');
420 st->codec->channels = ape->channels;
421 st->codec->sample_rate = ape->samplerate;
422 st->codec->bits_per_sample = ape->bps;
423 st->codec->frame_size = MAC_SUBFRAME_SIZE;
425 st->nb_frames = ape->totalframes;
427 s->duration = (int64_t) total_blocks * AV_TIME_BASE / ape->samplerate;
428 av_set_pts_info(st, 64, MAC_SUBFRAME_SIZE, ape->samplerate);
430 st->codec->extradata = av_malloc(APE_EXTRADATA_SIZE);
431 st->codec->extradata_size = APE_EXTRADATA_SIZE;
432 AV_WL16(st->codec->extradata + 0, ape->fileversion);
433 AV_WL16(st->codec->extradata + 2, ape->compressiontype);
434 AV_WL16(st->codec->extradata + 4, ape->formatflags);
437 for (i = 0; i < ape->totalframes; i++) {
438 ape->frames[i].pts = pts;
439 av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME);
440 pts += ape->blocksperframe / MAC_SUBFRAME_SIZE;
446 static int ape_read_packet(AVFormatContext * s, AVPacket * pkt)
450 APEContext *ape = s->priv_data;
451 uint32_t extra_size = 8;
453 if (url_feof(&s->pb))
455 if (ape->currentframe > ape->totalframes)
458 url_fseek (&s->pb, ape->frames[ape->currentframe].pos, SEEK_SET);
460 /* Calculate how many blocks there are in this frame */
461 if (ape->currentframe == (ape->totalframes - 1))
462 nblocks = ape->finalframeblocks;
464 nblocks = ape->blocksperframe;
466 if (av_new_packet(pkt, ape->frames[ape->currentframe].size + extra_size) < 0)
467 return AVERROR_NOMEM;
469 AV_WL32(pkt->data , nblocks);
470 AV_WL32(pkt->data + 4, ape->frames[ape->currentframe].skip);
471 ret = get_buffer(&s->pb, pkt->data + extra_size, ape->frames[ape->currentframe].size);
473 pkt->pts = ape->frames[ape->currentframe].pts;
474 pkt->stream_index = 0;
476 /* note: we need to modify the packet size here to handle the last
478 pkt->size = ret + extra_size;
485 static int ape_read_close(AVFormatContext * s)
487 APEContext *ape = s->priv_data;
489 av_freep(&ape->frames);
490 av_freep(&ape->seektable);
494 static int ape_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
496 AVStream *st = s->streams[stream_index];
497 APEContext *ape = s->priv_data;
498 int index = av_index_search_timestamp(st, timestamp, flags);
503 ape->currentframe = index;
507 AVInputFormat ape_demuxer = {
516 .extensions = "ape,apl,mac"