]> git.sesse.net Git - ffmpeg/blob - libavcodec/apedec.c
0bef457eb86df63d135f57c5e5d01d19e683e639
[ffmpeg] / libavcodec / apedec.c
1 /*
2  * Monkey's Audio lossless audio decoder
3  * Copyright (c) 2007 Benjamin Zores <ben@geexbox.org>
4  *  based upon libdemac from Dave Chapman.
5  *
6  * This file is part of Libav.
7  *
8  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include "libavutil/avassert.h"
24 #include "libavutil/channel_layout.h"
25 #include "libavutil/opt.h"
26 #include "avcodec.h"
27 #include "dsputil.h"
28 #include "bytestream.h"
29 #include "internal.h"
30
31 /**
32  * @file
33  * Monkey's Audio lossless audio decoder
34  */
35
36 #define MAX_CHANNELS        2
37 #define MAX_BYTESPERSAMPLE  3
38
39 #define APE_FRAMECODE_MONO_SILENCE    1
40 #define APE_FRAMECODE_STEREO_SILENCE  3
41 #define APE_FRAMECODE_PSEUDO_STEREO   4
42
43 #define HISTORY_SIZE 512
44 #define PREDICTOR_ORDER 8
45 /** Total size of all predictor histories */
46 #define PREDICTOR_SIZE 50
47
48 #define YDELAYA (18 + PREDICTOR_ORDER*4)
49 #define YDELAYB (18 + PREDICTOR_ORDER*3)
50 #define XDELAYA (18 + PREDICTOR_ORDER*2)
51 #define XDELAYB (18 + PREDICTOR_ORDER)
52
53 #define YADAPTCOEFFSA 18
54 #define XADAPTCOEFFSA 14
55 #define YADAPTCOEFFSB 10
56 #define XADAPTCOEFFSB 5
57
58 /**
59  * Possible compression levels
60  * @{
61  */
62 enum APECompressionLevel {
63     COMPRESSION_LEVEL_FAST       = 1000,
64     COMPRESSION_LEVEL_NORMAL     = 2000,
65     COMPRESSION_LEVEL_HIGH       = 3000,
66     COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
67     COMPRESSION_LEVEL_INSANE     = 5000
68 };
69 /** @} */
70
71 #define APE_FILTER_LEVELS 3
72
73 /** Filter orders depending on compression level */
74 static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
75     {  0,   0,    0 },
76     { 16,   0,    0 },
77     { 64,   0,    0 },
78     { 32, 256,    0 },
79     { 16, 256, 1280 }
80 };
81
82 /** Filter fraction bits depending on compression level */
83 static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
84     {  0,  0,  0 },
85     { 11,  0,  0 },
86     { 11,  0,  0 },
87     { 10, 13,  0 },
88     { 11, 13, 15 }
89 };
90
91
92 /** Filters applied to the decoded data */
93 typedef struct APEFilter {
94     int16_t *coeffs;        ///< actual coefficients used in filtering
95     int16_t *adaptcoeffs;   ///< adaptive filter coefficients used for correcting of actual filter coefficients
96     int16_t *historybuffer; ///< filter memory
97     int16_t *delay;         ///< filtered values
98
99     int avg;
100 } APEFilter;
101
102 typedef struct APERice {
103     uint32_t k;
104     uint32_t ksum;
105 } APERice;
106
107 typedef struct APERangecoder {
108     uint32_t low;           ///< low end of interval
109     uint32_t range;         ///< length of interval
110     uint32_t help;          ///< bytes_to_follow resp. intermediate value
111     unsigned int buffer;    ///< buffer for input/output
112 } APERangecoder;
113
114 /** Filter histories */
115 typedef struct APEPredictor {
116     int32_t *buf;
117
118     int32_t lastA[2];
119
120     int32_t filterA[2];
121     int32_t filterB[2];
122
123     int32_t coeffsA[2][4];  ///< adaption coefficients
124     int32_t coeffsB[2][5];  ///< adaption coefficients
125     int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
126 } APEPredictor;
127
128 /** Decoder context */
129 typedef struct APEContext {
130     AVClass *class;                          ///< class for AVOptions
131     AVCodecContext *avctx;
132     DSPContext dsp;
133     int channels;
134     int samples;                             ///< samples left to decode in current frame
135     int bps;
136
137     int fileversion;                         ///< codec version, very important in decoding process
138     int compression_level;                   ///< compression levels
139     int fset;                                ///< which filter set to use (calculated from compression level)
140     int flags;                               ///< global decoder flags
141
142     uint32_t CRC;                            ///< frame CRC
143     int frameflags;                          ///< frame flags
144     APEPredictor predictor;                  ///< predictor used for final reconstruction
145
146     int32_t *decoded_buffer;
147     int decoded_size;
148     int32_t *decoded[MAX_CHANNELS];          ///< decoded data for each channel
149     int blocks_per_loop;                     ///< maximum number of samples to decode for each call
150
151     int16_t* filterbuf[APE_FILTER_LEVELS];   ///< filter memory
152
153     APERangecoder rc;                        ///< rangecoder used to decode actual values
154     APERice riceX;                           ///< rice code parameters for the second channel
155     APERice riceY;                           ///< rice code parameters for the first channel
156     APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
157
158     uint8_t *data;                           ///< current frame data
159     uint8_t *data_end;                       ///< frame data end
160     int data_size;                           ///< frame data allocated size
161     const uint8_t *ptr;                      ///< current position in frame data
162
163     int error;
164
165     void (*entropy_decode_mono)(struct APEContext *ctx, int blockstodecode);
166     void (*entropy_decode_stereo)(struct APEContext *ctx, int blockstodecode);
167     void (*predictor_decode_mono)(struct APEContext *ctx, int count);
168     void (*predictor_decode_stereo)(struct APEContext *ctx, int count);
169 } APEContext;
170
171 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
172                               int32_t *decoded1, int count);
173
174 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode);
175 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode);
176 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode);
177 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode);
178
179 static void predictor_decode_mono_3950(APEContext *ctx, int count);
180 static void predictor_decode_stereo_3950(APEContext *ctx, int count);
181
182 // TODO: dsputilize
183
184 static av_cold int ape_decode_close(AVCodecContext *avctx)
185 {
186     APEContext *s = avctx->priv_data;
187     int i;
188
189     for (i = 0; i < APE_FILTER_LEVELS; i++)
190         av_freep(&s->filterbuf[i]);
191
192     av_freep(&s->decoded_buffer);
193     av_freep(&s->data);
194     s->decoded_size = s->data_size = 0;
195
196     return 0;
197 }
198
199 static av_cold int ape_decode_init(AVCodecContext *avctx)
200 {
201     APEContext *s = avctx->priv_data;
202     int i;
203
204     if (avctx->extradata_size != 6) {
205         av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
206         return AVERROR(EINVAL);
207     }
208     if (avctx->channels > 2) {
209         av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
210         return AVERROR(EINVAL);
211     }
212     s->bps = avctx->bits_per_coded_sample;
213     switch (s->bps) {
214     case 8:
215         avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
216         break;
217     case 16:
218         avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
219         break;
220     case 24:
221         avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
222         break;
223     default:
224         avpriv_request_sample(avctx,
225                               "%d bits per coded sample", s->bps);
226         return AVERROR_PATCHWELCOME;
227     }
228     s->avctx             = avctx;
229     s->channels          = avctx->channels;
230     s->fileversion       = AV_RL16(avctx->extradata);
231     s->compression_level = AV_RL16(avctx->extradata + 2);
232     s->flags             = AV_RL16(avctx->extradata + 4);
233
234     av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n",
235            s->compression_level, s->flags);
236     if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE) {
237         av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
238                s->compression_level);
239         return AVERROR_INVALIDDATA;
240     }
241     s->fset = s->compression_level / 1000 - 1;
242     for (i = 0; i < APE_FILTER_LEVELS; i++) {
243         if (!ape_filter_orders[s->fset][i])
244             break;
245         FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
246                          (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
247                          filter_alloc_fail);
248     }
249
250     if (s->fileversion < 3990) {
251         s->entropy_decode_mono   = entropy_decode_mono_3900;
252         s->entropy_decode_stereo = entropy_decode_stereo_3900;
253     } else {
254         s->entropy_decode_mono   = entropy_decode_mono_3990;
255         s->entropy_decode_stereo = entropy_decode_stereo_3990;
256     }
257
258     s->predictor_decode_mono   = predictor_decode_mono_3950;
259     s->predictor_decode_stereo = predictor_decode_stereo_3950;
260
261     ff_dsputil_init(&s->dsp, avctx);
262     avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
263
264     return 0;
265 filter_alloc_fail:
266     ape_decode_close(avctx);
267     return AVERROR(ENOMEM);
268 }
269
270 /**
271  * @name APE range decoding functions
272  * @{
273  */
274
275 #define CODE_BITS    32
276 #define TOP_VALUE    ((unsigned int)1 << (CODE_BITS-1))
277 #define SHIFT_BITS   (CODE_BITS - 9)
278 #define EXTRA_BITS   ((CODE_BITS-2) % 8 + 1)
279 #define BOTTOM_VALUE (TOP_VALUE >> 8)
280
281 /** Start the decoder */
282 static inline void range_start_decoding(APEContext *ctx)
283 {
284     ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
285     ctx->rc.low    = ctx->rc.buffer >> (8 - EXTRA_BITS);
286     ctx->rc.range  = (uint32_t) 1 << EXTRA_BITS;
287 }
288
289 /** Perform normalization */
290 static inline void range_dec_normalize(APEContext *ctx)
291 {
292     while (ctx->rc.range <= BOTTOM_VALUE) {
293         ctx->rc.buffer <<= 8;
294         if(ctx->ptr < ctx->data_end) {
295             ctx->rc.buffer += *ctx->ptr;
296             ctx->ptr++;
297         } else {
298             ctx->error = 1;
299         }
300         ctx->rc.low    = (ctx->rc.low << 8)    | ((ctx->rc.buffer >> 1) & 0xFF);
301         ctx->rc.range  <<= 8;
302     }
303 }
304
305 /**
306  * Calculate culmulative frequency for next symbol. Does NO update!
307  * @param ctx decoder context
308  * @param tot_f is the total frequency or (code_value)1<<shift
309  * @return the culmulative frequency
310  */
311 static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
312 {
313     range_dec_normalize(ctx);
314     ctx->rc.help = ctx->rc.range / tot_f;
315     return ctx->rc.low / ctx->rc.help;
316 }
317
318 /**
319  * Decode value with given size in bits
320  * @param ctx decoder context
321  * @param shift number of bits to decode
322  */
323 static inline int range_decode_culshift(APEContext *ctx, int shift)
324 {
325     range_dec_normalize(ctx);
326     ctx->rc.help = ctx->rc.range >> shift;
327     return ctx->rc.low / ctx->rc.help;
328 }
329
330
331 /**
332  * Update decoding state
333  * @param ctx decoder context
334  * @param sy_f the interval length (frequency of the symbol)
335  * @param lt_f the lower end (frequency sum of < symbols)
336  */
337 static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
338 {
339     ctx->rc.low  -= ctx->rc.help * lt_f;
340     ctx->rc.range = ctx->rc.help * sy_f;
341 }
342
343 /** Decode n bits (n <= 16) without modelling */
344 static inline int range_decode_bits(APEContext *ctx, int n)
345 {
346     int sym = range_decode_culshift(ctx, n);
347     range_decode_update(ctx, 1, sym);
348     return sym;
349 }
350
351
352 #define MODEL_ELEMENTS 64
353
354 /**
355  * Fixed probabilities for symbols in Monkey Audio version 3.97
356  */
357 static const uint16_t counts_3970[22] = {
358         0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
359     62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
360     65450, 65469, 65480, 65487, 65491, 65493,
361 };
362
363 /**
364  * Probability ranges for symbols in Monkey Audio version 3.97
365  */
366 static const uint16_t counts_diff_3970[21] = {
367     14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
368     1104, 677, 415, 248, 150, 89, 54, 31,
369     19, 11, 7, 4, 2,
370 };
371
372 /**
373  * Fixed probabilities for symbols in Monkey Audio version 3.98
374  */
375 static const uint16_t counts_3980[22] = {
376         0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
377     64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
378     65485, 65488, 65490, 65491, 65492, 65493,
379 };
380
381 /**
382  * Probability ranges for symbols in Monkey Audio version 3.98
383  */
384 static const uint16_t counts_diff_3980[21] = {
385     19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
386     261, 119, 65, 31, 19, 10, 6, 3,
387     3, 2, 1, 1, 1,
388 };
389
390 /**
391  * Decode symbol
392  * @param ctx decoder context
393  * @param counts probability range start position
394  * @param counts_diff probability range widths
395  */
396 static inline int range_get_symbol(APEContext *ctx,
397                                    const uint16_t counts[],
398                                    const uint16_t counts_diff[])
399 {
400     int symbol, cf;
401
402     cf = range_decode_culshift(ctx, 16);
403
404     if(cf > 65492){
405         symbol= cf - 65535 + 63;
406         range_decode_update(ctx, 1, cf);
407         if(cf > 65535)
408             ctx->error=1;
409         return symbol;
410     }
411     /* figure out the symbol inefficiently; a binary search would be much better */
412     for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
413
414     range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
415
416     return symbol;
417 }
418 /** @} */ // group rangecoder
419
420 static inline void update_rice(APERice *rice, unsigned int x)
421 {
422     int lim = rice->k ? (1 << (rice->k + 4)) : 0;
423     rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
424
425     if (rice->ksum < lim)
426         rice->k--;
427     else if (rice->ksum >= (1 << (rice->k + 5)))
428         rice->k++;
429 }
430
431 static inline int ape_decode_value_3900(APEContext *ctx, APERice *rice)
432 {
433     unsigned int x, overflow;
434     int tmpk;
435
436     overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
437
438     if (overflow == (MODEL_ELEMENTS - 1)) {
439         tmpk = range_decode_bits(ctx, 5);
440         overflow = 0;
441     } else
442         tmpk = (rice->k < 1) ? 0 : rice->k - 1;
443
444     if (tmpk <= 16)
445         x = range_decode_bits(ctx, tmpk);
446     else if (tmpk <= 32) {
447         x = range_decode_bits(ctx, 16);
448         x |= (range_decode_bits(ctx, tmpk - 16) << 16);
449     } else {
450         av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
451         return AVERROR_INVALIDDATA;
452     }
453     x += overflow << tmpk;
454
455     update_rice(rice, x);
456
457     /* Convert to signed */
458     if (x & 1)
459         return (x >> 1) + 1;
460     else
461         return -(x >> 1);
462 }
463
464 static inline int ape_decode_value_3990(APEContext *ctx, APERice *rice)
465 {
466     unsigned int x, overflow;
467     int base, pivot;
468
469     pivot = rice->ksum >> 5;
470     if (pivot == 0)
471         pivot = 1;
472
473     overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
474
475     if (overflow == (MODEL_ELEMENTS - 1)) {
476         overflow  = range_decode_bits(ctx, 16) << 16;
477         overflow |= range_decode_bits(ctx, 16);
478     }
479
480     if (pivot < 0x10000) {
481         base = range_decode_culfreq(ctx, pivot);
482         range_decode_update(ctx, 1, base);
483     } else {
484         int base_hi = pivot, base_lo;
485         int bbits = 0;
486
487         while (base_hi & ~0xFFFF) {
488             base_hi >>= 1;
489             bbits++;
490         }
491         base_hi = range_decode_culfreq(ctx, base_hi + 1);
492         range_decode_update(ctx, 1, base_hi);
493         base_lo = range_decode_culfreq(ctx, 1 << bbits);
494         range_decode_update(ctx, 1, base_lo);
495
496         base = (base_hi << bbits) + base_lo;
497     }
498
499     x = base + overflow * pivot;
500
501     update_rice(rice, x);
502
503     /* Convert to signed */
504     if (x & 1)
505         return (x >> 1) + 1;
506     else
507         return -(x >> 1);
508 }
509
510 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode)
511 {
512     int32_t *decoded0 = ctx->decoded[0];
513
514     while (blockstodecode--)
515         *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
516 }
517
518 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode)
519 {
520     int32_t *decoded0 = ctx->decoded[0];
521     int32_t *decoded1 = ctx->decoded[1];
522
523     while (blockstodecode--) {
524         *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
525         *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
526     }
527 }
528
529 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode)
530 {
531     int32_t *decoded0 = ctx->decoded[0];
532
533     while (blockstodecode--)
534         *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
535 }
536
537 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode)
538 {
539     int32_t *decoded0 = ctx->decoded[0];
540     int32_t *decoded1 = ctx->decoded[1];
541
542     while (blockstodecode--) {
543         *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
544         *decoded1++ = ape_decode_value_3990(ctx, &ctx->riceX);
545     }
546 }
547
548 static int init_entropy_decoder(APEContext *ctx)
549 {
550     /* Read the CRC */
551     if (ctx->data_end - ctx->ptr < 6)
552         return AVERROR_INVALIDDATA;
553     ctx->CRC = bytestream_get_be32(&ctx->ptr);
554
555     /* Read the frame flags if they exist */
556     ctx->frameflags = 0;
557     if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
558         ctx->CRC &= ~0x80000000;
559
560         if (ctx->data_end - ctx->ptr < 6)
561             return AVERROR_INVALIDDATA;
562         ctx->frameflags = bytestream_get_be32(&ctx->ptr);
563     }
564
565     /* Initialize the rice structs */
566     ctx->riceX.k = 10;
567     ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
568     ctx->riceY.k = 10;
569     ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
570
571     /* The first 8 bits of input are ignored. */
572     ctx->ptr++;
573
574     range_start_decoding(ctx);
575
576     return 0;
577 }
578
579 static const int32_t initial_coeffs[4] = {
580     360, 317, -109, 98
581 };
582
583 static void init_predictor_decoder(APEContext *ctx)
584 {
585     APEPredictor *p = &ctx->predictor;
586
587     /* Zero the history buffers */
588     memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
589     p->buf = p->historybuffer;
590
591     /* Initialize and zero the coefficients */
592     memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
593     memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
594     memset(p->coeffsB, 0, sizeof(p->coeffsB));
595
596     p->filterA[0] = p->filterA[1] = 0;
597     p->filterB[0] = p->filterB[1] = 0;
598     p->lastA[0]   = p->lastA[1]   = 0;
599 }
600
601 /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
602 static inline int APESIGN(int32_t x) {
603     return (x < 0) - (x > 0);
604 }
605
606 static av_always_inline int predictor_update_filter(APEPredictor *p,
607                                                     const int decoded, const int filter,
608                                                     const int delayA,  const int delayB,
609                                                     const int adaptA,  const int adaptB)
610 {
611     int32_t predictionA, predictionB, sign;
612
613     p->buf[delayA]     = p->lastA[filter];
614     p->buf[adaptA]     = APESIGN(p->buf[delayA]);
615     p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
616     p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
617
618     predictionA = p->buf[delayA    ] * p->coeffsA[filter][0] +
619                   p->buf[delayA - 1] * p->coeffsA[filter][1] +
620                   p->buf[delayA - 2] * p->coeffsA[filter][2] +
621                   p->buf[delayA - 3] * p->coeffsA[filter][3];
622
623     /*  Apply a scaled first-order filter compression */
624     p->buf[delayB]     = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
625     p->buf[adaptB]     = APESIGN(p->buf[delayB]);
626     p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
627     p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
628     p->filterB[filter] = p->filterA[filter ^ 1];
629
630     predictionB = p->buf[delayB    ] * p->coeffsB[filter][0] +
631                   p->buf[delayB - 1] * p->coeffsB[filter][1] +
632                   p->buf[delayB - 2] * p->coeffsB[filter][2] +
633                   p->buf[delayB - 3] * p->coeffsB[filter][3] +
634                   p->buf[delayB - 4] * p->coeffsB[filter][4];
635
636     p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
637     p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
638
639     sign = APESIGN(decoded);
640     p->coeffsA[filter][0] += p->buf[adaptA    ] * sign;
641     p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
642     p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
643     p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
644     p->coeffsB[filter][0] += p->buf[adaptB    ] * sign;
645     p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
646     p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
647     p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
648     p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
649
650     return p->filterA[filter];
651 }
652
653 static void predictor_decode_stereo_3950(APEContext *ctx, int count)
654 {
655     APEPredictor *p = &ctx->predictor;
656     int32_t *decoded0 = ctx->decoded[0];
657     int32_t *decoded1 = ctx->decoded[1];
658
659     ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
660
661     while (count--) {
662         /* Predictor Y */
663         *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
664                                             YADAPTCOEFFSA, YADAPTCOEFFSB);
665         decoded0++;
666         *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
667                                             XADAPTCOEFFSA, XADAPTCOEFFSB);
668         decoded1++;
669
670         /* Combined */
671         p->buf++;
672
673         /* Have we filled the history buffer? */
674         if (p->buf == p->historybuffer + HISTORY_SIZE) {
675             memmove(p->historybuffer, p->buf,
676                     PREDICTOR_SIZE * sizeof(*p->historybuffer));
677             p->buf = p->historybuffer;
678         }
679     }
680 }
681
682 static void predictor_decode_mono_3950(APEContext *ctx, int count)
683 {
684     APEPredictor *p = &ctx->predictor;
685     int32_t *decoded0 = ctx->decoded[0];
686     int32_t predictionA, currentA, A, sign;
687
688     ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
689
690     currentA = p->lastA[0];
691
692     while (count--) {
693         A = *decoded0;
694
695         p->buf[YDELAYA] = currentA;
696         p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
697
698         predictionA = p->buf[YDELAYA    ] * p->coeffsA[0][0] +
699                       p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
700                       p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
701                       p->buf[YDELAYA - 3] * p->coeffsA[0][3];
702
703         currentA = A + (predictionA >> 10);
704
705         p->buf[YADAPTCOEFFSA]     = APESIGN(p->buf[YDELAYA    ]);
706         p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
707
708         sign = APESIGN(A);
709         p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA    ] * sign;
710         p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
711         p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
712         p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
713
714         p->buf++;
715
716         /* Have we filled the history buffer? */
717         if (p->buf == p->historybuffer + HISTORY_SIZE) {
718             memmove(p->historybuffer, p->buf,
719                     PREDICTOR_SIZE * sizeof(*p->historybuffer));
720             p->buf = p->historybuffer;
721         }
722
723         p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
724         *(decoded0++) = p->filterA[0];
725     }
726
727     p->lastA[0] = currentA;
728 }
729
730 static void do_init_filter(APEFilter *f, int16_t *buf, int order)
731 {
732     f->coeffs = buf;
733     f->historybuffer = buf + order;
734     f->delay       = f->historybuffer + order * 2;
735     f->adaptcoeffs = f->historybuffer + order;
736
737     memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
738     memset(f->coeffs, 0, order * sizeof(*f->coeffs));
739     f->avg = 0;
740 }
741
742 static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
743 {
744     do_init_filter(&f[0], buf, order);
745     do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
746 }
747
748 static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
749                             int32_t *data, int count, int order, int fracbits)
750 {
751     int res;
752     int absres;
753
754     while (count--) {
755         /* round fixedpoint scalar product */
756         res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order,
757                                                     f->adaptcoeffs - order,
758                                                     order, APESIGN(*data));
759         res = (res + (1 << (fracbits - 1))) >> fracbits;
760         res += *data;
761         *data++ = res;
762
763         /* Update the output history */
764         *f->delay++ = av_clip_int16(res);
765
766         if (version < 3980) {
767             /* Version ??? to < 3.98 files (untested) */
768             f->adaptcoeffs[0]  = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
769             f->adaptcoeffs[-4] >>= 1;
770             f->adaptcoeffs[-8] >>= 1;
771         } else {
772             /* Version 3.98 and later files */
773
774             /* Update the adaption coefficients */
775             absres = FFABS(res);
776             if (absres)
777                 *f->adaptcoeffs = ((res & (-1<<31)) ^ (-1<<30)) >>
778                                   (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
779             else
780                 *f->adaptcoeffs = 0;
781
782             f->avg += (absres - f->avg) / 16;
783
784             f->adaptcoeffs[-1] >>= 1;
785             f->adaptcoeffs[-2] >>= 1;
786             f->adaptcoeffs[-8] >>= 1;
787         }
788
789         f->adaptcoeffs++;
790
791         /* Have we filled the history buffer? */
792         if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
793             memmove(f->historybuffer, f->delay - (order * 2),
794                     (order * 2) * sizeof(*f->historybuffer));
795             f->delay = f->historybuffer + order * 2;
796             f->adaptcoeffs = f->historybuffer + order;
797         }
798     }
799 }
800
801 static void apply_filter(APEContext *ctx, APEFilter *f,
802                          int32_t *data0, int32_t *data1,
803                          int count, int order, int fracbits)
804 {
805     do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
806     if (data1)
807         do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
808 }
809
810 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
811                               int32_t *decoded1, int count)
812 {
813     int i;
814
815     for (i = 0; i < APE_FILTER_LEVELS; i++) {
816         if (!ape_filter_orders[ctx->fset][i])
817             break;
818         apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
819                      ape_filter_orders[ctx->fset][i],
820                      ape_filter_fracbits[ctx->fset][i]);
821     }
822 }
823
824 static int init_frame_decoder(APEContext *ctx)
825 {
826     int i, ret;
827     if ((ret = init_entropy_decoder(ctx)) < 0)
828         return ret;
829     init_predictor_decoder(ctx);
830
831     for (i = 0; i < APE_FILTER_LEVELS; i++) {
832         if (!ape_filter_orders[ctx->fset][i])
833             break;
834         init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
835                     ape_filter_orders[ctx->fset][i]);
836     }
837     return 0;
838 }
839
840 static void ape_unpack_mono(APEContext *ctx, int count)
841 {
842     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
843         /* We are pure silence, so we're done. */
844         av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
845         return;
846     }
847
848     ctx->entropy_decode_mono(ctx, count);
849
850     /* Now apply the predictor decoding */
851     ctx->predictor_decode_mono(ctx, count);
852
853     /* Pseudo-stereo - just copy left channel to right channel */
854     if (ctx->channels == 2) {
855         memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
856     }
857 }
858
859 static void ape_unpack_stereo(APEContext *ctx, int count)
860 {
861     int32_t left, right;
862     int32_t *decoded0 = ctx->decoded[0];
863     int32_t *decoded1 = ctx->decoded[1];
864
865     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
866         /* We are pure silence, so we're done. */
867         av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
868         return;
869     }
870
871     ctx->entropy_decode_stereo(ctx, count);
872
873     /* Now apply the predictor decoding */
874     ctx->predictor_decode_stereo(ctx, count);
875
876     /* Decorrelate and scale to output depth */
877     while (count--) {
878         left = *decoded1 - (*decoded0 / 2);
879         right = left + *decoded0;
880
881         *(decoded0++) = left;
882         *(decoded1++) = right;
883     }
884 }
885
886 static int ape_decode_frame(AVCodecContext *avctx, void *data,
887                             int *got_frame_ptr, AVPacket *avpkt)
888 {
889     AVFrame *frame     = data;
890     const uint8_t *buf = avpkt->data;
891     APEContext *s = avctx->priv_data;
892     uint8_t *sample8;
893     int16_t *sample16;
894     int32_t *sample24;
895     int i, ch, ret;
896     int blockstodecode;
897     int bytes_used = 0;
898
899     /* this should never be negative, but bad things will happen if it is, so
900        check it just to make sure. */
901     av_assert0(s->samples >= 0);
902
903     if(!s->samples){
904         uint32_t nblocks, offset;
905         int buf_size;
906
907         if (!avpkt->size) {
908             *got_frame_ptr = 0;
909             return 0;
910         }
911         if (avpkt->size < 8) {
912             av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
913             return AVERROR_INVALIDDATA;
914         }
915         buf_size = avpkt->size & ~3;
916         if (buf_size != avpkt->size) {
917             av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
918                    "extra bytes at the end will be skipped.\n");
919         }
920
921         av_fast_malloc(&s->data, &s->data_size, buf_size);
922         if (!s->data)
923             return AVERROR(ENOMEM);
924         s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
925         s->ptr = s->data;
926         s->data_end = s->data + buf_size;
927
928         nblocks = bytestream_get_be32(&s->ptr);
929         offset  = bytestream_get_be32(&s->ptr);
930         if (offset > 3) {
931             av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
932             s->data = NULL;
933             return AVERROR_INVALIDDATA;
934         }
935         if (s->data_end - s->ptr < offset) {
936             av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
937             return AVERROR_INVALIDDATA;
938         }
939         s->ptr += offset;
940
941         if (!nblocks || nblocks > INT_MAX) {
942             av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %u.\n", nblocks);
943             return AVERROR_INVALIDDATA;
944         }
945         s->samples = nblocks;
946
947         /* Initialize the frame decoder */
948         if (init_frame_decoder(s) < 0) {
949             av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
950             return AVERROR_INVALIDDATA;
951         }
952
953         bytes_used = avpkt->size;
954     }
955
956     if (!s->data) {
957         *got_frame_ptr = 0;
958         return avpkt->size;
959     }
960
961     blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
962
963     /* reallocate decoded sample buffer if needed */
964     av_fast_malloc(&s->decoded_buffer, &s->decoded_size,
965                    2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));
966     if (!s->decoded_buffer)
967         return AVERROR(ENOMEM);
968     memset(s->decoded_buffer, 0, s->decoded_size);
969     s->decoded[0] = s->decoded_buffer;
970     s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
971
972     /* get output buffer */
973     frame->nb_samples = blockstodecode;
974     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
975         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
976         return ret;
977     }
978
979     s->error=0;
980
981     if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
982         ape_unpack_mono(s, blockstodecode);
983     else
984         ape_unpack_stereo(s, blockstodecode);
985     emms_c();
986
987     if (s->error) {
988         s->samples=0;
989         av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
990         return AVERROR_INVALIDDATA;
991     }
992
993     switch (s->bps) {
994     case 8:
995         for (ch = 0; ch < s->channels; ch++) {
996             sample8 = (uint8_t *)frame->data[ch];
997             for (i = 0; i < blockstodecode; i++)
998                 *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
999         }
1000         break;
1001     case 16:
1002         for (ch = 0; ch < s->channels; ch++) {
1003             sample16 = (int16_t *)frame->data[ch];
1004             for (i = 0; i < blockstodecode; i++)
1005                 *sample16++ = s->decoded[ch][i];
1006         }
1007         break;
1008     case 24:
1009         for (ch = 0; ch < s->channels; ch++) {
1010             sample24 = (int32_t *)frame->data[ch];
1011             for (i = 0; i < blockstodecode; i++)
1012                 *sample24++ = s->decoded[ch][i] << 8;
1013         }
1014         break;
1015     }
1016
1017     s->samples -= blockstodecode;
1018
1019     *got_frame_ptr = 1;
1020
1021     return bytes_used;
1022 }
1023
1024 static void ape_flush(AVCodecContext *avctx)
1025 {
1026     APEContext *s = avctx->priv_data;
1027     s->samples= 0;
1028 }
1029
1030 #define OFFSET(x) offsetof(APEContext, x)
1031 #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
1032 static const AVOption options[] = {
1033     { "max_samples", "maximum number of samples decoded per call",             OFFSET(blocks_per_loop), AV_OPT_TYPE_INT,   { .i64 = 4608 },    1,       INT_MAX, PAR, "max_samples" },
1034     { "all",         "no maximum. decode all samples for each packet at once", 0,                       AV_OPT_TYPE_CONST, { .i64 = INT_MAX }, INT_MIN, INT_MAX, PAR, "max_samples" },
1035     { NULL},
1036 };
1037
1038 static const AVClass ape_decoder_class = {
1039     .class_name = "APE decoder",
1040     .item_name  = av_default_item_name,
1041     .option     = options,
1042     .version    = LIBAVUTIL_VERSION_INT,
1043 };
1044
1045 AVCodec ff_ape_decoder = {
1046     .name           = "ape",
1047     .type           = AVMEDIA_TYPE_AUDIO,
1048     .id             = AV_CODEC_ID_APE,
1049     .priv_data_size = sizeof(APEContext),
1050     .init           = ape_decode_init,
1051     .close          = ape_decode_close,
1052     .decode         = ape_decode_frame,
1053     .capabilities   = CODEC_CAP_SUBFRAMES | CODEC_CAP_DELAY | CODEC_CAP_DR1,
1054     .flush          = ape_flush,
1055     .long_name      = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
1056     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
1057                                                       AV_SAMPLE_FMT_S16P,
1058                                                       AV_SAMPLE_FMT_S32P,
1059                                                       AV_SAMPLE_FMT_NONE },
1060     .priv_class     = &ape_decoder_class,
1061 };