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