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