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