]> git.sesse.net Git - ffmpeg/blob - libavformat/ape.c
use new metadata API in ape demuxer
[ffmpeg] / 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 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     av_metadata_set(&s->metadata, key, value);
115 }
116
117 static void ape_parse_tag(AVFormatContext *s)
118 {
119     ByteIOContext *pb = s->pb;
120     int file_size = url_fsize(pb);
121     uint32_t val, fields, tag_bytes;
122     uint8_t buf[8];
123     int i;
124
125     if (file_size < APE_TAG_FOOTER_BYTES)
126         return;
127
128     url_fseek(pb, file_size - APE_TAG_FOOTER_BYTES, SEEK_SET);
129
130     get_buffer(pb, buf, 8);    /* APETAGEX */
131     if (strncmp(buf, "APETAGEX", 8)) {
132         return;
133     }
134
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);
138         return;
139     }
140
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");
144         return;
145     }
146
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);
150         return;
151     }
152
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");
156         return;
157     }
158
159     if (val & APE_TAG_FLAG_CONTAINS_HEADER)
160         tag_bytes += 2*APE_TAG_FOOTER_BYTES;
161
162     url_fseek(pb, file_size - tag_bytes, SEEK_SET);
163
164     for (i=0; i<fields; i++)
165         ape_tag_read_field(s);
166
167 #if ENABLE_DEBUG
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);
177 #endif
178 }
179
180 static int ape_probe(AVProbeData * p)
181 {
182     if (p->buf[0] == 'M' && p->buf[1] == 'A' && p->buf[2] == 'C' && p->buf[3] == ' ')
183         return AVPROBE_SCORE_MAX;
184
185     return 0;
186 }
187
188 static void ape_dumpinfo(AVFormatContext * s, APEContext * ape_ctx)
189 {
190 #if ENABLE_DEBUG
191     int i;
192
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");
207
208     av_log(s, AV_LOG_DEBUG, "\nHeader Block:\n\n");
209
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);
218
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");
222     } else {
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]);
226             } else {
227                 av_log(s, AV_LOG_DEBUG, "%8d   %d\n", i, ape_ctx->seektable[i]);
228             }
229         }
230     }
231
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);
235
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);
240 #endif
241 }
242
243 static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap)
244 {
245     ByteIOContext *pb = s->pb;
246     APEContext *ape = s->priv_data;
247     AVStream *st;
248     uint32_t tag;
249     int i;
250     int total_blocks;
251     int64_t pts;
252
253     /* TODO: Skip any leading junk such as id3v2 tags */
254     ape->junklength = 0;
255
256     tag = get_le32(pb);
257     if (tag != MKTAG('M', 'A', 'C', ' '))
258         return -1;
259
260     ape->fileversion = get_le16(pb);
261
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);
264         return -1;
265     }
266
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);
277
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);
282
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);
292     } else {
293         ape->descriptorlength = 0;
294         ape->headerlength = 32;
295
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);
304
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;
308         }
309
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);
314         } else
315             ape->seektablelength = ape->totalframes * sizeof(int32_t);
316
317         if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT)
318             ape->bps = 8;
319         else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT)
320             ape->bps = 24;
321         else
322             ape->bps = 16;
323
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;
328         else
329             ape->blocksperframe = 9216;
330
331         /* Skip any stored wav header */
332         if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER))
333             url_fskip(pb, ape->wavheaderlength);
334     }
335
336     if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){
337         av_log(s, AV_LOG_ERROR, "Too many frames: %d\n", ape->totalframes);
338         return -1;
339     }
340     ape->frames       = av_malloc(ape->totalframes * sizeof(APEFrame));
341     if(!ape->frames)
342         return AVERROR_NOMEM;
343     ape->firstframe   = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength;
344     ape->currentframe = 0;
345
346
347     ape->totalsamples = ape->finalframeblocks;
348     if (ape->totalframes > 1)
349         ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1);
350
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);
355     }
356
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;
365     }
366     ape->frames[ape->totalframes - 1].size    = ape->finalframeblocks * 4;
367     ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks;
368
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;
373         }
374         ape->frames[i].size = (ape->frames[i].size + 3) & ~3;
375     }
376
377
378     ape_dumpinfo(s, ape);
379
380     /* try to read APE tags */
381     if (!url_is_streamed(pb)) {
382         ape_parse_tag(s);
383         url_fseek(pb, 0, SEEK_SET);
384     }
385
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);
387
388     /* now we are ready: build format streams */
389     st = av_new_stream(s, 0);
390     if (!st)
391         return -1;
392
393     total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks;
394
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;
402
403     st->nb_frames = ape->totalframes;
404     s->start_time = 0;
405     s->duration   = (int64_t) total_blocks * AV_TIME_BASE / ape->samplerate;
406     av_set_pts_info(st, 64, MAC_SUBFRAME_SIZE, ape->samplerate);
407
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);
413
414     pts = 0;
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;
419     }
420
421     return 0;
422 }
423
424 static int ape_read_packet(AVFormatContext * s, AVPacket * pkt)
425 {
426     int ret;
427     int nblocks;
428     APEContext *ape = s->priv_data;
429     uint32_t extra_size = 8;
430
431     if (url_feof(s->pb))
432         return AVERROR_IO;
433     if (ape->currentframe > ape->totalframes)
434         return AVERROR_IO;
435
436     url_fseek (s->pb, ape->frames[ape->currentframe].pos, SEEK_SET);
437
438     /* Calculate how many blocks there are in this frame */
439     if (ape->currentframe == (ape->totalframes - 1))
440         nblocks = ape->finalframeblocks;
441     else
442         nblocks = ape->blocksperframe;
443
444     if (av_new_packet(pkt,  ape->frames[ape->currentframe].size + extra_size) < 0)
445         return AVERROR_NOMEM;
446
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);
450
451     pkt->pts = ape->frames[ape->currentframe].pts;
452     pkt->stream_index = 0;
453
454     /* note: we need to modify the packet size here to handle the last
455        packet */
456     pkt->size = ret + extra_size;
457
458     ape->currentframe++;
459
460     return 0;
461 }
462
463 static int ape_read_close(AVFormatContext * s)
464 {
465     APEContext *ape = s->priv_data;
466
467     av_freep(&ape->frames);
468     av_freep(&ape->seektable);
469     return 0;
470 }
471
472 static int ape_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
473 {
474     AVStream *st = s->streams[stream_index];
475     APEContext *ape = s->priv_data;
476     int index = av_index_search_timestamp(st, timestamp, flags);
477
478     if (index < 0)
479         return -1;
480
481     ape->currentframe = index;
482     return 0;
483 }
484
485 AVInputFormat ape_demuxer = {
486     "ape",
487     NULL_IF_CONFIG_SMALL("Monkey's Audio"),
488     sizeof(APEContext),
489     ape_probe,
490     ape_read_header,
491     ape_read_packet,
492     ape_read_close,
493     ape_read_seek,
494     .extensions = "ape,apl,mac"
495 };