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
25 #include "libavutil/intreadwrite.h"
28 #define ENABLE_DEBUG 0
30 /* The earliest and latest file formats supported by this library */
31 #define APE_MIN_VERSION 3950
32 #define APE_MAX_VERSION 3990
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)
41 #define MAC_SUBFRAME_SIZE 4608
43 #define APE_EXTRADATA_SIZE 6
46 #define APE_TAG_VERSION 2000
47 #define APE_TAG_FOOTER_BYTES 32
48 #define APE_TAG_FLAG_CONTAINS_HEADER (1 << 31)
49 #define APE_TAG_FLAG_IS_HEADER (1 << 29)
63 uint32_t totalsamples;
67 /* Info from Descriptor Block */
71 uint32_t descriptorlength;
72 uint32_t headerlength;
73 uint32_t seektablelength;
74 uint32_t wavheaderlength;
75 uint32_t audiodatalength;
76 uint32_t audiodatalength_high;
77 uint32_t wavtaillength;
80 /* Info from Header Block */
81 uint16_t compressiontype;
83 uint32_t blocksperframe;
84 uint32_t finalframeblocks;
94 static void ape_tag_read_field(AVFormatContext *s)
96 ByteIOContext *pb = s->pb;
97 uint8_t key[1024], value[1024];
101 size = get_le32(pb); /* field size */
102 url_fskip(pb, 4); /* skip field flags */
104 for (i=0; pb->buf_ptr[i]!='0' && pb->buf_ptr[i]>=0x20 && pb->buf_ptr[i]<=0x7E; i++);
106 l = FFMIN(i, sizeof(key) -1);
107 get_buffer(pb, key, l);
109 url_fskip(pb, 1 + i-l);
110 l = FFMIN(size, sizeof(value)-1);
111 get_buffer(pb, value, l);
113 url_fskip(pb, size-l);
114 av_metadata_set(&s->metadata, key, value);
117 static void ape_parse_tag(AVFormatContext *s)
119 ByteIOContext *pb = s->pb;
120 int file_size = url_fsize(pb);
121 uint32_t val, fields, tag_bytes;
125 if (file_size < APE_TAG_FOOTER_BYTES)
128 url_fseek(pb, file_size - APE_TAG_FOOTER_BYTES, SEEK_SET);
130 get_buffer(pb, buf, 8); /* APETAGEX */
131 if (strncmp(buf, "APETAGEX", 8)) {
135 val = get_le32(pb); /* APE tag version */
136 if (val > APE_TAG_VERSION) {
137 av_log(s, AV_LOG_ERROR, "Unsupported tag version. (>=%d)\n", APE_TAG_VERSION);
141 tag_bytes = get_le32(pb); /* tag size */
142 if (tag_bytes - APE_TAG_FOOTER_BYTES > (1024 * 1024 * 16)) {
143 av_log(s, AV_LOG_ERROR, "Tag size is way too big\n");
147 fields = get_le32(pb); /* number of fields */
148 if (fields > 65536) {
149 av_log(s, AV_LOG_ERROR, "Too many tag fields (%d)\n", fields);
153 val = get_le32(pb); /* flags */
154 if (val & APE_TAG_FLAG_IS_HEADER) {
155 av_log(s, AV_LOG_ERROR, "APE Tag is a header\n");
159 if (val & APE_TAG_FLAG_CONTAINS_HEADER)
160 tag_bytes += 2*APE_TAG_FOOTER_BYTES;
162 url_fseek(pb, file_size - tag_bytes, SEEK_SET);
164 for (i=0; i<fields; i++)
165 ape_tag_read_field(s);
168 av_log(s, AV_LOG_DEBUG, "\nAPE Tags:\n\n");
169 av_log(s, AV_LOG_DEBUG, "title = %s\n", s->title);
170 av_log(s, AV_LOG_DEBUG, "author = %s\n", s->author);
171 av_log(s, AV_LOG_DEBUG, "copyright = %s\n", s->copyright);
172 av_log(s, AV_LOG_DEBUG, "comment = %s\n", s->comment);
173 av_log(s, AV_LOG_DEBUG, "album = %s\n", s->album);
174 av_log(s, AV_LOG_DEBUG, "year = %d\n", s->year);
175 av_log(s, AV_LOG_DEBUG, "track = %d\n", s->track);
176 av_log(s, AV_LOG_DEBUG, "genre = %s\n", s->genre);
180 static int ape_probe(AVProbeData * p)
182 if (p->buf[0] == 'M' && p->buf[1] == 'A' && p->buf[2] == 'C' && p->buf[3] == ' ')
183 return AVPROBE_SCORE_MAX;
188 static void ape_dumpinfo(AVFormatContext * s, APEContext * ape_ctx)
193 av_log(s, AV_LOG_DEBUG, "Descriptor Block:\n\n");
194 av_log(s, 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]);
195 av_log(s, AV_LOG_DEBUG, "fileversion = %d\n", ape_ctx->fileversion);
196 av_log(s, AV_LOG_DEBUG, "descriptorlength = %d\n", ape_ctx->descriptorlength);
197 av_log(s, AV_LOG_DEBUG, "headerlength = %d\n", ape_ctx->headerlength);
198 av_log(s, AV_LOG_DEBUG, "seektablelength = %d\n", ape_ctx->seektablelength);
199 av_log(s, AV_LOG_DEBUG, "wavheaderlength = %d\n", ape_ctx->wavheaderlength);
200 av_log(s, AV_LOG_DEBUG, "audiodatalength = %d\n", ape_ctx->audiodatalength);
201 av_log(s, AV_LOG_DEBUG, "audiodatalength_high = %d\n", ape_ctx->audiodatalength_high);
202 av_log(s, AV_LOG_DEBUG, "wavtaillength = %d\n", ape_ctx->wavtaillength);
203 av_log(s, AV_LOG_DEBUG, "md5 = ");
204 for (i = 0; i < 16; i++)
205 av_log(s, AV_LOG_DEBUG, "%02x", ape_ctx->md5[i]);
206 av_log(s, AV_LOG_DEBUG, "\n");
208 av_log(s, AV_LOG_DEBUG, "\nHeader Block:\n\n");
210 av_log(s, AV_LOG_DEBUG, "compressiontype = %d\n", ape_ctx->compressiontype);
211 av_log(s, AV_LOG_DEBUG, "formatflags = %d\n", ape_ctx->formatflags);
212 av_log(s, AV_LOG_DEBUG, "blocksperframe = %d\n", ape_ctx->blocksperframe);
213 av_log(s, AV_LOG_DEBUG, "finalframeblocks = %d\n", ape_ctx->finalframeblocks);
214 av_log(s, AV_LOG_DEBUG, "totalframes = %d\n", ape_ctx->totalframes);
215 av_log(s, AV_LOG_DEBUG, "bps = %d\n", ape_ctx->bps);
216 av_log(s, AV_LOG_DEBUG, "channels = %d\n", ape_ctx->channels);
217 av_log(s, AV_LOG_DEBUG, "samplerate = %d\n", ape_ctx->samplerate);
219 av_log(s, AV_LOG_DEBUG, "\nSeektable\n\n");
220 if ((ape_ctx->seektablelength / sizeof(uint32_t)) != ape_ctx->totalframes) {
221 av_log(s, AV_LOG_DEBUG, "No seektable\n");
223 for (i = 0; i < ape_ctx->seektablelength / sizeof(uint32_t); i++) {
224 if (i < ape_ctx->totalframes - 1) {
225 av_log(s, AV_LOG_DEBUG, "%8d %d (%d bytes)\n", i, ape_ctx->seektable[i], ape_ctx->seektable[i + 1] - ape_ctx->seektable[i]);
227 av_log(s, AV_LOG_DEBUG, "%8d %d\n", i, ape_ctx->seektable[i]);
232 av_log(s, AV_LOG_DEBUG, "\nFrames\n\n");
233 for (i = 0; i < ape_ctx->totalframes; i++)
234 av_log(s, 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);
236 av_log(s, AV_LOG_DEBUG, "\nCalculated information:\n\n");
237 av_log(s, AV_LOG_DEBUG, "junklength = %d\n", ape_ctx->junklength);
238 av_log(s, AV_LOG_DEBUG, "firstframe = %d\n", ape_ctx->firstframe);
239 av_log(s, AV_LOG_DEBUG, "totalsamples = %d\n", ape_ctx->totalsamples);
243 static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap)
245 ByteIOContext *pb = s->pb;
246 APEContext *ape = s->priv_data;
253 /* TODO: Skip any leading junk such as id3v2 tags */
257 if (tag != MKTAG('M', 'A', 'C', ' '))
260 ape->fileversion = get_le16(pb);
262 if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) {
263 av_log(s, AV_LOG_ERROR, "Unsupported file version - %d.%02d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10);
267 if (ape->fileversion >= 3980) {
268 ape->padding1 = get_le16(pb);
269 ape->descriptorlength = get_le32(pb);
270 ape->headerlength = get_le32(pb);
271 ape->seektablelength = get_le32(pb);
272 ape->wavheaderlength = get_le32(pb);
273 ape->audiodatalength = get_le32(pb);
274 ape->audiodatalength_high = get_le32(pb);
275 ape->wavtaillength = get_le32(pb);
276 get_buffer(pb, ape->md5, 16);
278 /* Skip any unknown bytes at the end of the descriptor.
279 This is for future compatibility */
280 if (ape->descriptorlength > 52)
281 url_fseek(pb, ape->descriptorlength - 52, SEEK_CUR);
283 /* Read header data */
284 ape->compressiontype = get_le16(pb);
285 ape->formatflags = get_le16(pb);
286 ape->blocksperframe = get_le32(pb);
287 ape->finalframeblocks = get_le32(pb);
288 ape->totalframes = get_le32(pb);
289 ape->bps = get_le16(pb);
290 ape->channels = get_le16(pb);
291 ape->samplerate = get_le32(pb);
293 ape->descriptorlength = 0;
294 ape->headerlength = 32;
296 ape->compressiontype = get_le16(pb);
297 ape->formatflags = get_le16(pb);
298 ape->channels = get_le16(pb);
299 ape->samplerate = get_le32(pb);
300 ape->wavheaderlength = get_le32(pb);
301 ape->wavtaillength = get_le32(pb);
302 ape->totalframes = get_le32(pb);
303 ape->finalframeblocks = get_le32(pb);
305 if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) {
306 url_fseek(pb, 4, SEEK_CUR); /* Skip the peak level */
307 ape->headerlength += 4;
310 if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) {
311 ape->seektablelength = get_le32(pb);
312 ape->headerlength += 4;
313 ape->seektablelength *= sizeof(int32_t);
315 ape->seektablelength = ape->totalframes * sizeof(int32_t);
317 if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT)
319 else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT)
324 if (ape->fileversion >= 3950)
325 ape->blocksperframe = 73728 * 4;
326 else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800 && ape->compressiontype >= 4000))
327 ape->blocksperframe = 73728;
329 ape->blocksperframe = 9216;
331 /* Skip any stored wav header */
332 if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER))
333 url_fskip(pb, ape->wavheaderlength);
336 if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){
337 av_log(s, AV_LOG_ERROR, "Too many frames: %d\n", ape->totalframes);
340 ape->frames = av_malloc(ape->totalframes * sizeof(APEFrame));
342 return AVERROR_NOMEM;
343 ape->firstframe = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength;
344 ape->currentframe = 0;
347 ape->totalsamples = ape->finalframeblocks;
348 if (ape->totalframes > 1)
349 ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1);
351 if (ape->seektablelength > 0) {
352 ape->seektable = av_malloc(ape->seektablelength);
353 for (i = 0; i < ape->seektablelength / sizeof(uint32_t); i++)
354 ape->seektable[i] = get_le32(pb);
357 ape->frames[0].pos = ape->firstframe;
358 ape->frames[0].nblocks = ape->blocksperframe;
359 ape->frames[0].skip = 0;
360 for (i = 1; i < ape->totalframes; i++) {
361 ape->frames[i].pos = ape->seektable[i]; //ape->frames[i-1].pos + ape->blocksperframe;
362 ape->frames[i].nblocks = ape->blocksperframe;
363 ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos;
364 ape->frames[i].skip = (ape->frames[i].pos - ape->frames[0].pos) & 3;
366 ape->frames[ape->totalframes - 1].size = ape->finalframeblocks * 4;
367 ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks;
369 for (i = 0; i < ape->totalframes; i++) {
370 if(ape->frames[i].skip){
371 ape->frames[i].pos -= ape->frames[i].skip;
372 ape->frames[i].size += ape->frames[i].skip;
374 ape->frames[i].size = (ape->frames[i].size + 3) & ~3;
378 ape_dumpinfo(s, ape);
380 /* try to read APE tags */
381 if (!url_is_streamed(pb)) {
383 url_fseek(pb, 0, SEEK_SET);
386 av_log(s, AV_LOG_DEBUG, "Decoding file - v%d.%02d, compression level %d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10, ape->compressiontype);
388 /* now we are ready: build format streams */
389 st = av_new_stream(s, 0);
393 total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks;
395 st->codec->codec_type = CODEC_TYPE_AUDIO;
396 st->codec->codec_id = CODEC_ID_APE;
397 st->codec->codec_tag = MKTAG('A', 'P', 'E', ' ');
398 st->codec->channels = ape->channels;
399 st->codec->sample_rate = ape->samplerate;
400 st->codec->bits_per_coded_sample = ape->bps;
401 st->codec->frame_size = MAC_SUBFRAME_SIZE;
403 st->nb_frames = ape->totalframes;
405 s->duration = (int64_t) total_blocks * AV_TIME_BASE / ape->samplerate;
406 av_set_pts_info(st, 64, MAC_SUBFRAME_SIZE, ape->samplerate);
408 st->codec->extradata = av_malloc(APE_EXTRADATA_SIZE);
409 st->codec->extradata_size = APE_EXTRADATA_SIZE;
410 AV_WL16(st->codec->extradata + 0, ape->fileversion);
411 AV_WL16(st->codec->extradata + 2, ape->compressiontype);
412 AV_WL16(st->codec->extradata + 4, ape->formatflags);
415 for (i = 0; i < ape->totalframes; i++) {
416 ape->frames[i].pts = pts;
417 av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME);
418 pts += ape->blocksperframe / MAC_SUBFRAME_SIZE;
424 static int ape_read_packet(AVFormatContext * s, AVPacket * pkt)
428 APEContext *ape = s->priv_data;
429 uint32_t extra_size = 8;
433 if (ape->currentframe > ape->totalframes)
436 url_fseek (s->pb, ape->frames[ape->currentframe].pos, SEEK_SET);
438 /* Calculate how many blocks there are in this frame */
439 if (ape->currentframe == (ape->totalframes - 1))
440 nblocks = ape->finalframeblocks;
442 nblocks = ape->blocksperframe;
444 if (av_new_packet(pkt, ape->frames[ape->currentframe].size + extra_size) < 0)
445 return AVERROR_NOMEM;
447 AV_WL32(pkt->data , nblocks);
448 AV_WL32(pkt->data + 4, ape->frames[ape->currentframe].skip);
449 ret = get_buffer(s->pb, pkt->data + extra_size, ape->frames[ape->currentframe].size);
451 pkt->pts = ape->frames[ape->currentframe].pts;
452 pkt->stream_index = 0;
454 /* note: we need to modify the packet size here to handle the last
456 pkt->size = ret + extra_size;
463 static int ape_read_close(AVFormatContext * s)
465 APEContext *ape = s->priv_data;
467 av_freep(&ape->frames);
468 av_freep(&ape->seektable);
472 static int ape_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
474 AVStream *st = s->streams[stream_index];
475 APEContext *ape = s->priv_data;
476 int index = av_index_search_timestamp(st, timestamp, flags);
481 ape->currentframe = index;
485 AVInputFormat ape_demuxer = {
487 NULL_IF_CONFIG_SMALL("Monkey's Audio"),
494 .extensions = "ape,apl,mac"