]> git.sesse.net Git - ffmpeg/blob - libavcodec/apedec.c
apedec: do not set s->samples until after validation.
[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 #define ALT_BITSTREAM_READER_LE
24 #include "avcodec.h"
25 #include "dsputil.h"
26 #include "get_bits.h"
27 #include "bytestream.h"
28 #include "libavutil/audioconvert.h"
29
30 /**
31  * @file
32  * Monkey's Audio lossless audio decoder
33  */
34
35 #define BLOCKS_PER_LOOP     4608
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     AVCodecContext *avctx;
131     DSPContext dsp;
132     int channels;
133     int samples;                             ///< samples left to decode in current frame
134
135     int fileversion;                         ///< codec version, very important in decoding process
136     int compression_level;                   ///< compression levels
137     int fset;                                ///< which filter set to use (calculated from compression level)
138     int flags;                               ///< global decoder flags
139
140     uint32_t CRC;                            ///< frame CRC
141     int frameflags;                          ///< frame flags
142     int currentframeblocks;                  ///< samples (per channel) in current frame
143     int blocksdecoded;                       ///< count of decoded samples in current frame
144     APEPredictor predictor;                  ///< predictor used for final reconstruction
145
146     int32_t decoded0[BLOCKS_PER_LOOP];       ///< decoded data for the first channel
147     int32_t decoded1[BLOCKS_PER_LOOP];       ///< decoded data for the second channel
148
149     int16_t* filterbuf[APE_FILTER_LEVELS];   ///< filter memory
150
151     APERangecoder rc;                        ///< rangecoder used to decode actual values
152     APERice riceX;                           ///< rice code parameters for the second channel
153     APERice riceY;                           ///< rice code parameters for the first channel
154     APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
155
156     uint8_t *data;                           ///< current frame data
157     uint8_t *data_end;                       ///< frame data end
158     const uint8_t *ptr;                      ///< current position in frame data
159     const uint8_t *last_ptr;                 ///< position where last 4608-sample block ended
160
161     int error;
162 } APEContext;
163
164 // TODO: dsputilize
165
166 static av_cold int ape_decode_close(AVCodecContext *avctx)
167 {
168     APEContext *s = avctx->priv_data;
169     int i;
170
171     for (i = 0; i < APE_FILTER_LEVELS; i++)
172         av_freep(&s->filterbuf[i]);
173
174     av_freep(&s->data);
175     return 0;
176 }
177
178 static av_cold int ape_decode_init(AVCodecContext *avctx)
179 {
180     APEContext *s = avctx->priv_data;
181     int i;
182
183     if (avctx->extradata_size != 6) {
184         av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
185         return AVERROR(EINVAL);
186     }
187     if (avctx->bits_per_coded_sample != 16) {
188         av_log(avctx, AV_LOG_ERROR, "Only 16-bit samples are supported\n");
189         return AVERROR(EINVAL);
190     }
191     if (avctx->channels > 2) {
192         av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
193         return AVERROR(EINVAL);
194     }
195     s->avctx             = avctx;
196     s->channels          = avctx->channels;
197     s->fileversion       = AV_RL16(avctx->extradata);
198     s->compression_level = AV_RL16(avctx->extradata + 2);
199     s->flags             = AV_RL16(avctx->extradata + 4);
200
201     av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n",
202            s->compression_level, s->flags);
203     if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE) {
204         av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
205                s->compression_level);
206         return AVERROR_INVALIDDATA;
207     }
208     s->fset = s->compression_level / 1000 - 1;
209     for (i = 0; i < APE_FILTER_LEVELS; i++) {
210         if (!ape_filter_orders[s->fset][i])
211             break;
212         FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
213                          (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
214                          filter_alloc_fail);
215     }
216
217     dsputil_init(&s->dsp, avctx);
218     avctx->sample_fmt = AV_SAMPLE_FMT_S16;
219     avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
220     return 0;
221 filter_alloc_fail:
222     ape_decode_close(avctx);
223     return AVERROR(ENOMEM);
224 }
225
226 /**
227  * @name APE range decoding functions
228  * @{
229  */
230
231 #define CODE_BITS    32
232 #define TOP_VALUE    ((unsigned int)1 << (CODE_BITS-1))
233 #define SHIFT_BITS   (CODE_BITS - 9)
234 #define EXTRA_BITS   ((CODE_BITS-2) % 8 + 1)
235 #define BOTTOM_VALUE (TOP_VALUE >> 8)
236
237 /** Start the decoder */
238 static inline void range_start_decoding(APEContext *ctx)
239 {
240     ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
241     ctx->rc.low    = ctx->rc.buffer >> (8 - EXTRA_BITS);
242     ctx->rc.range  = (uint32_t) 1 << EXTRA_BITS;
243 }
244
245 /** Perform normalization */
246 static inline void range_dec_normalize(APEContext *ctx)
247 {
248     while (ctx->rc.range <= BOTTOM_VALUE) {
249         ctx->rc.buffer <<= 8;
250         if(ctx->ptr < ctx->data_end)
251             ctx->rc.buffer += *ctx->ptr;
252         ctx->ptr++;
253         ctx->rc.low    = (ctx->rc.low << 8)    | ((ctx->rc.buffer >> 1) & 0xFF);
254         ctx->rc.range  <<= 8;
255     }
256 }
257
258 /**
259  * Calculate culmulative frequency for next symbol. Does NO update!
260  * @param ctx decoder context
261  * @param tot_f is the total frequency or (code_value)1<<shift
262  * @return the culmulative frequency
263  */
264 static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
265 {
266     range_dec_normalize(ctx);
267     ctx->rc.help = ctx->rc.range / tot_f;
268     return ctx->rc.low / ctx->rc.help;
269 }
270
271 /**
272  * Decode value with given size in bits
273  * @param ctx decoder context
274  * @param shift number of bits to decode
275  */
276 static inline int range_decode_culshift(APEContext *ctx, int shift)
277 {
278     range_dec_normalize(ctx);
279     ctx->rc.help = ctx->rc.range >> shift;
280     return ctx->rc.low / ctx->rc.help;
281 }
282
283
284 /**
285  * Update decoding state
286  * @param ctx decoder context
287  * @param sy_f the interval length (frequency of the symbol)
288  * @param lt_f the lower end (frequency sum of < symbols)
289  */
290 static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
291 {
292     ctx->rc.low  -= ctx->rc.help * lt_f;
293     ctx->rc.range = ctx->rc.help * sy_f;
294 }
295
296 /** Decode n bits (n <= 16) without modelling */
297 static inline int range_decode_bits(APEContext *ctx, int n)
298 {
299     int sym = range_decode_culshift(ctx, n);
300     range_decode_update(ctx, 1, sym);
301     return sym;
302 }
303
304
305 #define MODEL_ELEMENTS 64
306
307 /**
308  * Fixed probabilities for symbols in Monkey Audio version 3.97
309  */
310 static const uint16_t counts_3970[22] = {
311         0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
312     62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
313     65450, 65469, 65480, 65487, 65491, 65493,
314 };
315
316 /**
317  * Probability ranges for symbols in Monkey Audio version 3.97
318  */
319 static const uint16_t counts_diff_3970[21] = {
320     14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
321     1104, 677, 415, 248, 150, 89, 54, 31,
322     19, 11, 7, 4, 2,
323 };
324
325 /**
326  * Fixed probabilities for symbols in Monkey Audio version 3.98
327  */
328 static const uint16_t counts_3980[22] = {
329         0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
330     64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
331     65485, 65488, 65490, 65491, 65492, 65493,
332 };
333
334 /**
335  * Probability ranges for symbols in Monkey Audio version 3.98
336  */
337 static const uint16_t counts_diff_3980[21] = {
338     19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
339     261, 119, 65, 31, 19, 10, 6, 3,
340     3, 2, 1, 1, 1,
341 };
342
343 /**
344  * Decode symbol
345  * @param ctx decoder context
346  * @param counts probability range start position
347  * @param counts_diff probability range widths
348  */
349 static inline int range_get_symbol(APEContext *ctx,
350                                    const uint16_t counts[],
351                                    const uint16_t counts_diff[])
352 {
353     int symbol, cf;
354
355     cf = range_decode_culshift(ctx, 16);
356
357     if(cf > 65492){
358         symbol= cf - 65535 + 63;
359         range_decode_update(ctx, 1, cf);
360         if(cf > 65535)
361             ctx->error=1;
362         return symbol;
363     }
364     /* figure out the symbol inefficiently; a binary search would be much better */
365     for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
366
367     range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
368
369     return symbol;
370 }
371 /** @} */ // group rangecoder
372
373 static inline void update_rice(APERice *rice, int x)
374 {
375     int lim = rice->k ? (1 << (rice->k + 4)) : 0;
376     rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
377
378     if (rice->ksum < lim)
379         rice->k--;
380     else if (rice->ksum >= (1 << (rice->k + 5)))
381         rice->k++;
382 }
383
384 static inline int ape_decode_value(APEContext *ctx, APERice *rice)
385 {
386     int x, overflow;
387
388     if (ctx->fileversion < 3990) {
389         int tmpk;
390
391         overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
392
393         if (overflow == (MODEL_ELEMENTS - 1)) {
394             tmpk = range_decode_bits(ctx, 5);
395             overflow = 0;
396         } else
397             tmpk = (rice->k < 1) ? 0 : rice->k - 1;
398
399         if (tmpk <= 16)
400             x = range_decode_bits(ctx, tmpk);
401         else {
402             x = range_decode_bits(ctx, 16);
403             x |= (range_decode_bits(ctx, tmpk - 16) << 16);
404         }
405         x += overflow << tmpk;
406     } else {
407         int base, pivot;
408
409         pivot = rice->ksum >> 5;
410         if (pivot == 0)
411             pivot = 1;
412
413         overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
414
415         if (overflow == (MODEL_ELEMENTS - 1)) {
416             overflow  = range_decode_bits(ctx, 16) << 16;
417             overflow |= range_decode_bits(ctx, 16);
418         }
419
420         if (pivot < 0x10000) {
421             base = range_decode_culfreq(ctx, pivot);
422             range_decode_update(ctx, 1, base);
423         } else {
424             int base_hi = pivot, base_lo;
425             int bbits = 0;
426
427             while (base_hi & ~0xFFFF) {
428                 base_hi >>= 1;
429                 bbits++;
430             }
431             base_hi = range_decode_culfreq(ctx, base_hi + 1);
432             range_decode_update(ctx, 1, base_hi);
433             base_lo = range_decode_culfreq(ctx, 1 << bbits);
434             range_decode_update(ctx, 1, base_lo);
435
436             base = (base_hi << bbits) + base_lo;
437         }
438
439         x = base + overflow * pivot;
440     }
441
442     update_rice(rice, x);
443
444     /* Convert to signed */
445     if (x & 1)
446         return (x >> 1) + 1;
447     else
448         return -(x >> 1);
449 }
450
451 static void entropy_decode(APEContext *ctx, int blockstodecode, int stereo)
452 {
453     int32_t *decoded0 = ctx->decoded0;
454     int32_t *decoded1 = ctx->decoded1;
455
456     ctx->blocksdecoded = blockstodecode;
457
458     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
459         /* We are pure silence, just memset the output buffer. */
460         memset(decoded0, 0, blockstodecode * sizeof(int32_t));
461         memset(decoded1, 0, blockstodecode * sizeof(int32_t));
462     } else {
463         while (blockstodecode--) {
464             *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
465             if (stereo)
466                 *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
467         }
468     }
469
470     if (ctx->blocksdecoded == ctx->currentframeblocks)
471         range_dec_normalize(ctx);   /* normalize to use up all bytes */
472 }
473
474 static void init_entropy_decoder(APEContext *ctx)
475 {
476     /* Read the CRC */
477     ctx->CRC = bytestream_get_be32(&ctx->ptr);
478
479     /* Read the frame flags if they exist */
480     ctx->frameflags = 0;
481     if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
482         ctx->CRC &= ~0x80000000;
483
484         ctx->frameflags = bytestream_get_be32(&ctx->ptr);
485     }
486
487     /* Keep a count of the blocks decoded in this frame */
488     ctx->blocksdecoded = 0;
489
490     /* Initialize the rice structs */
491     ctx->riceX.k = 10;
492     ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
493     ctx->riceY.k = 10;
494     ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
495
496     /* The first 8 bits of input are ignored. */
497     ctx->ptr++;
498
499     range_start_decoding(ctx);
500 }
501
502 static const int32_t initial_coeffs[4] = {
503     360, 317, -109, 98
504 };
505
506 static void init_predictor_decoder(APEContext *ctx)
507 {
508     APEPredictor *p = &ctx->predictor;
509
510     /* Zero the history buffers */
511     memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(int32_t));
512     p->buf = p->historybuffer;
513
514     /* Initialize and zero the coefficients */
515     memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
516     memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
517     memset(p->coeffsB, 0, sizeof(p->coeffsB));
518
519     p->filterA[0] = p->filterA[1] = 0;
520     p->filterB[0] = p->filterB[1] = 0;
521     p->lastA[0]   = p->lastA[1]   = 0;
522 }
523
524 /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
525 static inline int APESIGN(int32_t x) {
526     return (x < 0) - (x > 0);
527 }
528
529 static av_always_inline int predictor_update_filter(APEPredictor *p,
530                                                     const int decoded, const int filter,
531                                                     const int delayA,  const int delayB,
532                                                     const int adaptA,  const int adaptB)
533 {
534     int32_t predictionA, predictionB, sign;
535
536     p->buf[delayA]     = p->lastA[filter];
537     p->buf[adaptA]     = APESIGN(p->buf[delayA]);
538     p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
539     p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
540
541     predictionA = p->buf[delayA    ] * p->coeffsA[filter][0] +
542                   p->buf[delayA - 1] * p->coeffsA[filter][1] +
543                   p->buf[delayA - 2] * p->coeffsA[filter][2] +
544                   p->buf[delayA - 3] * p->coeffsA[filter][3];
545
546     /*  Apply a scaled first-order filter compression */
547     p->buf[delayB]     = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
548     p->buf[adaptB]     = APESIGN(p->buf[delayB]);
549     p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
550     p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
551     p->filterB[filter] = p->filterA[filter ^ 1];
552
553     predictionB = p->buf[delayB    ] * p->coeffsB[filter][0] +
554                   p->buf[delayB - 1] * p->coeffsB[filter][1] +
555                   p->buf[delayB - 2] * p->coeffsB[filter][2] +
556                   p->buf[delayB - 3] * p->coeffsB[filter][3] +
557                   p->buf[delayB - 4] * p->coeffsB[filter][4];
558
559     p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
560     p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
561
562     sign = APESIGN(decoded);
563     p->coeffsA[filter][0] += p->buf[adaptA    ] * sign;
564     p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
565     p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
566     p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
567     p->coeffsB[filter][0] += p->buf[adaptB    ] * sign;
568     p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
569     p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
570     p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
571     p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
572
573     return p->filterA[filter];
574 }
575
576 static void predictor_decode_stereo(APEContext *ctx, int count)
577 {
578     APEPredictor *p = &ctx->predictor;
579     int32_t *decoded0 = ctx->decoded0;
580     int32_t *decoded1 = ctx->decoded1;
581
582     while (count--) {
583         /* Predictor Y */
584         *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
585                                             YADAPTCOEFFSA, YADAPTCOEFFSB);
586         decoded0++;
587         *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
588                                             XADAPTCOEFFSA, XADAPTCOEFFSB);
589         decoded1++;
590
591         /* Combined */
592         p->buf++;
593
594         /* Have we filled the history buffer? */
595         if (p->buf == p->historybuffer + HISTORY_SIZE) {
596             memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
597             p->buf = p->historybuffer;
598         }
599     }
600 }
601
602 static void predictor_decode_mono(APEContext *ctx, int count)
603 {
604     APEPredictor *p = &ctx->predictor;
605     int32_t *decoded0 = ctx->decoded0;
606     int32_t predictionA, currentA, A, sign;
607
608     currentA = p->lastA[0];
609
610     while (count--) {
611         A = *decoded0;
612
613         p->buf[YDELAYA] = currentA;
614         p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
615
616         predictionA = p->buf[YDELAYA    ] * p->coeffsA[0][0] +
617                       p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
618                       p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
619                       p->buf[YDELAYA - 3] * p->coeffsA[0][3];
620
621         currentA = A + (predictionA >> 10);
622
623         p->buf[YADAPTCOEFFSA]     = APESIGN(p->buf[YDELAYA    ]);
624         p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
625
626         sign = APESIGN(A);
627         p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA    ] * sign;
628         p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
629         p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
630         p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
631
632         p->buf++;
633
634         /* Have we filled the history buffer? */
635         if (p->buf == p->historybuffer + HISTORY_SIZE) {
636             memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
637             p->buf = p->historybuffer;
638         }
639
640         p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
641         *(decoded0++) = p->filterA[0];
642     }
643
644     p->lastA[0] = currentA;
645 }
646
647 static void do_init_filter(APEFilter *f, int16_t *buf, int order)
648 {
649     f->coeffs = buf;
650     f->historybuffer = buf + order;
651     f->delay       = f->historybuffer + order * 2;
652     f->adaptcoeffs = f->historybuffer + order;
653
654     memset(f->historybuffer, 0, (order * 2) * sizeof(int16_t));
655     memset(f->coeffs, 0, order * sizeof(int16_t));
656     f->avg = 0;
657 }
658
659 static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
660 {
661     do_init_filter(&f[0], buf, order);
662     do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
663 }
664
665 static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
666                             int32_t *data, int count, int order, int fracbits)
667 {
668     int res;
669     int absres;
670
671     while (count--) {
672         /* round fixedpoint scalar product */
673         res = ctx->dsp.scalarproduct_and_madd_int16(f->coeffs, f->delay - order,
674                                                     f->adaptcoeffs - order,
675                                                     order, APESIGN(*data));
676         res = (res + (1 << (fracbits - 1))) >> fracbits;
677         res += *data;
678         *data++ = res;
679
680         /* Update the output history */
681         *f->delay++ = av_clip_int16(res);
682
683         if (version < 3980) {
684             /* Version ??? to < 3.98 files (untested) */
685             f->adaptcoeffs[0]  = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
686             f->adaptcoeffs[-4] >>= 1;
687             f->adaptcoeffs[-8] >>= 1;
688         } else {
689             /* Version 3.98 and later files */
690
691             /* Update the adaption coefficients */
692             absres = FFABS(res);
693             if (absres)
694                 *f->adaptcoeffs = ((res & (1<<31)) - (1<<30)) >>
695                                   (25 + (absres <= f->avg*3) + (absres <= f->avg*4/3));
696             else
697                 *f->adaptcoeffs = 0;
698
699             f->avg += (absres - f->avg) / 16;
700
701             f->adaptcoeffs[-1] >>= 1;
702             f->adaptcoeffs[-2] >>= 1;
703             f->adaptcoeffs[-8] >>= 1;
704         }
705
706         f->adaptcoeffs++;
707
708         /* Have we filled the history buffer? */
709         if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
710             memmove(f->historybuffer, f->delay - (order * 2),
711                     (order * 2) * sizeof(int16_t));
712             f->delay = f->historybuffer + order * 2;
713             f->adaptcoeffs = f->historybuffer + order;
714         }
715     }
716 }
717
718 static void apply_filter(APEContext *ctx, APEFilter *f,
719                          int32_t *data0, int32_t *data1,
720                          int count, int order, int fracbits)
721 {
722     do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
723     if (data1)
724         do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
725 }
726
727 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
728                               int32_t *decoded1, int count)
729 {
730     int i;
731
732     for (i = 0; i < APE_FILTER_LEVELS; i++) {
733         if (!ape_filter_orders[ctx->fset][i])
734             break;
735         apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
736                      ape_filter_orders[ctx->fset][i],
737                      ape_filter_fracbits[ctx->fset][i]);
738     }
739 }
740
741 static void init_frame_decoder(APEContext *ctx)
742 {
743     int i;
744     init_entropy_decoder(ctx);
745     init_predictor_decoder(ctx);
746
747     for (i = 0; i < APE_FILTER_LEVELS; i++) {
748         if (!ape_filter_orders[ctx->fset][i])
749             break;
750         init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
751                     ape_filter_orders[ctx->fset][i]);
752     }
753 }
754
755 static void ape_unpack_mono(APEContext *ctx, int count)
756 {
757     int32_t *decoded0 = ctx->decoded0;
758     int32_t *decoded1 = ctx->decoded1;
759
760     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
761         entropy_decode(ctx, count, 0);
762         /* We are pure silence, so we're done. */
763         av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
764         return;
765     }
766
767     entropy_decode(ctx, count, 0);
768     ape_apply_filters(ctx, decoded0, NULL, count);
769
770     /* Now apply the predictor decoding */
771     predictor_decode_mono(ctx, count);
772
773     /* Pseudo-stereo - just copy left channel to right channel */
774     if (ctx->channels == 2) {
775         memcpy(decoded1, decoded0, count * sizeof(*decoded1));
776     }
777 }
778
779 static void ape_unpack_stereo(APEContext *ctx, int count)
780 {
781     int32_t left, right;
782     int32_t *decoded0 = ctx->decoded0;
783     int32_t *decoded1 = ctx->decoded1;
784
785     if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
786         /* We are pure silence, so we're done. */
787         av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
788         return;
789     }
790
791     entropy_decode(ctx, count, 1);
792     ape_apply_filters(ctx, decoded0, decoded1, count);
793
794     /* Now apply the predictor decoding */
795     predictor_decode_stereo(ctx, count);
796
797     /* Decorrelate and scale to output depth */
798     while (count--) {
799         left = *decoded1 - (*decoded0 / 2);
800         right = left + *decoded0;
801
802         *(decoded0++) = left;
803         *(decoded1++) = right;
804     }
805 }
806
807 static int ape_decode_frame(AVCodecContext *avctx,
808                             void *data, int *data_size,
809                             AVPacket *avpkt)
810 {
811     const uint8_t *buf = avpkt->data;
812     int buf_size = avpkt->size;
813     APEContext *s = avctx->priv_data;
814     int16_t *samples = data;
815     int nblocks;
816     int i, n;
817     int blockstodecode;
818     int bytes_used;
819
820     /* should not happen but who knows */
821     if (BLOCKS_PER_LOOP * 2 * avctx->channels > *data_size) {
822         av_log (avctx, AV_LOG_ERROR, "Output buffer is too small.\n");
823         return AVERROR(EINVAL);
824     }
825
826     if(!s->samples){
827         void *tmp_data = av_realloc(s->data, (buf_size + 3) & ~3);
828         if (!tmp_data)
829             return AVERROR(ENOMEM);
830         s->data = tmp_data;
831         s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
832         s->ptr = s->last_ptr = s->data;
833         s->data_end = s->data + buf_size;
834
835         nblocks = bytestream_get_be32(&s->ptr);
836         n =  bytestream_get_be32(&s->ptr);
837         if(n < 0 || n > 3){
838             av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
839             s->data = NULL;
840             return AVERROR_INVALIDDATA;
841         }
842         s->ptr += n;
843
844         s->currentframeblocks = nblocks;
845         buf += 4;
846         if (nblocks <= 0) {
847             *data_size = 0;
848             return buf_size;
849         }
850         s->samples = nblocks;
851
852         memset(s->decoded0,  0, sizeof(s->decoded0));
853         memset(s->decoded1,  0, sizeof(s->decoded1));
854
855         /* Initialize the frame decoder */
856         init_frame_decoder(s);
857     }
858
859     if (!s->data) {
860         *data_size = 0;
861         return buf_size;
862     }
863
864     nblocks = s->samples;
865     blockstodecode = FFMIN(BLOCKS_PER_LOOP, nblocks);
866
867     s->error=0;
868
869     if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
870         ape_unpack_mono(s, blockstodecode);
871     else
872         ape_unpack_stereo(s, blockstodecode);
873     emms_c();
874
875     if(s->error || s->ptr > s->data_end){
876         s->samples=0;
877         av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
878         return AVERROR_INVALIDDATA;
879     }
880
881     for (i = 0; i < blockstodecode; i++) {
882         *samples++ = s->decoded0[i];
883         if(s->channels == 2)
884             *samples++ = s->decoded1[i];
885     }
886
887     s->samples -= blockstodecode;
888
889     *data_size = blockstodecode * 2 * s->channels;
890     bytes_used = s->samples ? s->ptr - s->last_ptr : buf_size;
891     s->last_ptr = s->ptr;
892     return bytes_used;
893 }
894
895 static void ape_flush(AVCodecContext *avctx)
896 {
897     APEContext *s = avctx->priv_data;
898     s->samples= 0;
899 }
900
901 AVCodec ff_ape_decoder = {
902     .name           = "ape",
903     .type           = AVMEDIA_TYPE_AUDIO,
904     .id             = CODEC_ID_APE,
905     .priv_data_size = sizeof(APEContext),
906     .init           = ape_decode_init,
907     .close          = ape_decode_close,
908     .decode         = ape_decode_frame,
909     .capabilities = CODEC_CAP_SUBFRAMES,
910     .flush = ape_flush,
911     .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
912 };