]> git.sesse.net Git - ffmpeg/blob - libavcodec/apedec.c
hevc: change the stride of the MC buffer to be in bytes instead of elements
[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 <inttypes.h>
24
25 #include "libavutil/avassert.h"
26 #include "libavutil/channel_layout.h"
27 #include "libavutil/opt.h"
28 #include "apedsp.h"
29 #include "avcodec.h"
30 #include "bswapdsp.h"
31 #include "bytestream.h"
32 #include "internal.h"
33 #include "get_bits.h"
34 #include "unary.h"
35
36 /**
37  * @file
38  * Monkey's Audio lossless audio decoder
39  */
40
41 #define MAX_CHANNELS        2
42 #define MAX_BYTESPERSAMPLE  3
43
44 #define APE_FRAMECODE_MONO_SILENCE    1
45 #define APE_FRAMECODE_STEREO_SILENCE  3
46 #define APE_FRAMECODE_PSEUDO_STEREO   4
47
48 #define HISTORY_SIZE 512
49 #define PREDICTOR_ORDER 8
50 /** Total size of all predictor histories */
51 #define PREDICTOR_SIZE 50
52
53 #define YDELAYA (18 + PREDICTOR_ORDER*4)
54 #define YDELAYB (18 + PREDICTOR_ORDER*3)
55 #define XDELAYA (18 + PREDICTOR_ORDER*2)
56 #define XDELAYB (18 + PREDICTOR_ORDER)
57
58 #define YADAPTCOEFFSA 18
59 #define XADAPTCOEFFSA 14
60 #define YADAPTCOEFFSB 10
61 #define XADAPTCOEFFSB 5
62
63 /**
64  * Possible compression levels
65  * @{
66  */
67 enum APECompressionLevel {
68     COMPRESSION_LEVEL_FAST       = 1000,
69     COMPRESSION_LEVEL_NORMAL     = 2000,
70     COMPRESSION_LEVEL_HIGH       = 3000,
71     COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
72     COMPRESSION_LEVEL_INSANE     = 5000
73 };
74 /** @} */
75
76 #define APE_FILTER_LEVELS 3
77
78 /** Filter orders depending on compression level */
79 static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
80     {  0,   0,    0 },
81     { 16,   0,    0 },
82     { 64,   0,    0 },
83     { 32, 256,    0 },
84     { 16, 256, 1280 }
85 };
86
87 /** Filter fraction bits depending on compression level */
88 static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
89     {  0,  0,  0 },
90     { 11,  0,  0 },
91     { 11,  0,  0 },
92     { 10, 13,  0 },
93     { 11, 13, 15 }
94 };
95
96
97 /** Filters applied to the decoded data */
98 typedef struct APEFilter {
99     int16_t *coeffs;        ///< actual coefficients used in filtering
100     int16_t *adaptcoeffs;   ///< adaptive filter coefficients used for correcting of actual filter coefficients
101     int16_t *historybuffer; ///< filter memory
102     int16_t *delay;         ///< filtered values
103
104     int avg;
105 } APEFilter;
106
107 typedef struct APERice {
108     uint32_t k;
109     uint32_t ksum;
110 } APERice;
111
112 typedef struct APERangecoder {
113     uint32_t low;           ///< low end of interval
114     uint32_t range;         ///< length of interval
115     uint32_t help;          ///< bytes_to_follow resp. intermediate value
116     unsigned int buffer;    ///< buffer for input/output
117 } APERangecoder;
118
119 /** Filter histories */
120 typedef struct APEPredictor {
121     int32_t *buf;
122
123     int32_t lastA[2];
124
125     int32_t filterA[2];
126     int32_t filterB[2];
127
128     int32_t coeffsA[2][4];  ///< adaption coefficients
129     int32_t coeffsB[2][5];  ///< adaption coefficients
130     int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
131
132     unsigned int sample_pos;
133 } APEPredictor;
134
135 /** Decoder context */
136 typedef struct APEContext {
137     AVClass *class;                          ///< class for AVOptions
138     AVCodecContext *avctx;
139     BswapDSPContext bdsp;
140     APEDSPContext adsp;
141     int channels;
142     int samples;                             ///< samples left to decode in current frame
143     int bps;
144
145     int fileversion;                         ///< codec version, very important in decoding process
146     int compression_level;                   ///< compression levels
147     int fset;                                ///< which filter set to use (calculated from compression level)
148     int flags;                               ///< global decoder flags
149
150     uint32_t CRC;                            ///< frame CRC
151     int frameflags;                          ///< frame flags
152     APEPredictor predictor;                  ///< predictor used for final reconstruction
153
154     int32_t *decoded_buffer;
155     int decoded_size;
156     int32_t *decoded[MAX_CHANNELS];          ///< decoded data for each channel
157     int blocks_per_loop;                     ///< maximum number of samples to decode for each call
158
159     int16_t* filterbuf[APE_FILTER_LEVELS];   ///< filter memory
160
161     APERangecoder rc;                        ///< rangecoder used to decode actual values
162     APERice riceX;                           ///< rice code parameters for the second channel
163     APERice riceY;                           ///< rice code parameters for the first channel
164     APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
165     GetBitContext gb;
166
167     uint8_t *data;                           ///< current frame data
168     uint8_t *data_end;                       ///< frame data end
169     int data_size;                           ///< frame data allocated size
170     const uint8_t *ptr;                      ///< current position in frame data
171
172     int error;
173
174     void (*entropy_decode_mono)(struct APEContext *ctx, int blockstodecode);
175     void (*entropy_decode_stereo)(struct APEContext *ctx, int blockstodecode);
176     void (*predictor_decode_mono)(struct APEContext *ctx, int count);
177     void (*predictor_decode_stereo)(struct APEContext *ctx, int count);
178 } APEContext;
179
180 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
181                               int32_t *decoded1, int count);
182
183 static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode);
184 static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode);
185 static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode);
186 static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode);
187 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode);
188 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode);
189 static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode);
190 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode);
191 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode);
192
193 static void predictor_decode_mono_3800(APEContext *ctx, int count);
194 static void predictor_decode_stereo_3800(APEContext *ctx, int count);
195 static void predictor_decode_mono_3930(APEContext *ctx, int count);
196 static void predictor_decode_stereo_3930(APEContext *ctx, int count);
197 static void predictor_decode_mono_3950(APEContext *ctx, int count);
198 static void predictor_decode_stereo_3950(APEContext *ctx, int count);
199
200 static av_cold int ape_decode_close(AVCodecContext *avctx)
201 {
202     APEContext *s = avctx->priv_data;
203     int i;
204
205     for (i = 0; i < APE_FILTER_LEVELS; i++)
206         av_freep(&s->filterbuf[i]);
207
208     av_freep(&s->decoded_buffer);
209     av_freep(&s->data);
210     s->decoded_size = s->data_size = 0;
211
212     return 0;
213 }
214
215 static int32_t scalarproduct_and_madd_int16_c(int16_t *v1, const int16_t *v2,
216                                               const int16_t *v3,
217                                               int order, int mul)
218 {
219     int res = 0;
220
221     while (order--) {
222         res   += *v1 * *v2++;
223         *v1++ += mul * *v3++;
224     }
225     return res;
226 }
227
228 static av_cold int ape_decode_init(AVCodecContext *avctx)
229 {
230     APEContext *s = avctx->priv_data;
231     int i;
232
233     if (avctx->extradata_size != 6) {
234         av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
235         return AVERROR(EINVAL);
236     }
237     if (avctx->channels > 2) {
238         av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
239         return AVERROR(EINVAL);
240     }
241     s->bps = avctx->bits_per_coded_sample;
242     switch (s->bps) {
243     case 8:
244         avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
245         break;
246     case 16:
247         avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
248         break;
249     case 24:
250         avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
251         break;
252     default:
253         avpriv_request_sample(avctx,
254                               "%d bits per coded sample", s->bps);
255         return AVERROR_PATCHWELCOME;
256     }
257     s->avctx             = avctx;
258     s->channels          = avctx->channels;
259     s->fileversion       = AV_RL16(avctx->extradata);
260     s->compression_level = AV_RL16(avctx->extradata + 2);
261     s->flags             = AV_RL16(avctx->extradata + 4);
262
263     av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n",
264            s->compression_level, s->flags);
265     if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE ||
266         (s->fileversion < 3930 && s->compression_level == COMPRESSION_LEVEL_INSANE)) {
267         av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
268                s->compression_level);
269         return AVERROR_INVALIDDATA;
270     }
271     s->fset = s->compression_level / 1000 - 1;
272     for (i = 0; i < APE_FILTER_LEVELS; i++) {
273         if (!ape_filter_orders[s->fset][i])
274             break;
275         FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
276                          (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
277                          filter_alloc_fail);
278     }
279
280     if (s->fileversion < 3860) {
281         s->entropy_decode_mono   = entropy_decode_mono_0000;
282         s->entropy_decode_stereo = entropy_decode_stereo_0000;
283     } else if (s->fileversion < 3900) {
284         s->entropy_decode_mono   = entropy_decode_mono_3860;
285         s->entropy_decode_stereo = entropy_decode_stereo_3860;
286     } else if (s->fileversion < 3930) {
287         s->entropy_decode_mono   = entropy_decode_mono_3900;
288         s->entropy_decode_stereo = entropy_decode_stereo_3900;
289     } else if (s->fileversion < 3990) {
290         s->entropy_decode_mono   = entropy_decode_mono_3900;
291         s->entropy_decode_stereo = entropy_decode_stereo_3930;
292     } else {
293         s->entropy_decode_mono   = entropy_decode_mono_3990;
294         s->entropy_decode_stereo = entropy_decode_stereo_3990;
295     }
296
297     if (s->fileversion < 3930) {
298         s->predictor_decode_mono   = predictor_decode_mono_3800;
299         s->predictor_decode_stereo = predictor_decode_stereo_3800;
300     } else if (s->fileversion < 3950) {
301         s->predictor_decode_mono   = predictor_decode_mono_3930;
302         s->predictor_decode_stereo = predictor_decode_stereo_3930;
303     } else {
304         s->predictor_decode_mono   = predictor_decode_mono_3950;
305         s->predictor_decode_stereo = predictor_decode_stereo_3950;
306     }
307
308     s->adsp.scalarproduct_and_madd_int16 = scalarproduct_and_madd_int16_c;
309
310     if (ARCH_ARM)
311         ff_apedsp_init_arm(&s->adsp);
312     if (ARCH_PPC)
313         ff_apedsp_init_ppc(&s->adsp);
314     if (ARCH_X86)
315         ff_apedsp_init_x86(&s->adsp);
316
317     ff_bswapdsp_init(&s->bdsp);
318     avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
319
320     return 0;
321 filter_alloc_fail:
322     ape_decode_close(avctx);
323     return AVERROR(ENOMEM);
324 }
325
326 /**
327  * @name APE range decoding functions
328  * @{
329  */
330
331 #define CODE_BITS    32
332 #define TOP_VALUE    ((unsigned int)1 << (CODE_BITS-1))
333 #define SHIFT_BITS   (CODE_BITS - 9)
334 #define EXTRA_BITS   ((CODE_BITS-2) % 8 + 1)
335 #define BOTTOM_VALUE (TOP_VALUE >> 8)
336
337 /** Start the decoder */
338 static inline void range_start_decoding(APEContext *ctx)
339 {
340     ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
341     ctx->rc.low    = ctx->rc.buffer >> (8 - EXTRA_BITS);
342     ctx->rc.range  = (uint32_t) 1 << EXTRA_BITS;
343 }
344
345 /** Perform normalization */
346 static inline void range_dec_normalize(APEContext *ctx)
347 {
348     while (ctx->rc.range <= BOTTOM_VALUE) {
349         ctx->rc.buffer <<= 8;
350         if(ctx->ptr < ctx->data_end) {
351             ctx->rc.buffer += *ctx->ptr;
352             ctx->ptr++;
353         } else {
354             ctx->error = 1;
355         }
356         ctx->rc.low    = (ctx->rc.low << 8)    | ((ctx->rc.buffer >> 1) & 0xFF);
357         ctx->rc.range  <<= 8;
358     }
359 }
360
361 /**
362  * Calculate culmulative frequency for next symbol. Does NO update!
363  * @param ctx decoder context
364  * @param tot_f is the total frequency or (code_value)1<<shift
365  * @return the culmulative frequency
366  */
367 static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
368 {
369     range_dec_normalize(ctx);
370     ctx->rc.help = ctx->rc.range / tot_f;
371     return ctx->rc.low / ctx->rc.help;
372 }
373
374 /**
375  * Decode value with given size in bits
376  * @param ctx decoder context
377  * @param shift number of bits to decode
378  */
379 static inline int range_decode_culshift(APEContext *ctx, int shift)
380 {
381     range_dec_normalize(ctx);
382     ctx->rc.help = ctx->rc.range >> shift;
383     return ctx->rc.low / ctx->rc.help;
384 }
385
386
387 /**
388  * Update decoding state
389  * @param ctx decoder context
390  * @param sy_f the interval length (frequency of the symbol)
391  * @param lt_f the lower end (frequency sum of < symbols)
392  */
393 static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
394 {
395     ctx->rc.low  -= ctx->rc.help * lt_f;
396     ctx->rc.range = ctx->rc.help * sy_f;
397 }
398
399 /** Decode n bits (n <= 16) without modelling */
400 static inline int range_decode_bits(APEContext *ctx, int n)
401 {
402     int sym = range_decode_culshift(ctx, n);
403     range_decode_update(ctx, 1, sym);
404     return sym;
405 }
406
407
408 #define MODEL_ELEMENTS 64
409
410 /**
411  * Fixed probabilities for symbols in Monkey Audio version 3.97
412  */
413 static const uint16_t counts_3970[22] = {
414         0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
415     62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
416     65450, 65469, 65480, 65487, 65491, 65493,
417 };
418
419 /**
420  * Probability ranges for symbols in Monkey Audio version 3.97
421  */
422 static const uint16_t counts_diff_3970[21] = {
423     14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
424     1104, 677, 415, 248, 150, 89, 54, 31,
425     19, 11, 7, 4, 2,
426 };
427
428 /**
429  * Fixed probabilities for symbols in Monkey Audio version 3.98
430  */
431 static const uint16_t counts_3980[22] = {
432         0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
433     64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
434     65485, 65488, 65490, 65491, 65492, 65493,
435 };
436
437 /**
438  * Probability ranges for symbols in Monkey Audio version 3.98
439  */
440 static const uint16_t counts_diff_3980[21] = {
441     19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
442     261, 119, 65, 31, 19, 10, 6, 3,
443     3, 2, 1, 1, 1,
444 };
445
446 /**
447  * Decode symbol
448  * @param ctx decoder context
449  * @param counts probability range start position
450  * @param counts_diff probability range widths
451  */
452 static inline int range_get_symbol(APEContext *ctx,
453                                    const uint16_t counts[],
454                                    const uint16_t counts_diff[])
455 {
456     int symbol, cf;
457
458     cf = range_decode_culshift(ctx, 16);
459
460     if(cf > 65492){
461         symbol= cf - 65535 + 63;
462         range_decode_update(ctx, 1, cf);
463         if(cf > 65535)
464             ctx->error=1;
465         return symbol;
466     }
467     /* figure out the symbol inefficiently; a binary search would be much better */
468     for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
469
470     range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
471
472     return symbol;
473 }
474 /** @} */ // group rangecoder
475
476 static inline void update_rice(APERice *rice, unsigned int x)
477 {
478     int lim = rice->k ? (1 << (rice->k + 4)) : 0;
479     rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
480
481     if (rice->ksum < lim)
482         rice->k--;
483     else if (rice->ksum >= (1 << (rice->k + 5)))
484         rice->k++;
485 }
486
487 static inline int get_rice_ook(GetBitContext *gb, int k)
488 {
489     unsigned int x;
490
491     x = get_unary(gb, 1, get_bits_left(gb));
492
493     if (k)
494         x = (x << k) | get_bits(gb, k);
495
496     return x;
497 }
498
499 static inline int ape_decode_value_3860(APEContext *ctx, GetBitContext *gb,
500                                         APERice *rice)
501 {
502     unsigned int x, overflow;
503
504     overflow = get_unary(gb, 1, get_bits_left(gb));
505
506     if (ctx->fileversion > 3880) {
507         while (overflow >= 16) {
508             overflow -= 16;
509             rice->k  += 4;
510         }
511     }
512
513     if (!rice->k)
514         x = overflow;
515     else
516         x = (overflow << rice->k) + get_bits(gb, rice->k);
517
518     rice->ksum += x - (rice->ksum + 8 >> 4);
519     if (rice->ksum < (rice->k ? 1 << (rice->k + 4) : 0))
520         rice->k--;
521     else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
522         rice->k++;
523
524     /* Convert to signed */
525     if (x & 1)
526         return (x >> 1) + 1;
527     else
528         return -(x >> 1);
529 }
530
531 static inline int ape_decode_value_3900(APEContext *ctx, APERice *rice)
532 {
533     unsigned int x, overflow;
534     int tmpk;
535
536     overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
537
538     if (overflow == (MODEL_ELEMENTS - 1)) {
539         tmpk = range_decode_bits(ctx, 5);
540         overflow = 0;
541     } else
542         tmpk = (rice->k < 1) ? 0 : rice->k - 1;
543
544     if (tmpk <= 16 || ctx->fileversion < 3910)
545         x = range_decode_bits(ctx, tmpk);
546     else if (tmpk <= 32) {
547         x = range_decode_bits(ctx, 16);
548         x |= (range_decode_bits(ctx, tmpk - 16) << 16);
549     } else {
550         av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
551         return AVERROR_INVALIDDATA;
552     }
553     x += overflow << tmpk;
554
555     update_rice(rice, x);
556
557     /* Convert to signed */
558     if (x & 1)
559         return (x >> 1) + 1;
560     else
561         return -(x >> 1);
562 }
563
564 static inline int ape_decode_value_3990(APEContext *ctx, APERice *rice)
565 {
566     unsigned int x, overflow;
567     int base, pivot;
568
569     pivot = rice->ksum >> 5;
570     if (pivot == 0)
571         pivot = 1;
572
573     overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
574
575     if (overflow == (MODEL_ELEMENTS - 1)) {
576         overflow  = range_decode_bits(ctx, 16) << 16;
577         overflow |= range_decode_bits(ctx, 16);
578     }
579
580     if (pivot < 0x10000) {
581         base = range_decode_culfreq(ctx, pivot);
582         range_decode_update(ctx, 1, base);
583     } else {
584         int base_hi = pivot, base_lo;
585         int bbits = 0;
586
587         while (base_hi & ~0xFFFF) {
588             base_hi >>= 1;
589             bbits++;
590         }
591         base_hi = range_decode_culfreq(ctx, base_hi + 1);
592         range_decode_update(ctx, 1, base_hi);
593         base_lo = range_decode_culfreq(ctx, 1 << bbits);
594         range_decode_update(ctx, 1, base_lo);
595
596         base = (base_hi << bbits) + base_lo;
597     }
598
599     x = base + overflow * pivot;
600
601     update_rice(rice, x);
602
603     /* Convert to signed */
604     if (x & 1)
605         return (x >> 1) + 1;
606     else
607         return -(x >> 1);
608 }
609
610 static void decode_array_0000(APEContext *ctx, GetBitContext *gb,
611                               int32_t *out, APERice *rice, int blockstodecode)
612 {
613     int i;
614     int ksummax, ksummin;
615
616     rice->ksum = 0;
617     for (i = 0; i < FFMIN(blockstodecode, 5); i++) {
618         out[i] = get_rice_ook(&ctx->gb, 10);
619         rice->ksum += out[i];
620     }
621     rice->k = av_log2(rice->ksum / 10) + 1;
622     for (; i < FFMIN(blockstodecode, 64); i++) {
623         out[i] = get_rice_ook(&ctx->gb, rice->k);
624         rice->ksum += out[i];
625         rice->k = av_log2(rice->ksum / ((i + 1) * 2)) + 1;
626     }
627     ksummax = 1 << rice->k + 7;
628     ksummin = rice->k ? (1 << rice->k + 6) : 0;
629     for (; i < blockstodecode; i++) {
630         out[i] = get_rice_ook(&ctx->gb, rice->k);
631         rice->ksum += out[i] - out[i - 64];
632         while (rice->ksum < ksummin) {
633             rice->k--;
634             ksummin = rice->k ? ksummin >> 1 : 0;
635             ksummax >>= 1;
636         }
637         while (rice->ksum >= ksummax) {
638             rice->k++;
639             if (rice->k > 24)
640                 return;
641             ksummax <<= 1;
642             ksummin = ksummin ? ksummin << 1 : 128;
643         }
644     }
645
646     for (i = 0; i < blockstodecode; i++) {
647         if (out[i] & 1)
648             out[i] = (out[i] >> 1) + 1;
649         else
650             out[i] = -(out[i] >> 1);
651     }
652 }
653
654 static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode)
655 {
656     decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
657                       blockstodecode);
658 }
659
660 static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode)
661 {
662     decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
663                       blockstodecode);
664     decode_array_0000(ctx, &ctx->gb, ctx->decoded[1], &ctx->riceX,
665                       blockstodecode);
666 }
667
668 static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode)
669 {
670     int32_t *decoded0 = ctx->decoded[0];
671
672     while (blockstodecode--)
673         *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
674 }
675
676 static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode)
677 {
678     int32_t *decoded0 = ctx->decoded[0];
679     int32_t *decoded1 = ctx->decoded[1];
680     int blocks = blockstodecode;
681
682     while (blockstodecode--)
683         *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
684     while (blocks--)
685         *decoded1++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceX);
686 }
687
688 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode)
689 {
690     int32_t *decoded0 = ctx->decoded[0];
691
692     while (blockstodecode--)
693         *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
694 }
695
696 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode)
697 {
698     int32_t *decoded0 = ctx->decoded[0];
699     int32_t *decoded1 = ctx->decoded[1];
700     int blocks = blockstodecode;
701
702     while (blockstodecode--)
703         *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
704     range_dec_normalize(ctx);
705     // because of some implementation peculiarities we need to backpedal here
706     ctx->ptr -= 1;
707     range_start_decoding(ctx);
708     while (blocks--)
709         *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
710 }
711
712 static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode)
713 {
714     int32_t *decoded0 = ctx->decoded[0];
715     int32_t *decoded1 = ctx->decoded[1];
716
717     while (blockstodecode--) {
718         *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
719         *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
720     }
721 }
722
723 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode)
724 {
725     int32_t *decoded0 = ctx->decoded[0];
726
727     while (blockstodecode--)
728         *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
729 }
730
731 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode)
732 {
733     int32_t *decoded0 = ctx->decoded[0];
734     int32_t *decoded1 = ctx->decoded[1];
735
736     while (blockstodecode--) {
737         *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
738         *decoded1++ = ape_decode_value_3990(ctx, &ctx->riceX);
739     }
740 }
741
742 static int init_entropy_decoder(APEContext *ctx)
743 {
744     /* Read the CRC */
745     if (ctx->fileversion >= 3900) {
746         if (ctx->data_end - ctx->ptr < 6)
747             return AVERROR_INVALIDDATA;
748         ctx->CRC = bytestream_get_be32(&ctx->ptr);
749     } else {
750         ctx->CRC = get_bits_long(&ctx->gb, 32);
751     }
752
753     /* Read the frame flags if they exist */
754     ctx->frameflags = 0;
755     if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
756         ctx->CRC &= ~0x80000000;
757
758         if (ctx->data_end - ctx->ptr < 6)
759             return AVERROR_INVALIDDATA;
760         ctx->frameflags = bytestream_get_be32(&ctx->ptr);
761     }
762
763     /* Initialize the rice structs */
764     ctx->riceX.k = 10;
765     ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
766     ctx->riceY.k = 10;
767     ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
768
769     if (ctx->fileversion >= 3900) {
770         /* The first 8 bits of input are ignored. */
771         ctx->ptr++;
772
773         range_start_decoding(ctx);
774     }
775
776     return 0;
777 }
778
779 static const int32_t initial_coeffs_fast_3320[1] = {
780     375,
781 };
782
783 static const int32_t initial_coeffs_a_3800[3] = {
784     64, 115, 64,
785 };
786
787 static const int32_t initial_coeffs_b_3800[2] = {
788     740, 0
789 };
790
791 static const int32_t initial_coeffs_3930[4] = {
792     360, 317, -109, 98
793 };
794
795 static void init_predictor_decoder(APEContext *ctx)
796 {
797     APEPredictor *p = &ctx->predictor;
798
799     /* Zero the history buffers */
800     memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
801     p->buf = p->historybuffer;
802
803     /* Initialize and zero the coefficients */
804     if (ctx->fileversion < 3930) {
805         if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
806             memcpy(p->coeffsA[0], initial_coeffs_fast_3320,
807                    sizeof(initial_coeffs_fast_3320));
808             memcpy(p->coeffsA[1], initial_coeffs_fast_3320,
809                    sizeof(initial_coeffs_fast_3320));
810         } else {
811             memcpy(p->coeffsA[0], initial_coeffs_a_3800,
812                    sizeof(initial_coeffs_a_3800));
813             memcpy(p->coeffsA[1], initial_coeffs_a_3800,
814                    sizeof(initial_coeffs_a_3800));
815         }
816     } else {
817         memcpy(p->coeffsA[0], initial_coeffs_3930, sizeof(initial_coeffs_3930));
818         memcpy(p->coeffsA[1], initial_coeffs_3930, sizeof(initial_coeffs_3930));
819     }
820     memset(p->coeffsB, 0, sizeof(p->coeffsB));
821     if (ctx->fileversion < 3930) {
822         memcpy(p->coeffsB[0], initial_coeffs_b_3800,
823                sizeof(initial_coeffs_b_3800));
824         memcpy(p->coeffsB[1], initial_coeffs_b_3800,
825                sizeof(initial_coeffs_b_3800));
826     }
827
828     p->filterA[0] = p->filterA[1] = 0;
829     p->filterB[0] = p->filterB[1] = 0;
830     p->lastA[0]   = p->lastA[1]   = 0;
831
832     p->sample_pos = 0;
833 }
834
835 /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
836 static inline int APESIGN(int32_t x) {
837     return (x < 0) - (x > 0);
838 }
839
840 static av_always_inline int filter_fast_3320(APEPredictor *p,
841                                              const int decoded, const int filter,
842                                              const int delayA)
843 {
844     int32_t predictionA;
845
846     p->buf[delayA] = p->lastA[filter];
847     if (p->sample_pos < 3) {
848         p->lastA[filter]   = decoded;
849         p->filterA[filter] = decoded;
850         return decoded;
851     }
852
853     predictionA = p->buf[delayA] * 2 - p->buf[delayA - 1];
854     p->lastA[filter] = decoded + (predictionA  * p->coeffsA[filter][0] >> 9);
855
856     if ((decoded ^ predictionA) > 0)
857         p->coeffsA[filter][0]++;
858     else
859         p->coeffsA[filter][0]--;
860
861     p->filterA[filter] += p->lastA[filter];
862
863     return p->filterA[filter];
864 }
865
866 static av_always_inline int filter_3800(APEPredictor *p,
867                                         const int decoded, const int filter,
868                                         const int delayA,  const int delayB,
869                                         const int start,   const int shift)
870 {
871     int32_t predictionA, predictionB, sign;
872     int32_t d0, d1, d2, d3, d4;
873
874     p->buf[delayA] = p->lastA[filter];
875     p->buf[delayB] = p->filterB[filter];
876     if (p->sample_pos < start) {
877         predictionA = decoded + p->filterA[filter];
878         p->lastA[filter]   = decoded;
879         p->filterB[filter] = decoded;
880         p->filterA[filter] = predictionA;
881         return predictionA;
882     }
883     d2 =  p->buf[delayA];
884     d1 = (p->buf[delayA] - p->buf[delayA - 1]) << 1;
885     d0 =  p->buf[delayA] + ((p->buf[delayA - 2] - p->buf[delayA - 1]) << 3);
886     d3 =  p->buf[delayB] * 2 - p->buf[delayB - 1];
887     d4 =  p->buf[delayB];
888
889     predictionA = d0 * p->coeffsA[filter][0] +
890                   d1 * p->coeffsA[filter][1] +
891                   d2 * p->coeffsA[filter][2];
892
893     sign = APESIGN(decoded);
894     p->coeffsA[filter][0] += (((d0 >> 30) & 2) - 1) * sign;
895     p->coeffsA[filter][1] += (((d1 >> 28) & 8) - 4) * sign;
896     p->coeffsA[filter][2] += (((d2 >> 28) & 8) - 4) * sign;
897
898     predictionB = d3 * p->coeffsB[filter][0] -
899                   d4 * p->coeffsB[filter][1];
900     p->lastA[filter] = decoded + (predictionA >> 11);
901     sign = APESIGN(p->lastA[filter]);
902     p->coeffsB[filter][0] += (((d3 >> 29) & 4) - 2) * sign;
903     p->coeffsB[filter][1] -= (((d4 >> 30) & 2) - 1) * sign;
904
905     p->filterB[filter] = p->lastA[filter] + (predictionB >> shift);
906     p->filterA[filter] = p->filterB[filter] + ((p->filterA[filter] * 31) >> 5);
907
908     return p->filterA[filter];
909 }
910
911 static void long_filter_high_3800(int32_t *buffer, int order, int shift,
912                                   int32_t *coeffs, int32_t *delay, int length)
913 {
914     int i, j;
915     int32_t dotprod, sign;
916
917     memset(coeffs, 0, order * sizeof(*coeffs));
918     for (i = 0; i < order; i++)
919         delay[i] = buffer[i];
920     for (i = order; i < length; i++) {
921         dotprod = 0;
922         sign = APESIGN(buffer[i]);
923         for (j = 0; j < order; j++) {
924             dotprod += delay[j] * coeffs[j];
925             coeffs[j] -= (((delay[j] >> 30) & 2) - 1) * sign;
926         }
927         buffer[i] -= dotprod >> shift;
928         for (j = 0; j < order - 1; j++)
929             delay[j] = delay[j + 1];
930         delay[order - 1] = buffer[i];
931     }
932 }
933
934 static void long_filter_ehigh_3830(int32_t *buffer, int length)
935 {
936     int i, j;
937     int32_t dotprod, sign;
938     int32_t coeffs[8] = { 0 }, delay[8] = { 0 };
939
940     for (i = 0; i < length; i++) {
941         dotprod = 0;
942         sign = APESIGN(buffer[i]);
943         for (j = 7; j >= 0; j--) {
944             dotprod += delay[j] * coeffs[j];
945             coeffs[j] -= (((delay[j] >> 30) & 2) - 1) * sign;
946         }
947         for (j = 7; j > 0; j--)
948             delay[j] = delay[j - 1];
949         delay[0] = buffer[i];
950         buffer[i] -= dotprod >> 9;
951     }
952 }
953
954 static void predictor_decode_stereo_3800(APEContext *ctx, int count)
955 {
956     APEPredictor *p = &ctx->predictor;
957     int32_t *decoded0 = ctx->decoded[0];
958     int32_t *decoded1 = ctx->decoded[1];
959     int32_t coeffs[256], delay[256];
960     int start = 4, shift = 10;
961
962     if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
963         start = 16;
964         long_filter_high_3800(decoded0, 16, 9, coeffs, delay, count);
965         long_filter_high_3800(decoded1, 16, 9, coeffs, delay, count);
966     } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
967         int order = 128, shift2 = 11;
968
969         if (ctx->fileversion >= 3830) {
970             order <<= 1;
971             shift++;
972             shift2++;
973             long_filter_ehigh_3830(decoded0 + order, count - order);
974             long_filter_ehigh_3830(decoded1 + order, count - order);
975         }
976         start = order;
977         long_filter_high_3800(decoded0, order, shift2, coeffs, delay, count);
978         long_filter_high_3800(decoded1, order, shift2, coeffs, delay, count);
979     }
980
981     while (count--) {
982         int X = *decoded0, Y = *decoded1;
983         if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
984             *decoded0 = filter_fast_3320(p, Y, 0, YDELAYA);
985             decoded0++;
986             *decoded1 = filter_fast_3320(p, X, 1, XDELAYA);
987             decoded1++;
988         } else {
989             *decoded0 = filter_3800(p, Y, 0, YDELAYA, YDELAYB,
990                                     start, shift);
991             decoded0++;
992             *decoded1 = filter_3800(p, X, 1, XDELAYA, XDELAYB,
993                                     start, shift);
994             decoded1++;
995         }
996
997         /* Combined */
998         p->buf++;
999         p->sample_pos++;
1000
1001         /* Have we filled the history buffer? */
1002         if (p->buf == p->historybuffer + HISTORY_SIZE) {
1003             memmove(p->historybuffer, p->buf,
1004                     PREDICTOR_SIZE * sizeof(*p->historybuffer));
1005             p->buf = p->historybuffer;
1006         }
1007     }
1008 }
1009
1010 static void predictor_decode_mono_3800(APEContext *ctx, int count)
1011 {
1012     APEPredictor *p = &ctx->predictor;
1013     int32_t *decoded0 = ctx->decoded[0];
1014     int32_t coeffs[256], delay[256];
1015     int start = 4, shift = 10;
1016
1017     if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
1018         start = 16;
1019         long_filter_high_3800(decoded0, 16, 9, coeffs, delay, count);
1020     } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
1021         int order = 128, shift2 = 11;
1022
1023         if (ctx->fileversion >= 3830) {
1024             order <<= 1;
1025             shift++;
1026             shift2++;
1027             long_filter_ehigh_3830(decoded0 + order, count - order);
1028         }
1029         start = order;
1030         long_filter_high_3800(decoded0, order, shift2, coeffs, delay, count);
1031     }
1032
1033     while (count--) {
1034         if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
1035             *decoded0 = filter_fast_3320(p, *decoded0, 0, YDELAYA);
1036             decoded0++;
1037         } else {
1038             *decoded0 = filter_3800(p, *decoded0, 0, YDELAYA, YDELAYB,
1039                                     start, shift);
1040             decoded0++;
1041         }
1042
1043         /* Combined */
1044         p->buf++;
1045         p->sample_pos++;
1046
1047         /* Have we filled the history buffer? */
1048         if (p->buf == p->historybuffer + HISTORY_SIZE) {
1049             memmove(p->historybuffer, p->buf,
1050                     PREDICTOR_SIZE * sizeof(*p->historybuffer));
1051             p->buf = p->historybuffer;
1052         }
1053     }
1054 }
1055
1056 static av_always_inline int predictor_update_3930(APEPredictor *p,
1057                                                   const int decoded, const int filter,
1058                                                   const int delayA)
1059 {
1060     int32_t predictionA, sign;
1061     int32_t d0, d1, d2, d3;
1062
1063     p->buf[delayA]     = p->lastA[filter];
1064     d0 = p->buf[delayA    ];
1065     d1 = p->buf[delayA    ] - p->buf[delayA - 1];
1066     d2 = p->buf[delayA - 1] - p->buf[delayA - 2];
1067     d3 = p->buf[delayA - 2] - p->buf[delayA - 3];
1068
1069     predictionA = d0 * p->coeffsA[filter][0] +
1070                   d1 * p->coeffsA[filter][1] +
1071                   d2 * p->coeffsA[filter][2] +
1072                   d3 * p->coeffsA[filter][3];
1073
1074     p->lastA[filter] = decoded + (predictionA >> 9);
1075     p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
1076
1077     sign = APESIGN(decoded);
1078     p->coeffsA[filter][0] += ((d0 < 0) * 2 - 1) * sign;
1079     p->coeffsA[filter][1] += ((d1 < 0) * 2 - 1) * sign;
1080     p->coeffsA[filter][2] += ((d2 < 0) * 2 - 1) * sign;
1081     p->coeffsA[filter][3] += ((d3 < 0) * 2 - 1) * sign;
1082
1083     return p->filterA[filter];
1084 }
1085
1086 static void predictor_decode_stereo_3930(APEContext *ctx, int count)
1087 {
1088     APEPredictor *p = &ctx->predictor;
1089     int32_t *decoded0 = ctx->decoded[0];
1090     int32_t *decoded1 = ctx->decoded[1];
1091
1092     ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1093
1094     while (count--) {
1095         /* Predictor Y */
1096         int Y = *decoded1, X = *decoded0;
1097         *decoded0 = predictor_update_3930(p, Y, 0, YDELAYA);
1098         decoded0++;
1099         *decoded1 = predictor_update_3930(p, X, 1, XDELAYA);
1100         decoded1++;
1101
1102         /* Combined */
1103         p->buf++;
1104
1105         /* Have we filled the history buffer? */
1106         if (p->buf == p->historybuffer + HISTORY_SIZE) {
1107             memmove(p->historybuffer, p->buf,
1108                     PREDICTOR_SIZE * sizeof(*p->historybuffer));
1109             p->buf = p->historybuffer;
1110         }
1111     }
1112 }
1113
1114 static void predictor_decode_mono_3930(APEContext *ctx, int count)
1115 {
1116     APEPredictor *p = &ctx->predictor;
1117     int32_t *decoded0 = ctx->decoded[0];
1118
1119     ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1120
1121     while (count--) {
1122         *decoded0 = predictor_update_3930(p, *decoded0, 0, YDELAYA);
1123         decoded0++;
1124
1125         p->buf++;
1126
1127         /* Have we filled the history buffer? */
1128         if (p->buf == p->historybuffer + HISTORY_SIZE) {
1129             memmove(p->historybuffer, p->buf,
1130                     PREDICTOR_SIZE * sizeof(*p->historybuffer));
1131             p->buf = p->historybuffer;
1132         }
1133     }
1134 }
1135
1136 static av_always_inline int predictor_update_filter(APEPredictor *p,
1137                                                     const int decoded, const int filter,
1138                                                     const int delayA,  const int delayB,
1139                                                     const int adaptA,  const int adaptB)
1140 {
1141     int32_t predictionA, predictionB, sign;
1142
1143     p->buf[delayA]     = p->lastA[filter];
1144     p->buf[adaptA]     = APESIGN(p->buf[delayA]);
1145     p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
1146     p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
1147
1148     predictionA = p->buf[delayA    ] * p->coeffsA[filter][0] +
1149                   p->buf[delayA - 1] * p->coeffsA[filter][1] +
1150                   p->buf[delayA - 2] * p->coeffsA[filter][2] +
1151                   p->buf[delayA - 3] * p->coeffsA[filter][3];
1152
1153     /*  Apply a scaled first-order filter compression */
1154     p->buf[delayB]     = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
1155     p->buf[adaptB]     = APESIGN(p->buf[delayB]);
1156     p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
1157     p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
1158     p->filterB[filter] = p->filterA[filter ^ 1];
1159
1160     predictionB = p->buf[delayB    ] * p->coeffsB[filter][0] +
1161                   p->buf[delayB - 1] * p->coeffsB[filter][1] +
1162                   p->buf[delayB - 2] * p->coeffsB[filter][2] +
1163                   p->buf[delayB - 3] * p->coeffsB[filter][3] +
1164                   p->buf[delayB - 4] * p->coeffsB[filter][4];
1165
1166     p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
1167     p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
1168
1169     sign = APESIGN(decoded);
1170     p->coeffsA[filter][0] += p->buf[adaptA    ] * sign;
1171     p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
1172     p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
1173     p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
1174     p->coeffsB[filter][0] += p->buf[adaptB    ] * sign;
1175     p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
1176     p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
1177     p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
1178     p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
1179
1180     return p->filterA[filter];
1181 }
1182
1183 static void predictor_decode_stereo_3950(APEContext *ctx, int count)
1184 {
1185     APEPredictor *p = &ctx->predictor;
1186     int32_t *decoded0 = ctx->decoded[0];
1187     int32_t *decoded1 = ctx->decoded[1];
1188
1189     ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1190
1191     while (count--) {
1192         /* Predictor Y */
1193         *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
1194                                             YADAPTCOEFFSA, YADAPTCOEFFSB);
1195         decoded0++;
1196         *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
1197                                             XADAPTCOEFFSA, XADAPTCOEFFSB);
1198         decoded1++;
1199
1200         /* Combined */
1201         p->buf++;
1202
1203         /* Have we filled the history buffer? */
1204         if (p->buf == p->historybuffer + HISTORY_SIZE) {
1205             memmove(p->historybuffer, p->buf,
1206                     PREDICTOR_SIZE * sizeof(*p->historybuffer));
1207             p->buf = p->historybuffer;
1208         }
1209     }
1210 }
1211
1212 static void predictor_decode_mono_3950(APEContext *ctx, int count)
1213 {
1214     APEPredictor *p = &ctx->predictor;
1215     int32_t *decoded0 = ctx->decoded[0];
1216     int32_t predictionA, currentA, A, sign;
1217
1218     ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1219
1220     currentA = p->lastA[0];
1221
1222     while (count--) {
1223         A = *decoded0;
1224
1225         p->buf[YDELAYA] = currentA;
1226         p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
1227
1228         predictionA = p->buf[YDELAYA    ] * p->coeffsA[0][0] +
1229                       p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
1230                       p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
1231                       p->buf[YDELAYA - 3] * p->coeffsA[0][3];
1232
1233         currentA = A + (predictionA >> 10);
1234
1235         p->buf[YADAPTCOEFFSA]     = APESIGN(p->buf[YDELAYA    ]);
1236         p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
1237
1238         sign = APESIGN(A);
1239         p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA    ] * sign;
1240         p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
1241         p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
1242         p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
1243
1244         p->buf++;
1245
1246         /* Have we filled the history buffer? */
1247         if (p->buf == p->historybuffer + HISTORY_SIZE) {
1248             memmove(p->historybuffer, p->buf,
1249                     PREDICTOR_SIZE * sizeof(*p->historybuffer));
1250             p->buf = p->historybuffer;
1251         }
1252
1253         p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
1254         *(decoded0++) = p->filterA[0];
1255     }
1256
1257     p->lastA[0] = currentA;
1258 }
1259
1260 static void do_init_filter(APEFilter *f, int16_t *buf, int order)
1261 {
1262     f->coeffs = buf;
1263     f->historybuffer = buf + order;
1264     f->delay       = f->historybuffer + order * 2;
1265     f->adaptcoeffs = f->historybuffer + order;
1266
1267     memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
1268     memset(f->coeffs, 0, order * sizeof(*f->coeffs));
1269     f->avg = 0;
1270 }
1271
1272 static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
1273 {
1274     do_init_filter(&f[0], buf, order);
1275     do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
1276 }
1277
1278 static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
1279                             int32_t *data, int count, int order, int fracbits)
1280 {
1281     int res;
1282     int absres;
1283
1284     while (count--) {
1285         /* round fixedpoint scalar product */
1286         res = ctx->adsp.scalarproduct_and_madd_int16(f->coeffs,
1287                                                      f->delay - order,
1288                                                      f->adaptcoeffs - order,
1289                                                      order, APESIGN(*data));
1290         res = (res + (1 << (fracbits - 1))) >> fracbits;
1291         res += *data;
1292         *data++ = res;
1293
1294         /* Update the output history */
1295         *f->delay++ = av_clip_int16(res);
1296
1297         if (version < 3980) {
1298             /* Version ??? to < 3.98 files (untested) */
1299             f->adaptcoeffs[0]  = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
1300             f->adaptcoeffs[-4] >>= 1;
1301             f->adaptcoeffs[-8] >>= 1;
1302         } else {
1303             /* Version 3.98 and later files */
1304
1305             /* Update the adaption coefficients */
1306             absres = FFABS(res);
1307             if (absres)
1308                 *f->adaptcoeffs = ((res & (-1<<31)) ^ (-1<<30)) >>
1309                                   (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
1310             else
1311                 *f->adaptcoeffs = 0;
1312
1313             f->avg += (absres - f->avg) / 16;
1314
1315             f->adaptcoeffs[-1] >>= 1;
1316             f->adaptcoeffs[-2] >>= 1;
1317             f->adaptcoeffs[-8] >>= 1;
1318         }
1319
1320         f->adaptcoeffs++;
1321
1322         /* Have we filled the history buffer? */
1323         if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
1324             memmove(f->historybuffer, f->delay - (order * 2),
1325                     (order * 2) * sizeof(*f->historybuffer));
1326             f->delay = f->historybuffer + order * 2;
1327             f->adaptcoeffs = f->historybuffer + order;
1328         }
1329     }
1330 }
1331
1332 static void apply_filter(APEContext *ctx, APEFilter *f,
1333                          int32_t *data0, int32_t *data1,
1334                          int count, int order, int fracbits)
1335 {
1336     do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
1337     if (data1)
1338         do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
1339 }
1340
1341 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
1342                               int32_t *decoded1, int count)
1343 {
1344     int i;
1345
1346     for (i = 0; i < APE_FILTER_LEVELS; i++) {
1347         if (!ape_filter_orders[ctx->fset][i])
1348             break;
1349         apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
1350                      ape_filter_orders[ctx->fset][i],
1351                      ape_filter_fracbits[ctx->fset][i]);
1352     }
1353 }
1354
1355 static int init_frame_decoder(APEContext *ctx)
1356 {
1357     int i, ret;
1358     if ((ret = init_entropy_decoder(ctx)) < 0)
1359         return ret;
1360     init_predictor_decoder(ctx);
1361
1362     for (i = 0; i < APE_FILTER_LEVELS; i++) {
1363         if (!ape_filter_orders[ctx->fset][i])
1364             break;
1365         init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
1366                     ape_filter_orders[ctx->fset][i]);
1367     }
1368     return 0;
1369 }
1370
1371 static void ape_unpack_mono(APEContext *ctx, int count)
1372 {
1373     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
1374         /* We are pure silence, so we're done. */
1375         av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
1376         return;
1377     }
1378
1379     ctx->entropy_decode_mono(ctx, count);
1380
1381     /* Now apply the predictor decoding */
1382     ctx->predictor_decode_mono(ctx, count);
1383
1384     /* Pseudo-stereo - just copy left channel to right channel */
1385     if (ctx->channels == 2) {
1386         memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
1387     }
1388 }
1389
1390 static void ape_unpack_stereo(APEContext *ctx, int count)
1391 {
1392     int32_t left, right;
1393     int32_t *decoded0 = ctx->decoded[0];
1394     int32_t *decoded1 = ctx->decoded[1];
1395
1396     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
1397         /* We are pure silence, so we're done. */
1398         av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
1399         return;
1400     }
1401
1402     ctx->entropy_decode_stereo(ctx, count);
1403
1404     /* Now apply the predictor decoding */
1405     ctx->predictor_decode_stereo(ctx, count);
1406
1407     /* Decorrelate and scale to output depth */
1408     while (count--) {
1409         left = *decoded1 - (*decoded0 / 2);
1410         right = left + *decoded0;
1411
1412         *(decoded0++) = left;
1413         *(decoded1++) = right;
1414     }
1415 }
1416
1417 static int ape_decode_frame(AVCodecContext *avctx, void *data,
1418                             int *got_frame_ptr, AVPacket *avpkt)
1419 {
1420     AVFrame *frame     = data;
1421     const uint8_t *buf = avpkt->data;
1422     APEContext *s = avctx->priv_data;
1423     uint8_t *sample8;
1424     int16_t *sample16;
1425     int32_t *sample24;
1426     int i, ch, ret;
1427     int blockstodecode;
1428
1429     /* this should never be negative, but bad things will happen if it is, so
1430        check it just to make sure. */
1431     av_assert0(s->samples >= 0);
1432
1433     if(!s->samples){
1434         uint32_t nblocks, offset;
1435         int buf_size;
1436
1437         if (!avpkt->size) {
1438             *got_frame_ptr = 0;
1439             return 0;
1440         }
1441         if (avpkt->size < 8) {
1442             av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1443             return AVERROR_INVALIDDATA;
1444         }
1445         buf_size = avpkt->size & ~3;
1446         if (buf_size != avpkt->size) {
1447             av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
1448                    "extra bytes at the end will be skipped.\n");
1449         }
1450         if (s->fileversion < 3950) // previous versions overread two bytes
1451             buf_size += 2;
1452         av_fast_malloc(&s->data, &s->data_size, buf_size);
1453         if (!s->data)
1454             return AVERROR(ENOMEM);
1455         s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,
1456                           buf_size >> 2);
1457         memset(s->data + (buf_size & ~3), 0, buf_size & 3);
1458         s->ptr = s->data;
1459         s->data_end = s->data + buf_size;
1460
1461         nblocks = bytestream_get_be32(&s->ptr);
1462         offset  = bytestream_get_be32(&s->ptr);
1463         if (s->fileversion >= 3900) {
1464             if (offset > 3) {
1465                 av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
1466                 s->data = NULL;
1467                 return AVERROR_INVALIDDATA;
1468             }
1469             if (s->data_end - s->ptr < offset) {
1470                 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1471                 return AVERROR_INVALIDDATA;
1472             }
1473             s->ptr += offset;
1474         } else {
1475             init_get_bits(&s->gb, s->ptr, (s->data_end - s->ptr) * 8);
1476             if (s->fileversion > 3800)
1477                 skip_bits_long(&s->gb, offset * 8);
1478             else
1479                 skip_bits_long(&s->gb, offset);
1480         }
1481
1482         if (!nblocks || nblocks > INT_MAX) {
1483             av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n",
1484                    nblocks);
1485             return AVERROR_INVALIDDATA;
1486         }
1487         s->samples = nblocks;
1488
1489         /* Initialize the frame decoder */
1490         if (init_frame_decoder(s) < 0) {
1491             av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
1492             return AVERROR_INVALIDDATA;
1493         }
1494
1495     }
1496
1497     if (!s->data) {
1498         *got_frame_ptr = 0;
1499         return avpkt->size;
1500     }
1501
1502     blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
1503     // for old files coefficients were not interleaved,
1504     // so we need to decode all of them at once
1505     if (s->fileversion < 3930)
1506         blockstodecode = s->samples;
1507
1508     /* reallocate decoded sample buffer if needed */
1509     av_fast_malloc(&s->decoded_buffer, &s->decoded_size,
1510                    2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));
1511     if (!s->decoded_buffer)
1512         return AVERROR(ENOMEM);
1513     memset(s->decoded_buffer, 0, s->decoded_size);
1514     s->decoded[0] = s->decoded_buffer;
1515     s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
1516
1517     /* get output buffer */
1518     frame->nb_samples = blockstodecode;
1519     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
1520         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1521         return ret;
1522     }
1523
1524     s->error=0;
1525
1526     if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
1527         ape_unpack_mono(s, blockstodecode);
1528     else
1529         ape_unpack_stereo(s, blockstodecode);
1530     emms_c();
1531
1532     if (s->error) {
1533         s->samples=0;
1534         av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
1535         return AVERROR_INVALIDDATA;
1536     }
1537
1538     switch (s->bps) {
1539     case 8:
1540         for (ch = 0; ch < s->channels; ch++) {
1541             sample8 = (uint8_t *)frame->data[ch];
1542             for (i = 0; i < blockstodecode; i++)
1543                 *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
1544         }
1545         break;
1546     case 16:
1547         for (ch = 0; ch < s->channels; ch++) {
1548             sample16 = (int16_t *)frame->data[ch];
1549             for (i = 0; i < blockstodecode; i++)
1550                 *sample16++ = s->decoded[ch][i];
1551         }
1552         break;
1553     case 24:
1554         for (ch = 0; ch < s->channels; ch++) {
1555             sample24 = (int32_t *)frame->data[ch];
1556             for (i = 0; i < blockstodecode; i++)
1557                 *sample24++ = s->decoded[ch][i] << 8;
1558         }
1559         break;
1560     }
1561
1562     s->samples -= blockstodecode;
1563
1564     *got_frame_ptr = 1;
1565
1566     return (s->samples == 0) ? avpkt->size : 0;
1567 }
1568
1569 static void ape_flush(AVCodecContext *avctx)
1570 {
1571     APEContext *s = avctx->priv_data;
1572     s->samples= 0;
1573 }
1574
1575 #define OFFSET(x) offsetof(APEContext, x)
1576 #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
1577 static const AVOption options[] = {
1578     { "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" },
1579     { "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" },
1580     { NULL},
1581 };
1582
1583 static const AVClass ape_decoder_class = {
1584     .class_name = "APE decoder",
1585     .item_name  = av_default_item_name,
1586     .option     = options,
1587     .version    = LIBAVUTIL_VERSION_INT,
1588 };
1589
1590 AVCodec ff_ape_decoder = {
1591     .name           = "ape",
1592     .long_name      = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
1593     .type           = AVMEDIA_TYPE_AUDIO,
1594     .id             = AV_CODEC_ID_APE,
1595     .priv_data_size = sizeof(APEContext),
1596     .init           = ape_decode_init,
1597     .close          = ape_decode_close,
1598     .decode         = ape_decode_frame,
1599     .capabilities   = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DELAY |
1600                       AV_CODEC_CAP_DR1,
1601     .flush          = ape_flush,
1602     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
1603                                                       AV_SAMPLE_FMT_S16P,
1604                                                       AV_SAMPLE_FMT_S32P,
1605                                                       AV_SAMPLE_FMT_NONE },
1606     .priv_class     = &ape_decoder_class,
1607 };