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 28#define ENABLE_DEBUG 0 29 30/* The earliest and latest file formats supported by this library */ 31#define APE_MIN_VERSION 3950 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 MAC_SUBFRAME_SIZE 4608 42 43#define APE_EXTRADATA_SIZE 6 44 45/* APE tags */ 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) 50 51typedef struct { 52 int64_t pos; 53 int nblocks; 54 int size; 55 int skip; 56 int64_t pts; 57} APEFrame; 58 59typedef struct { 60 /* Derived fields */ 61 uint32_t junklength; 62 uint32_t firstframe; 63 uint32_t totalsamples; 64 int currentframe; 65 APEFrame *frames; 66 67 /* Info from Descriptor Block */ 68 char magic[4]; 69 int16_t fileversion; 70 int16_t padding1; 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; 78 uint8_t md5[16]; 79 80 /* Info from Header Block */ 81 uint16_t compressiontype; 82 uint16_t formatflags; 83 uint32_t blocksperframe; 84 uint32_t finalframeblocks; 85 uint32_t totalframes; 86 uint16_t bps; 87 uint16_t channels; 88 uint32_t samplerate; 89 90 /* Seektable */ 91 uint32_t *seektable; 92} APEContext; 93 94static void ape_tag_read_field(AVFormatContext *s) 95{ 96 ByteIOContext *pb = s->pb; 97 uint8_t key[1024], value[1024]; 98 uint32_t size; 99 int i, l; 100 101 size = get_le32(pb); /* field size */ 102 url_fskip(pb, 4); /* skip field flags */ 103 104 for (i=0; pb->buf_ptr[i]!='0' && pb->buf_ptr[i]>=0x20 && pb->buf_ptr[i]<=0x7E; i++); 105 106 l = FFMIN(i, sizeof(key) -1); 107 get_buffer(pb, key, l); 108 key[l] = 0; 109 url_fskip(pb, 1 + i-l); 110 l = FFMIN(size, sizeof(value)-1); 111 get_buffer(pb, value, l); 112 value[l] = 0; 113 url_fskip(pb, size-l); 114 if (l < size) 115 av_log(s, AV_LOG_WARNING, "Too long '%s' tag was truncated.\n", key); 116 av_metadata_set(&s->metadata, key, value); 117} 118 119static void ape_parse_tag(AVFormatContext *s) 120{ 121 ByteIOContext *pb = s->pb; 122 int file_size = url_fsize(pb); 123 uint32_t val, fields, tag_bytes; 124 uint8_t buf[8]; 125 int i; 126 127 if (file_size < APE_TAG_FOOTER_BYTES) 128 return; 129 130 url_fseek(pb, file_size - APE_TAG_FOOTER_BYTES, SEEK_SET); 131 132 get_buffer(pb, buf, 8); /* APETAGEX */ 133 if (strncmp(buf, "APETAGEX", 8)) { 134 return; 135 } 136 137 val = get_le32(pb); /* APE tag version */ 138 if (val > APE_TAG_VERSION) { 139 av_log(s, AV_LOG_ERROR, "Unsupported tag version. (>=%d)\n", APE_TAG_VERSION); 140 return; 141 } 142 143 tag_bytes = get_le32(pb); /* tag size */ 144 if (tag_bytes - APE_TAG_FOOTER_BYTES > (1024 * 1024 * 16)) { 145 av_log(s, AV_LOG_ERROR, "Tag size is way too big\n"); 146 return; 147 } 148 149 fields = get_le32(pb); /* number of fields */ 150 if (fields > 65536) { 151 av_log(s, AV_LOG_ERROR, "Too many tag fields (%d)\n", fields); 152 return; 153 } 154 155 val = get_le32(pb); /* flags */ 156 if (val & APE_TAG_FLAG_IS_HEADER) { 157 av_log(s, AV_LOG_ERROR, "APE Tag is a header\n"); 158 return; 159 } 160 161 if (val & APE_TAG_FLAG_CONTAINS_HEADER) 162 tag_bytes += 2*APE_TAG_FOOTER_BYTES; 163 164 url_fseek(pb, file_size - tag_bytes, SEEK_SET); 165 166 for (i=0; i<fields; i++) 167 ape_tag_read_field(s); 168 169#if ENABLE_DEBUG 170 av_log(s, AV_LOG_DEBUG, "\nAPE Tags:\n\n"); 171 av_log(s, AV_LOG_DEBUG, "title = %s\n", s->title); 172 av_log(s, AV_LOG_DEBUG, "author = %s\n", s->author); 173 av_log(s, AV_LOG_DEBUG, "copyright = %s\n", s->copyright); 174 av_log(s, AV_LOG_DEBUG, "comment = %s\n", s->comment); 175 av_log(s, AV_LOG_DEBUG, "album = %s\n", s->album); 176 av_log(s, AV_LOG_DEBUG, "year = %d\n", s->year); 177 av_log(s, AV_LOG_DEBUG, "track = %d\n", s->track); 178 av_log(s, AV_LOG_DEBUG, "genre = %s\n", s->genre); 179#endif 180} 181 182static int ape_probe(AVProbeData * p) 183{ 184 if (p->buf[0] == 'M' && p->buf[1] == 'A' && p->buf[2] == 'C' && p->buf[3] == ' ') 185 return AVPROBE_SCORE_MAX; 186 187 return 0; 188} 189 190static void ape_dumpinfo(AVFormatContext * s, APEContext * ape_ctx) 191{ 192#if ENABLE_DEBUG 193 int i; 194 195 av_log(s, AV_LOG_DEBUG, "Descriptor Block:\n\n"); 196 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]); 197 av_log(s, AV_LOG_DEBUG, "fileversion = %d\n", ape_ctx->fileversion); 198 av_log(s, AV_LOG_DEBUG, "descriptorlength = %d\n", ape_ctx->descriptorlength); 199 av_log(s, AV_LOG_DEBUG, "headerlength = %d\n", ape_ctx->headerlength); 200 av_log(s, AV_LOG_DEBUG, "seektablelength = %d\n", ape_ctx->seektablelength); 201 av_log(s, AV_LOG_DEBUG, "wavheaderlength = %d\n", ape_ctx->wavheaderlength); 202 av_log(s, AV_LOG_DEBUG, "audiodatalength = %d\n", ape_ctx->audiodatalength); 203 av_log(s, AV_LOG_DEBUG, "audiodatalength_high = %d\n", ape_ctx->audiodatalength_high); 204 av_log(s, AV_LOG_DEBUG, "wavtaillength = %d\n", ape_ctx->wavtaillength); 205 av_log(s, AV_LOG_DEBUG, "md5 = "); 206 for (i = 0; i < 16; i++) 207 av_log(s, AV_LOG_DEBUG, "%02x", ape_ctx->md5[i]); 208 av_log(s, AV_LOG_DEBUG, "\n"); 209 210 av_log(s, AV_LOG_DEBUG, "\nHeader Block:\n\n"); 211 212 av_log(s, AV_LOG_DEBUG, "compressiontype = %d\n", ape_ctx->compressiontype); 213 av_log(s, AV_LOG_DEBUG, "formatflags = %d\n", ape_ctx->formatflags); 214 av_log(s, AV_LOG_DEBUG, "blocksperframe = %d\n", ape_ctx->blocksperframe); 215 av_log(s, AV_LOG_DEBUG, "finalframeblocks = %d\n", ape_ctx->finalframeblocks); 216 av_log(s, AV_LOG_DEBUG, "totalframes = %d\n", ape_ctx->totalframes); 217 av_log(s, AV_LOG_DEBUG, "bps = %d\n", ape_ctx->bps); 218 av_log(s, AV_LOG_DEBUG, "channels = %d\n", ape_ctx->channels); 219 av_log(s, AV_LOG_DEBUG, "samplerate = %d\n", ape_ctx->samplerate); 220 221 av_log(s, AV_LOG_DEBUG, "\nSeektable\n\n"); 222 if ((ape_ctx->seektablelength / sizeof(uint32_t)) != ape_ctx->totalframes) { 223 av_log(s, AV_LOG_DEBUG, "No seektable\n"); 224 } else { 225 for (i = 0; i < ape_ctx->seektablelength / sizeof(uint32_t); i++) { 226 if (i < ape_ctx->totalframes - 1) { 227 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]); 228 } else { 229 av_log(s, AV_LOG_DEBUG, "%8d %d\n", i, ape_ctx->seektable[i]); 230 } 231 } 232 } 233 234 av_log(s, AV_LOG_DEBUG, "\nFrames\n\n"); 235 for (i = 0; i < ape_ctx->totalframes; i++) 236 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); 237 238 av_log(s, AV_LOG_DEBUG, "\nCalculated information:\n\n"); 239 av_log(s, AV_LOG_DEBUG, "junklength = %d\n", ape_ctx->junklength); 240 av_log(s, AV_LOG_DEBUG, "firstframe = %d\n", ape_ctx->firstframe); 241 av_log(s, AV_LOG_DEBUG, "totalsamples = %d\n", ape_ctx->totalsamples); 242#endif 243} 244 245static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap) 246{ 247 ByteIOContext *pb = s->pb; 248 APEContext *ape = s->priv_data; 249 AVStream *st; 250 uint32_t tag; 251 int i; 252 int total_blocks; 253 int64_t pts; 254 255 /* TODO: Skip any leading junk such as id3v2 tags */ 256 ape->junklength = 0; 257 258 tag = get_le32(pb); 259 if (tag != MKTAG('M', 'A', 'C', ' ')) 260 return -1; 261 262 ape->fileversion = get_le16(pb); 263 264 if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) { 265 av_log(s, AV_LOG_ERROR, "Unsupported file version - %d.%02d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10); 266 return -1; 267 } 268 269 if (ape->fileversion >= 3980) { 270 ape->padding1 = get_le16(pb); 271 ape->descriptorlength = get_le32(pb); 272 ape->headerlength = get_le32(pb); 273 ape->seektablelength = get_le32(pb); 274 ape->wavheaderlength = get_le32(pb); 275 ape->audiodatalength = get_le32(pb); 276 ape->audiodatalength_high = get_le32(pb); 277 ape->wavtaillength = get_le32(pb); 278 get_buffer(pb, ape->md5, 16); 279 280 /* Skip any unknown bytes at the end of the descriptor. 281 This is for future compatibility */ 282 if (ape->descriptorlength > 52) 283 url_fseek(pb, ape->descriptorlength - 52, SEEK_CUR); 284 285 /* Read header data */ 286 ape->compressiontype = get_le16(pb); 287 ape->formatflags = get_le16(pb); 288 ape->blocksperframe = get_le32(pb); 289 ape->finalframeblocks = get_le32(pb); 290 ape->totalframes = get_le32(pb); 291 ape->bps = get_le16(pb); 292 ape->channels = get_le16(pb); 293 ape->samplerate = get_le32(pb); 294 } else { 295 ape->descriptorlength = 0; 296 ape->headerlength = 32; 297 298 ape->compressiontype = get_le16(pb); 299 ape->formatflags = get_le16(pb); 300 ape->channels = get_le16(pb); 301 ape->samplerate = get_le32(pb); 302 ape->wavheaderlength = get_le32(pb); 303 ape->wavtaillength = get_le32(pb); 304 ape->totalframes = get_le32(pb); 305 ape->finalframeblocks = get_le32(pb); 306 307 if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) { 308 url_fseek(pb, 4, SEEK_CUR); /* Skip the peak level */ 309 ape->headerlength += 4; 310 } 311 312 if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) { 313 ape->seektablelength = get_le32(pb); 314 ape->headerlength += 4; 315 ape->seektablelength *= sizeof(int32_t); 316 } else 317 ape->seektablelength = ape->totalframes * sizeof(int32_t); 318 319 if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT) 320 ape->bps = 8; 321 else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT) 322 ape->bps = 24; 323 else 324 ape->bps = 16; 325 326 if (ape->fileversion >= 3950) 327 ape->blocksperframe = 73728 * 4; 328 else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800 && ape->compressiontype >= 4000)) 329 ape->blocksperframe = 73728; 330 else 331 ape->blocksperframe = 9216; 332 333 /* Skip any stored wav header */ 334 if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER)) 335 url_fskip(pb, ape->wavheaderlength); 336 } 337 338 if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){ 339 av_log(s, AV_LOG_ERROR, "Too many frames: %d\n", ape->totalframes); 340 return -1; 341 } 342 ape->frames = av_malloc(ape->totalframes * sizeof(APEFrame)); 343 if(!ape->frames) 344 return AVERROR_NOMEM; 345 ape->firstframe = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength; 346 ape->currentframe = 0; 347 348 349 ape->totalsamples = ape->finalframeblocks; 350 if (ape->totalframes > 1) 351 ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1); 352 353 if (ape->seektablelength > 0) { 354 ape->seektable = av_malloc(ape->seektablelength); 355 for (i = 0; i < ape->seektablelength / sizeof(uint32_t); i++) 356 ape->seektable[i] = get_le32(pb); 357 } 358 359 ape->frames[0].pos = ape->firstframe; 360 ape->frames[0].nblocks = ape->blocksperframe; 361 ape->frames[0].skip = 0; 362 for (i = 1; i < ape->totalframes; i++) { 363 ape->frames[i].pos = ape->seektable[i]; //ape->frames[i-1].pos + ape->blocksperframe; 364 ape->frames[i].nblocks = ape->blocksperframe; 365 ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos; 366 ape->frames[i].skip = (ape->frames[i].pos - ape->frames[0].pos) & 3; 367 } 368 ape->frames[ape->totalframes - 1].size = ape->finalframeblocks * 4; 369 ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks; 370 371 for (i = 0; i < ape->totalframes; i++) { 372 if(ape->frames[i].skip){ 373 ape->frames[i].pos -= ape->frames[i].skip; 374 ape->frames[i].size += ape->frames[i].skip; 375 } 376 ape->frames[i].size = (ape->frames[i].size + 3) & ~3; 377 } 378 379 380 ape_dumpinfo(s, ape); 381 382 /* try to read APE tags */ 383 if (!url_is_streamed(pb)) { 384 ape_parse_tag(s); 385 url_fseek(pb, 0, SEEK_SET); 386 } 387 388 av_log(s, AV_LOG_DEBUG, "Decoding file - v%d.%02d, compression level %d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10, ape->compressiontype); 389 390 /* now we are ready: build format streams */ 391 st = av_new_stream(s, 0); 392 if (!st) 393 return -1; 394 395 total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks; 396 397 st->codec->codec_type = CODEC_TYPE_AUDIO; 398 st->codec->codec_id = CODEC_ID_APE; 399 st->codec->codec_tag = MKTAG('A', 'P', 'E', ' '); 400 st->codec->channels = ape->channels; 401 st->codec->sample_rate = ape->samplerate; 402 st->codec->bits_per_coded_sample = ape->bps; 403 st->codec->frame_size = MAC_SUBFRAME_SIZE; 404 405 st->nb_frames = ape->totalframes; 406 s->start_time = 0; 407 s->duration = (int64_t) total_blocks * AV_TIME_BASE / ape->samplerate; 408 av_set_pts_info(st, 64, MAC_SUBFRAME_SIZE, ape->samplerate); 409 410 st->codec->extradata = av_malloc(APE_EXTRADATA_SIZE); 411 st->codec->extradata_size = APE_EXTRADATA_SIZE; 412 AV_WL16(st->codec->extradata + 0, ape->fileversion); 413 AV_WL16(st->codec->extradata + 2, ape->compressiontype); 414 AV_WL16(st->codec->extradata + 4, ape->formatflags); 415 416 pts = 0; 417 for (i = 0; i < ape->totalframes; i++) { 418 ape->frames[i].pts = pts; 419 av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME); 420 pts += ape->blocksperframe / MAC_SUBFRAME_SIZE; 421 } 422 423 return 0; 424} 425 426static int ape_read_packet(AVFormatContext * s, AVPacket * pkt) 427{ 428 int ret; 429 int nblocks; 430 APEContext *ape = s->priv_data; 431 uint32_t extra_size = 8; 432 433 if (url_feof(s->pb)) 434 return AVERROR_IO; 435 if (ape->currentframe > ape->totalframes) 436 return AVERROR_IO; 437 438 url_fseek (s->pb, ape->frames[ape->currentframe].pos, SEEK_SET); 439 440 /* Calculate how many blocks there are in this frame */ 441 if (ape->currentframe == (ape->totalframes - 1)) 442 nblocks = ape->finalframeblocks; 443 else 444 nblocks = ape->blocksperframe; 445 446 if (av_new_packet(pkt, ape->frames[ape->currentframe].size + extra_size) < 0) 447 return AVERROR_NOMEM; 448 449 AV_WL32(pkt->data , nblocks); 450 AV_WL32(pkt->data + 4, ape->frames[ape->currentframe].skip); 451 ret = get_buffer(s->pb, pkt->data + extra_size, ape->frames[ape->currentframe].size); 452 453 pkt->pts = ape->frames[ape->currentframe].pts; 454 pkt->stream_index = 0; 455 456 /* note: we need to modify the packet size here to handle the last 457 packet */ 458 pkt->size = ret + extra_size; 459 460 ape->currentframe++; 461 462 return 0; 463} 464 465static int ape_read_close(AVFormatContext * s) 466{ 467 APEContext *ape = s->priv_data; 468 469 av_freep(&ape->frames); 470 av_freep(&ape->seektable); 471 return 0; 472} 473 474static int ape_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) 475{ 476 AVStream *st = s->streams[stream_index]; 477 APEContext *ape = s->priv_data; 478 int index = av_index_search_timestamp(st, timestamp, flags); 479 480 if (index < 0) 481 return -1; 482 483 ape->currentframe = index; 484 return 0; 485} 486 487AVInputFormat ape_demuxer = { 488 "ape", 489 NULL_IF_CONFIG_SMALL("Monkey's Audio"), 490 sizeof(APEContext), 491 ape_probe, 492 ape_read_header, 493 ape_read_packet, 494 ape_read_close, 495 ape_read_seek, 496 .extensions = "ape,apl,mac" 497}; 498