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