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