2 * Monkey's Audio lossless audio decoder
3 * Copyright (c) 2007 Benjamin Zores <ben@geexbox.org>
4 * based upon libdemac from Dave Chapman.
6 * This file is part of FFmpeg.
8 * FFmpeg 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.
13 * FFmpeg 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.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "libavutil/avassert.h"
26 #include "libavutil/channel_layout.h"
27 #include "libavutil/crc.h"
28 #include "libavutil/opt.h"
29 #include "lossless_audiodsp.h"
32 #include "bytestream.h"
39 * Monkey's Audio lossless audio decoder
42 #define MAX_CHANNELS 2
43 #define MAX_BYTESPERSAMPLE 3
45 #define APE_FRAMECODE_MONO_SILENCE 1
46 #define APE_FRAMECODE_STEREO_SILENCE 3
47 #define APE_FRAMECODE_PSEUDO_STEREO 4
49 #define HISTORY_SIZE 512
50 #define PREDICTOR_ORDER 8
51 /** Total size of all predictor histories */
52 #define PREDICTOR_SIZE 50
54 #define YDELAYA (18 + PREDICTOR_ORDER*4)
55 #define YDELAYB (18 + PREDICTOR_ORDER*3)
56 #define XDELAYA (18 + PREDICTOR_ORDER*2)
57 #define XDELAYB (18 + PREDICTOR_ORDER)
59 #define YADAPTCOEFFSA 18
60 #define XADAPTCOEFFSA 14
61 #define YADAPTCOEFFSB 10
62 #define XADAPTCOEFFSB 5
65 * Possible compression levels
68 enum APECompressionLevel {
69 COMPRESSION_LEVEL_FAST = 1000,
70 COMPRESSION_LEVEL_NORMAL = 2000,
71 COMPRESSION_LEVEL_HIGH = 3000,
72 COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
73 COMPRESSION_LEVEL_INSANE = 5000
77 #define APE_FILTER_LEVELS 3
79 /** Filter orders depending on compression level */
80 static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
88 /** Filter fraction bits depending on compression level */
89 static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
98 /** Filters applied to the decoded data */
99 typedef struct APEFilter {
100 int16_t *coeffs; ///< actual coefficients used in filtering
101 int16_t *adaptcoeffs; ///< adaptive filter coefficients used for correcting of actual filter coefficients
102 int16_t *historybuffer; ///< filter memory
103 int16_t *delay; ///< filtered values
108 typedef struct APERice {
113 typedef struct APERangecoder {
114 uint32_t low; ///< low end of interval
115 uint32_t range; ///< length of interval
116 uint32_t help; ///< bytes_to_follow resp. intermediate value
117 unsigned int buffer; ///< buffer for input/output
120 /** Filter histories */
121 typedef struct APEPredictor {
129 uint32_t coeffsA[2][4]; ///< adaption coefficients
130 uint32_t coeffsB[2][5]; ///< adaption coefficients
131 int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
133 unsigned int sample_pos;
136 typedef struct APEPredictor64 {
144 uint64_t coeffsA[2][4]; ///< adaption coefficients
145 uint64_t coeffsB[2][5]; ///< adaption coefficients
146 int64_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
148 unsigned int sample_pos;
151 /** Decoder context */
152 typedef struct APEContext {
153 AVClass *class; ///< class for AVOptions
154 AVCodecContext *avctx;
155 BswapDSPContext bdsp;
156 LLAudDSPContext adsp;
158 int samples; ///< samples left to decode in current frame
161 int fileversion; ///< codec version, very important in decoding process
162 int compression_level; ///< compression levels
163 int fset; ///< which filter set to use (calculated from compression level)
164 int flags; ///< global decoder flags
166 uint32_t CRC; ///< signalled frame CRC
167 uint32_t CRC_state; ///< accumulated CRC
168 int frameflags; ///< frame flags
169 APEPredictor predictor; ///< predictor used for final reconstruction
170 APEPredictor64 predictor64; ///< 64bit predictor used for final reconstruction
172 int32_t *decoded_buffer;
174 int32_t *decoded[MAX_CHANNELS]; ///< decoded data for each channel
175 int blocks_per_loop; ///< maximum number of samples to decode for each call
177 int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory
179 APERangecoder rc; ///< rangecoder used to decode actual values
180 APERice riceX; ///< rice code parameters for the second channel
181 APERice riceY; ///< rice code parameters for the first channel
182 APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
185 uint8_t *data; ///< current frame data
186 uint8_t *data_end; ///< frame data end
187 int data_size; ///< frame data allocated size
188 const uint8_t *ptr; ///< current position in frame data
192 void (*entropy_decode_mono)(struct APEContext *ctx, int blockstodecode);
193 void (*entropy_decode_stereo)(struct APEContext *ctx, int blockstodecode);
194 void (*predictor_decode_mono)(struct APEContext *ctx, int count);
195 void (*predictor_decode_stereo)(struct APEContext *ctx, int count);
198 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
199 int32_t *decoded1, int count);
201 static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode);
202 static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode);
203 static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode);
204 static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode);
205 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode);
206 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode);
207 static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode);
208 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode);
209 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode);
211 static void predictor_decode_mono_3800(APEContext *ctx, int count);
212 static void predictor_decode_stereo_3800(APEContext *ctx, int count);
213 static void predictor_decode_mono_3930(APEContext *ctx, int count);
214 static void predictor_decode_stereo_3930(APEContext *ctx, int count);
215 static void predictor_decode_mono_3950(APEContext *ctx, int count);
216 static void predictor_decode_stereo_3950(APEContext *ctx, int count);
218 static av_cold int ape_decode_close(AVCodecContext *avctx)
220 APEContext *s = avctx->priv_data;
223 for (i = 0; i < APE_FILTER_LEVELS; i++)
224 av_freep(&s->filterbuf[i]);
226 av_freep(&s->decoded_buffer);
228 s->decoded_size = s->data_size = 0;
233 static av_cold int ape_decode_init(AVCodecContext *avctx)
235 APEContext *s = avctx->priv_data;
238 if (avctx->extradata_size != 6) {
239 av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
240 return AVERROR(EINVAL);
242 if (avctx->channels > 2) {
243 av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
244 return AVERROR(EINVAL);
246 avctx->bits_per_raw_sample =
247 s->bps = avctx->bits_per_coded_sample;
250 avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
253 avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
256 avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
259 avpriv_request_sample(avctx,
260 "%d bits per coded sample", s->bps);
261 return AVERROR_PATCHWELCOME;
264 s->channels = avctx->channels;
265 s->fileversion = AV_RL16(avctx->extradata);
266 s->compression_level = AV_RL16(avctx->extradata + 2);
267 s->flags = AV_RL16(avctx->extradata + 4);
269 av_log(avctx, AV_LOG_VERBOSE, "Compression Level: %d - Flags: %d\n",
270 s->compression_level, s->flags);
271 if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE ||
272 !s->compression_level ||
273 (s->fileversion < 3930 && s->compression_level == COMPRESSION_LEVEL_INSANE)) {
274 av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
275 s->compression_level);
276 return AVERROR_INVALIDDATA;
278 s->fset = s->compression_level / 1000 - 1;
279 for (i = 0; i < APE_FILTER_LEVELS; i++) {
280 if (!ape_filter_orders[s->fset][i])
282 if (!(s->filterbuf[i] = av_malloc((ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4)))
283 return AVERROR(ENOMEM);
286 if (s->fileversion < 3860) {
287 s->entropy_decode_mono = entropy_decode_mono_0000;
288 s->entropy_decode_stereo = entropy_decode_stereo_0000;
289 } else if (s->fileversion < 3900) {
290 s->entropy_decode_mono = entropy_decode_mono_3860;
291 s->entropy_decode_stereo = entropy_decode_stereo_3860;
292 } else if (s->fileversion < 3930) {
293 s->entropy_decode_mono = entropy_decode_mono_3900;
294 s->entropy_decode_stereo = entropy_decode_stereo_3900;
295 } else if (s->fileversion < 3990) {
296 s->entropy_decode_mono = entropy_decode_mono_3900;
297 s->entropy_decode_stereo = entropy_decode_stereo_3930;
299 s->entropy_decode_mono = entropy_decode_mono_3990;
300 s->entropy_decode_stereo = entropy_decode_stereo_3990;
303 if (s->fileversion < 3930) {
304 s->predictor_decode_mono = predictor_decode_mono_3800;
305 s->predictor_decode_stereo = predictor_decode_stereo_3800;
306 } else if (s->fileversion < 3950) {
307 s->predictor_decode_mono = predictor_decode_mono_3930;
308 s->predictor_decode_stereo = predictor_decode_stereo_3930;
310 s->predictor_decode_mono = predictor_decode_mono_3950;
311 s->predictor_decode_stereo = predictor_decode_stereo_3950;
314 ff_bswapdsp_init(&s->bdsp);
315 ff_llauddsp_init(&s->adsp);
316 avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
322 * @name APE range decoding functions
327 #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
328 #define SHIFT_BITS (CODE_BITS - 9)
329 #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
330 #define BOTTOM_VALUE (TOP_VALUE >> 8)
332 /** Start the decoder */
333 static inline void range_start_decoding(APEContext *ctx)
335 ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
336 ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
337 ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
340 /** Perform normalization */
341 static inline void range_dec_normalize(APEContext *ctx)
343 while (ctx->rc.range <= BOTTOM_VALUE) {
344 ctx->rc.buffer <<= 8;
345 if(ctx->ptr < ctx->data_end) {
346 ctx->rc.buffer += *ctx->ptr;
351 ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
357 * Calculate cumulative frequency for next symbol. Does NO update!
358 * @param ctx decoder context
359 * @param tot_f is the total frequency or (code_value)1<<shift
360 * @return the cumulative frequency
362 static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
364 range_dec_normalize(ctx);
365 ctx->rc.help = ctx->rc.range / tot_f;
366 return ctx->rc.low / ctx->rc.help;
370 * Decode value with given size in bits
371 * @param ctx decoder context
372 * @param shift number of bits to decode
374 static inline int range_decode_culshift(APEContext *ctx, int shift)
376 range_dec_normalize(ctx);
377 ctx->rc.help = ctx->rc.range >> shift;
378 return ctx->rc.low / ctx->rc.help;
383 * Update decoding state
384 * @param ctx decoder context
385 * @param sy_f the interval length (frequency of the symbol)
386 * @param lt_f the lower end (frequency sum of < symbols)
388 static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
390 ctx->rc.low -= ctx->rc.help * lt_f;
391 ctx->rc.range = ctx->rc.help * sy_f;
394 /** Decode n bits (n <= 16) without modelling */
395 static inline int range_decode_bits(APEContext *ctx, int n)
397 int sym = range_decode_culshift(ctx, n);
398 range_decode_update(ctx, 1, sym);
403 #define MODEL_ELEMENTS 64
406 * Fixed probabilities for symbols in Monkey Audio version 3.97
408 static const uint16_t counts_3970[22] = {
409 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
410 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
411 65450, 65469, 65480, 65487, 65491, 65493,
415 * Probability ranges for symbols in Monkey Audio version 3.97
417 static const uint16_t counts_diff_3970[21] = {
418 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
419 1104, 677, 415, 248, 150, 89, 54, 31,
424 * Fixed probabilities for symbols in Monkey Audio version 3.98
426 static const uint16_t counts_3980[22] = {
427 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
428 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
429 65485, 65488, 65490, 65491, 65492, 65493,
433 * Probability ranges for symbols in Monkey Audio version 3.98
435 static const uint16_t counts_diff_3980[21] = {
436 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
437 261, 119, 65, 31, 19, 10, 6, 3,
443 * @param ctx decoder context
444 * @param counts probability range start position
445 * @param counts_diff probability range widths
447 static inline int range_get_symbol(APEContext *ctx,
448 const uint16_t counts[],
449 const uint16_t counts_diff[])
453 cf = range_decode_culshift(ctx, 16);
456 symbol= cf - 65535 + 63;
457 range_decode_update(ctx, 1, cf);
462 /* figure out the symbol inefficiently; a binary search would be much better */
463 for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
465 range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
469 /** @} */ // group rangecoder
471 static inline void update_rice(APERice *rice, unsigned int x)
473 int lim = rice->k ? (1 << (rice->k + 4)) : 0;
474 rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
476 if (rice->ksum < lim)
478 else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
482 static inline int get_rice_ook(GetBitContext *gb, int k)
486 x = get_unary(gb, 1, get_bits_left(gb));
489 x = (x << k) | get_bits(gb, k);
494 static inline int ape_decode_value_3860(APEContext *ctx, GetBitContext *gb,
497 unsigned int x, overflow;
499 overflow = get_unary(gb, 1, get_bits_left(gb));
501 if (ctx->fileversion > 3880) {
502 while (overflow >= 16) {
510 else if(rice->k <= MIN_CACHE_BITS) {
511 x = (overflow << rice->k) + get_bits(gb, rice->k);
513 av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %"PRIu32"\n", rice->k);
515 return AVERROR_INVALIDDATA;
517 rice->ksum += x - (rice->ksum + 8 >> 4);
518 if (rice->ksum < (rice->k ? 1 << (rice->k + 4) : 0))
520 else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
523 /* Convert to signed */
524 return ((x >> 1) ^ ((x & 1) - 1)) + 1;
527 static inline int ape_decode_value_3900(APEContext *ctx, APERice *rice)
529 unsigned int x, overflow;
532 overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
534 if (overflow == (MODEL_ELEMENTS - 1)) {
535 tmpk = range_decode_bits(ctx, 5);
538 tmpk = (rice->k < 1) ? 0 : rice->k - 1;
540 if (tmpk <= 16 || ctx->fileversion < 3910) {
542 av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
543 return AVERROR_INVALIDDATA;
545 x = range_decode_bits(ctx, tmpk);
546 } else if (tmpk <= 31) {
547 x = range_decode_bits(ctx, 16);
548 x |= (range_decode_bits(ctx, tmpk - 16) << 16);
550 av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
551 return AVERROR_INVALIDDATA;
553 x += overflow << tmpk;
555 update_rice(rice, x);
557 /* Convert to signed */
558 return ((x >> 1) ^ ((x & 1) - 1)) + 1;
561 static inline int ape_decode_value_3990(APEContext *ctx, APERice *rice)
563 unsigned int x, overflow, pivot;
566 pivot = FFMAX(rice->ksum >> 5, 1);
568 overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
570 if (overflow == (MODEL_ELEMENTS - 1)) {
571 overflow = (unsigned)range_decode_bits(ctx, 16) << 16;
572 overflow |= range_decode_bits(ctx, 16);
575 if (pivot < 0x10000) {
576 base = range_decode_culfreq(ctx, pivot);
577 range_decode_update(ctx, 1, base);
579 int base_hi = pivot, base_lo;
582 while (base_hi & ~0xFFFF) {
586 base_hi = range_decode_culfreq(ctx, base_hi + 1);
587 range_decode_update(ctx, 1, base_hi);
588 base_lo = range_decode_culfreq(ctx, 1 << bbits);
589 range_decode_update(ctx, 1, base_lo);
591 base = (base_hi << bbits) + base_lo;
594 x = base + overflow * pivot;
596 update_rice(rice, x);
598 /* Convert to signed */
599 return ((x >> 1) ^ ((x & 1) - 1)) + 1;
602 static int get_k(int ksum)
604 return av_log2(ksum) + !!ksum;
607 static void decode_array_0000(APEContext *ctx, GetBitContext *gb,
608 int32_t *out, APERice *rice, int blockstodecode)
611 unsigned ksummax, ksummin;
614 for (i = 0; i < FFMIN(blockstodecode, 5); i++) {
615 out[i] = get_rice_ook(&ctx->gb, 10);
616 rice->ksum += out[i];
619 if (blockstodecode <= 5)
622 rice->k = get_k(rice->ksum / 10);
625 for (; i < FFMIN(blockstodecode, 64); i++) {
626 out[i] = get_rice_ook(&ctx->gb, rice->k);
627 rice->ksum += out[i];
628 rice->k = get_k(rice->ksum / ((i + 1) * 2));
633 if (blockstodecode <= 64)
636 rice->k = get_k(rice->ksum >> 7);
637 ksummax = 1 << rice->k + 7;
638 ksummin = rice->k ? (1 << rice->k + 6) : 0;
639 for (; i < blockstodecode; i++) {
640 if (get_bits_left(&ctx->gb) < 1) {
644 out[i] = get_rice_ook(&ctx->gb, rice->k);
645 rice->ksum += out[i] - (unsigned)out[i - 64];
646 while (rice->ksum < ksummin) {
648 ksummin = rice->k ? ksummin >> 1 : 0;
651 while (rice->ksum >= ksummax) {
656 ksummin = ksummin ? ksummin << 1 : 128;
661 for (i = 0; i < blockstodecode; i++)
662 out[i] = ((out[i] >> 1) ^ ((out[i] & 1) - 1)) + 1;
665 static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode)
667 decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
671 static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode)
673 decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
675 decode_array_0000(ctx, &ctx->gb, ctx->decoded[1], &ctx->riceX,
679 static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode)
681 int32_t *decoded0 = ctx->decoded[0];
683 while (blockstodecode--)
684 *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
687 static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode)
689 int32_t *decoded0 = ctx->decoded[0];
690 int32_t *decoded1 = ctx->decoded[1];
691 int blocks = blockstodecode;
693 while (blockstodecode--)
694 *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
696 *decoded1++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceX);
699 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode)
701 int32_t *decoded0 = ctx->decoded[0];
703 while (blockstodecode--)
704 *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
707 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode)
709 int32_t *decoded0 = ctx->decoded[0];
710 int32_t *decoded1 = ctx->decoded[1];
711 int blocks = blockstodecode;
713 while (blockstodecode--)
714 *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
715 range_dec_normalize(ctx);
716 // because of some implementation peculiarities we need to backpedal here
718 range_start_decoding(ctx);
720 *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
723 static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode)
725 int32_t *decoded0 = ctx->decoded[0];
726 int32_t *decoded1 = ctx->decoded[1];
728 while (blockstodecode--) {
729 *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
730 *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
734 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode)
736 int32_t *decoded0 = ctx->decoded[0];
738 while (blockstodecode--)
739 *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
742 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode)
744 int32_t *decoded0 = ctx->decoded[0];
745 int32_t *decoded1 = ctx->decoded[1];
747 while (blockstodecode--) {
748 *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
749 *decoded1++ = ape_decode_value_3990(ctx, &ctx->riceX);
753 static int init_entropy_decoder(APEContext *ctx)
756 if (ctx->fileversion >= 3900) {
757 if (ctx->data_end - ctx->ptr < 6)
758 return AVERROR_INVALIDDATA;
759 ctx->CRC = bytestream_get_be32(&ctx->ptr);
761 ctx->CRC = get_bits_long(&ctx->gb, 32);
764 /* Read the frame flags if they exist */
766 ctx->CRC_state = UINT32_MAX;
767 if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
768 ctx->CRC &= ~0x80000000;
770 if (ctx->data_end - ctx->ptr < 6)
771 return AVERROR_INVALIDDATA;
772 ctx->frameflags = bytestream_get_be32(&ctx->ptr);
775 /* Initialize the rice structs */
777 ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
779 ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
781 if (ctx->fileversion >= 3900) {
782 /* The first 8 bits of input are ignored. */
785 range_start_decoding(ctx);
791 static const int32_t initial_coeffs_fast_3320[1] = {
795 static const int32_t initial_coeffs_a_3800[3] = {
799 static const int32_t initial_coeffs_b_3800[2] = {
803 static const int32_t initial_coeffs_3930[4] = {
807 static const int64_t initial_coeffs_3930_64bit[4] = {
811 static void init_predictor_decoder(APEContext *ctx)
813 APEPredictor *p = &ctx->predictor;
814 APEPredictor64 *p64 = &ctx->predictor64;
816 /* Zero the history buffers */
817 memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
818 memset(p64->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p64->historybuffer));
819 p->buf = p->historybuffer;
820 p64->buf = p64->historybuffer;
822 /* Initialize and zero the coefficients */
823 if (ctx->fileversion < 3930) {
824 if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
825 memcpy(p->coeffsA[0], initial_coeffs_fast_3320,
826 sizeof(initial_coeffs_fast_3320));
827 memcpy(p->coeffsA[1], initial_coeffs_fast_3320,
828 sizeof(initial_coeffs_fast_3320));
830 memcpy(p->coeffsA[0], initial_coeffs_a_3800,
831 sizeof(initial_coeffs_a_3800));
832 memcpy(p->coeffsA[1], initial_coeffs_a_3800,
833 sizeof(initial_coeffs_a_3800));
836 memcpy(p->coeffsA[0], initial_coeffs_3930, sizeof(initial_coeffs_3930));
837 memcpy(p->coeffsA[1], initial_coeffs_3930, sizeof(initial_coeffs_3930));
838 memcpy(p64->coeffsA[0], initial_coeffs_3930_64bit, sizeof(initial_coeffs_3930_64bit));
839 memcpy(p64->coeffsA[1], initial_coeffs_3930_64bit, sizeof(initial_coeffs_3930_64bit));
841 memset(p->coeffsB, 0, sizeof(p->coeffsB));
842 memset(p64->coeffsB, 0, sizeof(p64->coeffsB));
843 if (ctx->fileversion < 3930) {
844 memcpy(p->coeffsB[0], initial_coeffs_b_3800,
845 sizeof(initial_coeffs_b_3800));
846 memcpy(p->coeffsB[1], initial_coeffs_b_3800,
847 sizeof(initial_coeffs_b_3800));
850 p->filterA[0] = p->filterA[1] = 0;
851 p->filterB[0] = p->filterB[1] = 0;
852 p->lastA[0] = p->lastA[1] = 0;
854 p64->filterA[0] = p64->filterA[1] = 0;
855 p64->filterB[0] = p64->filterB[1] = 0;
856 p64->lastA[0] = p64->lastA[1] = 0;
863 /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
864 static inline int APESIGN(int32_t x) {
865 return (x < 0) - (x > 0);
868 static av_always_inline int filter_fast_3320(APEPredictor *p,
869 const int decoded, const int filter,
874 p->buf[delayA] = p->lastA[filter];
875 if (p->sample_pos < 3) {
876 p->lastA[filter] = decoded;
877 p->filterA[filter] = decoded;
881 predictionA = p->buf[delayA] * 2U - p->buf[delayA - 1];
882 p->lastA[filter] = decoded + ((int32_t)(predictionA * p->coeffsA[filter][0]) >> 9);
884 if ((decoded ^ predictionA) > 0)
885 p->coeffsA[filter][0]++;
887 p->coeffsA[filter][0]--;
889 p->filterA[filter] += (unsigned)p->lastA[filter];
891 return p->filterA[filter];
894 static av_always_inline int filter_3800(APEPredictor *p,
895 const unsigned decoded, const int filter,
896 const int delayA, const int delayB,
897 const int start, const int shift)
899 int32_t predictionA, predictionB, sign;
900 int32_t d0, d1, d2, d3, d4;
902 p->buf[delayA] = p->lastA[filter];
903 p->buf[delayB] = p->filterB[filter];
904 if (p->sample_pos < start) {
905 predictionA = decoded + p->filterA[filter];
906 p->lastA[filter] = decoded;
907 p->filterB[filter] = decoded;
908 p->filterA[filter] = predictionA;
912 d1 = (p->buf[delayA] - p->buf[delayA - 1]) * 2U;
913 d0 = p->buf[delayA] + ((p->buf[delayA - 2] - p->buf[delayA - 1]) * 8U);
914 d3 = p->buf[delayB] * 2U - p->buf[delayB - 1];
917 predictionA = d0 * p->coeffsA[filter][0] +
918 d1 * p->coeffsA[filter][1] +
919 d2 * p->coeffsA[filter][2];
921 sign = APESIGN(decoded);
922 p->coeffsA[filter][0] += (((d0 >> 30) & 2) - 1) * sign;
923 p->coeffsA[filter][1] += (((d1 >> 28) & 8) - 4) * sign;
924 p->coeffsA[filter][2] += (((d2 >> 28) & 8) - 4) * sign;
926 predictionB = d3 * p->coeffsB[filter][0] -
927 d4 * p->coeffsB[filter][1];
928 p->lastA[filter] = decoded + (predictionA >> 11);
929 sign = APESIGN(p->lastA[filter]);
930 p->coeffsB[filter][0] += (((d3 >> 29) & 4) - 2) * sign;
931 p->coeffsB[filter][1] -= (((d4 >> 30) & 2) - 1) * sign;
933 p->filterB[filter] = p->lastA[filter] + (predictionB >> shift);
934 p->filterA[filter] = p->filterB[filter] + (unsigned)((int)(p->filterA[filter] * 31U) >> 5);
936 return p->filterA[filter];
939 static void long_filter_high_3800(int32_t *buffer, int order, int shift, int length)
942 int32_t dotprod, sign;
943 int32_t coeffs[256], delay[256];
948 memset(coeffs, 0, order * sizeof(*coeffs));
949 for (i = 0; i < order; i++)
950 delay[i] = buffer[i];
951 for (i = order; i < length; i++) {
953 sign = APESIGN(buffer[i]);
954 for (j = 0; j < order; j++) {
955 dotprod += delay[j] * (unsigned)coeffs[j];
956 coeffs[j] += ((delay[j] >> 31) | 1) * sign;
958 buffer[i] -= dotprod >> shift;
959 for (j = 0; j < order - 1; j++)
960 delay[j] = delay[j + 1];
961 delay[order - 1] = buffer[i];
965 static void long_filter_ehigh_3830(int32_t *buffer, int length)
968 int32_t dotprod, sign;
969 int32_t delay[8] = { 0 };
970 uint32_t coeffs[8] = { 0 };
972 for (i = 0; i < length; i++) {
974 sign = APESIGN(buffer[i]);
975 for (j = 7; j >= 0; j--) {
976 dotprod += delay[j] * coeffs[j];
977 coeffs[j] += ((delay[j] >> 31) | 1) * sign;
979 for (j = 7; j > 0; j--)
980 delay[j] = delay[j - 1];
981 delay[0] = buffer[i];
982 buffer[i] -= dotprod >> 9;
986 static void predictor_decode_stereo_3800(APEContext *ctx, int count)
988 APEPredictor *p = &ctx->predictor;
989 int32_t *decoded0 = ctx->decoded[0];
990 int32_t *decoded1 = ctx->decoded[1];
991 int start = 4, shift = 10;
993 if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
995 long_filter_high_3800(decoded0, 16, 9, count);
996 long_filter_high_3800(decoded1, 16, 9, count);
997 } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
998 int order = 128, shift2 = 11;
1000 if (ctx->fileversion >= 3830) {
1004 long_filter_ehigh_3830(decoded0 + order, count - order);
1005 long_filter_ehigh_3830(decoded1 + order, count - order);
1008 long_filter_high_3800(decoded0, order, shift2, count);
1009 long_filter_high_3800(decoded1, order, shift2, count);
1013 int X = *decoded0, Y = *decoded1;
1014 if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
1015 *decoded0 = filter_fast_3320(p, Y, 0, YDELAYA);
1017 *decoded1 = filter_fast_3320(p, X, 1, XDELAYA);
1020 *decoded0 = filter_3800(p, Y, 0, YDELAYA, YDELAYB,
1023 *decoded1 = filter_3800(p, X, 1, XDELAYA, XDELAYB,
1032 /* Have we filled the history buffer? */
1033 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1034 memmove(p->historybuffer, p->buf,
1035 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1036 p->buf = p->historybuffer;
1041 static void predictor_decode_mono_3800(APEContext *ctx, int count)
1043 APEPredictor *p = &ctx->predictor;
1044 int32_t *decoded0 = ctx->decoded[0];
1045 int start = 4, shift = 10;
1047 if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
1049 long_filter_high_3800(decoded0, 16, 9, count);
1050 } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
1051 int order = 128, shift2 = 11;
1053 if (ctx->fileversion >= 3830) {
1057 long_filter_ehigh_3830(decoded0 + order, count - order);
1060 long_filter_high_3800(decoded0, order, shift2, count);
1064 if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
1065 *decoded0 = filter_fast_3320(p, *decoded0, 0, YDELAYA);
1068 *decoded0 = filter_3800(p, *decoded0, 0, YDELAYA, YDELAYB,
1077 /* Have we filled the history buffer? */
1078 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1079 memmove(p->historybuffer, p->buf,
1080 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1081 p->buf = p->historybuffer;
1086 static av_always_inline int predictor_update_3930(APEPredictor *p,
1087 const int decoded, const int filter,
1090 int32_t predictionA, sign;
1091 int32_t d0, d1, d2, d3;
1093 p->buf[delayA] = p->lastA[filter];
1094 d0 = p->buf[delayA ];
1095 d1 = p->buf[delayA ] - p->buf[delayA - 1];
1096 d2 = p->buf[delayA - 1] - p->buf[delayA - 2];
1097 d3 = p->buf[delayA - 2] - p->buf[delayA - 3];
1099 predictionA = d0 * p->coeffsA[filter][0] +
1100 d1 * p->coeffsA[filter][1] +
1101 d2 * p->coeffsA[filter][2] +
1102 d3 * p->coeffsA[filter][3];
1104 p->lastA[filter] = decoded + (predictionA >> 9);
1105 p->filterA[filter] = p->lastA[filter] + ((int)(p->filterA[filter] * 31U) >> 5);
1107 sign = APESIGN(decoded);
1108 p->coeffsA[filter][0] += ((d0 < 0) * 2 - 1) * sign;
1109 p->coeffsA[filter][1] += ((d1 < 0) * 2 - 1) * sign;
1110 p->coeffsA[filter][2] += ((d2 < 0) * 2 - 1) * sign;
1111 p->coeffsA[filter][3] += ((d3 < 0) * 2 - 1) * sign;
1113 return p->filterA[filter];
1116 static void predictor_decode_stereo_3930(APEContext *ctx, int count)
1118 APEPredictor *p = &ctx->predictor;
1119 int32_t *decoded0 = ctx->decoded[0];
1120 int32_t *decoded1 = ctx->decoded[1];
1122 ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1126 int Y = *decoded1, X = *decoded0;
1127 *decoded0 = predictor_update_3930(p, Y, 0, YDELAYA);
1129 *decoded1 = predictor_update_3930(p, X, 1, XDELAYA);
1135 /* Have we filled the history buffer? */
1136 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1137 memmove(p->historybuffer, p->buf,
1138 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1139 p->buf = p->historybuffer;
1144 static void predictor_decode_mono_3930(APEContext *ctx, int count)
1146 APEPredictor *p = &ctx->predictor;
1147 int32_t *decoded0 = ctx->decoded[0];
1149 ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1152 *decoded0 = predictor_update_3930(p, *decoded0, 0, YDELAYA);
1157 /* Have we filled the history buffer? */
1158 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1159 memmove(p->historybuffer, p->buf,
1160 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1161 p->buf = p->historybuffer;
1166 static av_always_inline int predictor_update_filter(APEPredictor64 *p,
1167 const int decoded, const int filter,
1168 const int delayA, const int delayB,
1169 const int adaptA, const int adaptB)
1171 int64_t predictionA, predictionB;
1174 p->buf[delayA] = p->lastA[filter];
1175 p->buf[adaptA] = APESIGN(p->buf[delayA]);
1176 p->buf[delayA - 1] = p->buf[delayA] - (uint64_t)p->buf[delayA - 1];
1177 p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
1179 predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
1180 p->buf[delayA - 1] * p->coeffsA[filter][1] +
1181 p->buf[delayA - 2] * p->coeffsA[filter][2] +
1182 p->buf[delayA - 3] * p->coeffsA[filter][3];
1184 /* Apply a scaled first-order filter compression */
1185 p->buf[delayB] = p->filterA[filter ^ 1] - ((int64_t)(p->filterB[filter] * 31ULL) >> 5);
1186 p->buf[adaptB] = APESIGN(p->buf[delayB]);
1187 p->buf[delayB - 1] = p->buf[delayB] - (uint64_t)p->buf[delayB - 1];
1188 p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
1189 p->filterB[filter] = p->filterA[filter ^ 1];
1191 predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
1192 p->buf[delayB - 1] * p->coeffsB[filter][1] +
1193 p->buf[delayB - 2] * p->coeffsB[filter][2] +
1194 p->buf[delayB - 3] * p->coeffsB[filter][3] +
1195 p->buf[delayB - 4] * p->coeffsB[filter][4];
1197 p->lastA[filter] = decoded + ((int64_t)((uint64_t)predictionA + (predictionB >> 1)) >> 10);
1198 p->filterA[filter] = p->lastA[filter] + ((int64_t)(p->filterA[filter] * 31ULL) >> 5);
1200 sign = APESIGN(decoded);
1201 p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
1202 p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
1203 p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
1204 p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
1205 p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
1206 p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
1207 p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
1208 p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
1209 p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
1211 return p->filterA[filter];
1214 static void predictor_decode_stereo_3950(APEContext *ctx, int count)
1216 APEPredictor64 *p = &ctx->predictor64;
1217 int32_t *decoded0 = ctx->decoded[0];
1218 int32_t *decoded1 = ctx->decoded[1];
1220 ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1224 *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
1225 YADAPTCOEFFSA, YADAPTCOEFFSB);
1227 *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
1228 XADAPTCOEFFSA, XADAPTCOEFFSB);
1234 /* Have we filled the history buffer? */
1235 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1236 memmove(p->historybuffer, p->buf,
1237 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1238 p->buf = p->historybuffer;
1243 static void predictor_decode_mono_3950(APEContext *ctx, int count)
1245 APEPredictor64 *p = &ctx->predictor64;
1246 int32_t *decoded0 = ctx->decoded[0];
1247 int32_t predictionA, currentA, A, sign;
1249 ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1251 currentA = p->lastA[0];
1256 p->buf[YDELAYA] = currentA;
1257 p->buf[YDELAYA - 1] = p->buf[YDELAYA] - (uint64_t)p->buf[YDELAYA - 1];
1259 predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
1260 p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
1261 p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
1262 p->buf[YDELAYA - 3] * p->coeffsA[0][3];
1264 currentA = A + (uint64_t)(predictionA >> 10);
1266 p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
1267 p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
1270 p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
1271 p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
1272 p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
1273 p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
1277 /* Have we filled the history buffer? */
1278 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1279 memmove(p->historybuffer, p->buf,
1280 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1281 p->buf = p->historybuffer;
1284 p->filterA[0] = currentA + (uint64_t)((int64_t)(p->filterA[0] * 31U) >> 5);
1285 *(decoded0++) = p->filterA[0];
1288 p->lastA[0] = currentA;
1291 static void do_init_filter(APEFilter *f, int16_t *buf, int order)
1294 f->historybuffer = buf + order;
1295 f->delay = f->historybuffer + order * 2;
1296 f->adaptcoeffs = f->historybuffer + order;
1298 memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
1299 memset(f->coeffs, 0, order * sizeof(*f->coeffs));
1303 static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
1305 do_init_filter(&f[0], buf, order);
1306 do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
1309 static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
1310 int32_t *data, int count, int order, int fracbits)
1316 /* round fixedpoint scalar product */
1317 res = ctx->adsp.scalarproduct_and_madd_int16(f->coeffs,
1319 f->adaptcoeffs - order,
1320 order, APESIGN(*data));
1321 res = (int64_t)(res + (1LL << (fracbits - 1))) >> fracbits;
1322 res += (unsigned)*data;
1325 /* Update the output history */
1326 *f->delay++ = av_clip_int16(res);
1328 if (version < 3980) {
1329 /* Version ??? to < 3.98 files (untested) */
1330 f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
1331 f->adaptcoeffs[-4] >>= 1;
1332 f->adaptcoeffs[-8] >>= 1;
1334 /* Version 3.98 and later files */
1336 /* Update the adaption coefficients */
1337 absres = FFABSU(res);
1339 *f->adaptcoeffs = APESIGN(res) *
1340 (8 << ((absres > f->avg * 3) + (absres > f->avg * 4 / 3)));
1341 /* equivalent to the following code
1342 if (absres <= f->avg * 4 / 3)
1343 *f->adaptcoeffs = APESIGN(res) * 8;
1344 else if (absres <= f->avg * 3)
1345 *f->adaptcoeffs = APESIGN(res) * 16;
1347 *f->adaptcoeffs = APESIGN(res) * 32;
1350 *f->adaptcoeffs = 0;
1352 f->avg += (int)(absres - (unsigned)f->avg) / 16;
1354 f->adaptcoeffs[-1] >>= 1;
1355 f->adaptcoeffs[-2] >>= 1;
1356 f->adaptcoeffs[-8] >>= 1;
1361 /* Have we filled the history buffer? */
1362 if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
1363 memmove(f->historybuffer, f->delay - (order * 2),
1364 (order * 2) * sizeof(*f->historybuffer));
1365 f->delay = f->historybuffer + order * 2;
1366 f->adaptcoeffs = f->historybuffer + order;
1371 static void apply_filter(APEContext *ctx, APEFilter *f,
1372 int32_t *data0, int32_t *data1,
1373 int count, int order, int fracbits)
1375 do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
1377 do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
1380 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
1381 int32_t *decoded1, int count)
1385 for (i = 0; i < APE_FILTER_LEVELS; i++) {
1386 if (!ape_filter_orders[ctx->fset][i])
1388 apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
1389 ape_filter_orders[ctx->fset][i],
1390 ape_filter_fracbits[ctx->fset][i]);
1394 static int init_frame_decoder(APEContext *ctx)
1397 if ((ret = init_entropy_decoder(ctx)) < 0)
1399 init_predictor_decoder(ctx);
1401 for (i = 0; i < APE_FILTER_LEVELS; i++) {
1402 if (!ape_filter_orders[ctx->fset][i])
1404 init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
1405 ape_filter_orders[ctx->fset][i]);
1410 static void ape_unpack_mono(APEContext *ctx, int count)
1412 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
1413 /* We are pure silence, so we're done. */
1414 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
1418 ctx->entropy_decode_mono(ctx, count);
1422 /* Now apply the predictor decoding */
1423 ctx->predictor_decode_mono(ctx, count);
1425 /* Pseudo-stereo - just copy left channel to right channel */
1426 if (ctx->channels == 2) {
1427 memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
1431 static void ape_unpack_stereo(APEContext *ctx, int count)
1433 unsigned left, right;
1434 int32_t *decoded0 = ctx->decoded[0];
1435 int32_t *decoded1 = ctx->decoded[1];
1437 if ((ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) == APE_FRAMECODE_STEREO_SILENCE) {
1438 /* We are pure silence, so we're done. */
1439 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
1443 ctx->entropy_decode_stereo(ctx, count);
1447 /* Now apply the predictor decoding */
1448 ctx->predictor_decode_stereo(ctx, count);
1450 /* Decorrelate and scale to output depth */
1452 left = *decoded1 - (unsigned)(*decoded0 / 2);
1453 right = left + *decoded0;
1455 *(decoded0++) = left;
1456 *(decoded1++) = right;
1460 static int ape_decode_frame(AVCodecContext *avctx, void *data,
1461 int *got_frame_ptr, AVPacket *avpkt)
1463 AVFrame *frame = data;
1464 const uint8_t *buf = avpkt->data;
1465 APEContext *s = avctx->priv_data;
1471 uint64_t decoded_buffer_size;
1473 /* this should never be negative, but bad things will happen if it is, so
1474 check it just to make sure. */
1475 av_assert0(s->samples >= 0);
1478 uint32_t nblocks, offset;
1485 if (avpkt->size < 8) {
1486 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1487 return AVERROR_INVALIDDATA;
1489 buf_size = avpkt->size & ~3;
1490 if (buf_size != avpkt->size) {
1491 av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
1492 "extra bytes at the end will be skipped.\n");
1494 if (s->fileversion < 3950) // previous versions overread two bytes
1496 av_fast_padded_malloc(&s->data, &s->data_size, buf_size);
1498 return AVERROR(ENOMEM);
1499 s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,
1501 memset(s->data + (buf_size & ~3), 0, buf_size & 3);
1503 s->data_end = s->data + buf_size;
1505 nblocks = bytestream_get_be32(&s->ptr);
1506 offset = bytestream_get_be32(&s->ptr);
1507 if (s->fileversion >= 3900) {
1509 av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
1512 return AVERROR_INVALIDDATA;
1514 if (s->data_end - s->ptr < offset) {
1515 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1516 return AVERROR_INVALIDDATA;
1520 if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0)
1522 if (s->fileversion > 3800)
1523 skip_bits_long(&s->gb, offset * 8);
1525 skip_bits_long(&s->gb, offset);
1528 if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) {
1529 av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n",
1531 return AVERROR_INVALIDDATA;
1534 /* Initialize the frame decoder */
1535 if (init_frame_decoder(s) < 0) {
1536 av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
1537 return AVERROR_INVALIDDATA;
1539 s->samples = nblocks;
1547 blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
1548 // for old files coefficients were not interleaved,
1549 // so we need to decode all of them at once
1550 if (s->fileversion < 3930)
1551 blockstodecode = s->samples;
1553 /* reallocate decoded sample buffer if needed */
1554 decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer);
1555 av_assert0(decoded_buffer_size <= INT_MAX);
1557 /* get output buffer */
1558 frame->nb_samples = blockstodecode;
1559 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
1564 av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size);
1565 if (!s->decoded_buffer)
1566 return AVERROR(ENOMEM);
1567 memset(s->decoded_buffer, 0, decoded_buffer_size);
1568 s->decoded[0] = s->decoded_buffer;
1569 s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
1573 if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
1574 ape_unpack_mono(s, blockstodecode);
1576 ape_unpack_stereo(s, blockstodecode);
1581 av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
1582 return AVERROR_INVALIDDATA;
1587 for (ch = 0; ch < s->channels; ch++) {
1588 sample8 = (uint8_t *)frame->data[ch];
1589 for (i = 0; i < blockstodecode; i++)
1590 *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
1594 for (ch = 0; ch < s->channels; ch++) {
1595 sample16 = (int16_t *)frame->data[ch];
1596 for (i = 0; i < blockstodecode; i++)
1597 *sample16++ = s->decoded[ch][i];
1601 for (ch = 0; ch < s->channels; ch++) {
1602 sample24 = (int32_t *)frame->data[ch];
1603 for (i = 0; i < blockstodecode; i++)
1604 *sample24++ = s->decoded[ch][i] * 256U;
1609 s->samples -= blockstodecode;
1611 if (avctx->err_recognition & AV_EF_CRCCHECK &&
1612 s->fileversion >= 3900 && s->bps < 24) {
1613 uint32_t crc = s->CRC_state;
1614 const AVCRC *crc_tab = av_crc_get_table(AV_CRC_32_IEEE_LE);
1615 for (i = 0; i < blockstodecode; i++) {
1616 for (ch = 0; ch < s->channels; ch++) {
1617 uint8_t *smp = frame->data[ch] + (i*(s->bps >> 3));
1618 crc = av_crc(crc_tab, crc, smp, s->bps >> 3);
1622 if (!s->samples && (~crc >> 1) ^ s->CRC) {
1623 av_log(avctx, AV_LOG_ERROR, "CRC mismatch! Previously decoded "
1624 "frames may have been affected as well.\n");
1625 if (avctx->err_recognition & AV_EF_EXPLODE)
1626 return AVERROR_INVALIDDATA;
1634 return !s->samples ? avpkt->size : 0;
1637 static void ape_flush(AVCodecContext *avctx)
1639 APEContext *s = avctx->priv_data;
1643 #define OFFSET(x) offsetof(APEContext, x)
1644 #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
1645 static const AVOption options[] = {
1646 { "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" },
1647 { "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" },
1651 static const AVClass ape_decoder_class = {
1652 .class_name = "APE decoder",
1653 .item_name = av_default_item_name,
1655 .version = LIBAVUTIL_VERSION_INT,
1658 AVCodec ff_ape_decoder = {
1660 .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
1661 .type = AVMEDIA_TYPE_AUDIO,
1662 .id = AV_CODEC_ID_APE,
1663 .priv_data_size = sizeof(APEContext),
1664 .init = ape_decode_init,
1665 .close = ape_decode_close,
1666 .decode = ape_decode_frame,
1667 .capabilities = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DELAY |
1669 .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
1671 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
1674 AV_SAMPLE_FMT_NONE },
1675 .priv_class = &ape_decoder_class,