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 Libav.
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.
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.
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
25 #include "libavutil/avassert.h"
26 #include "libavutil/channel_layout.h"
27 #include "libavutil/opt.h"
31 #include "bitstream.h"
33 #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 int32_t coeffsA[2][4]; ///< adaption coefficients
130 int32_t coeffsB[2][5]; ///< adaption coefficients
131 int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
133 unsigned int sample_pos;
136 /** Decoder context */
137 typedef struct APEContext {
138 AVClass *class; ///< class for AVOptions
139 AVCodecContext *avctx;
140 BswapDSPContext bdsp;
143 int samples; ///< samples left to decode in current frame
146 int fileversion; ///< codec version, very important in decoding process
147 int compression_level; ///< compression levels
148 int fset; ///< which filter set to use (calculated from compression level)
149 int flags; ///< global decoder flags
151 uint32_t CRC; ///< frame CRC
152 int frameflags; ///< frame flags
153 APEPredictor predictor; ///< predictor used for final reconstruction
155 int32_t *decoded_buffer;
157 int32_t *decoded[MAX_CHANNELS]; ///< decoded data for each channel
158 int blocks_per_loop; ///< maximum number of samples to decode for each call
160 int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory
162 APERangecoder rc; ///< rangecoder used to decode actual values
163 APERice riceX; ///< rice code parameters for the second channel
164 APERice riceY; ///< rice code parameters for the first channel
165 APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
168 uint8_t *data; ///< current frame data
169 uint8_t *data_end; ///< frame data end
170 int data_size; ///< frame data allocated size
171 const uint8_t *ptr; ///< current position in frame data
175 void (*entropy_decode_mono)(struct APEContext *ctx, int blockstodecode);
176 void (*entropy_decode_stereo)(struct APEContext *ctx, int blockstodecode);
177 void (*predictor_decode_mono)(struct APEContext *ctx, int count);
178 void (*predictor_decode_stereo)(struct APEContext *ctx, int count);
181 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
182 int32_t *decoded1, int count);
184 static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode);
185 static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode);
186 static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode);
187 static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode);
188 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode);
189 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode);
190 static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode);
191 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode);
192 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode);
194 static void predictor_decode_mono_3800(APEContext *ctx, int count);
195 static void predictor_decode_stereo_3800(APEContext *ctx, int count);
196 static void predictor_decode_mono_3930(APEContext *ctx, int count);
197 static void predictor_decode_stereo_3930(APEContext *ctx, int count);
198 static void predictor_decode_mono_3950(APEContext *ctx, int count);
199 static void predictor_decode_stereo_3950(APEContext *ctx, int count);
201 static av_cold int ape_decode_close(AVCodecContext *avctx)
203 APEContext *s = avctx->priv_data;
206 for (i = 0; i < APE_FILTER_LEVELS; i++)
207 av_freep(&s->filterbuf[i]);
209 av_freep(&s->decoded_buffer);
211 s->decoded_size = s->data_size = 0;
216 static int32_t scalarproduct_and_madd_int16_c(int16_t *v1, const int16_t *v2,
224 *v1++ += mul * *v3++;
229 static av_cold int ape_decode_init(AVCodecContext *avctx)
231 APEContext *s = avctx->priv_data;
234 if (avctx->extradata_size != 6) {
235 av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
236 return AVERROR(EINVAL);
238 if (avctx->channels > 2) {
239 av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
240 return AVERROR(EINVAL);
242 s->bps = avctx->bits_per_coded_sample;
245 avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
248 avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
251 avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
254 avpriv_request_sample(avctx,
255 "%d bits per coded sample", s->bps);
256 return AVERROR_PATCHWELCOME;
259 s->channels = avctx->channels;
260 s->fileversion = AV_RL16(avctx->extradata);
261 s->compression_level = AV_RL16(avctx->extradata + 2);
262 s->flags = AV_RL16(avctx->extradata + 4);
264 av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n",
265 s->compression_level, s->flags);
266 if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE ||
267 (s->fileversion < 3930 && s->compression_level == COMPRESSION_LEVEL_INSANE)) {
268 av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
269 s->compression_level);
270 return AVERROR_INVALIDDATA;
272 s->fset = s->compression_level / 1000 - 1;
273 for (i = 0; i < APE_FILTER_LEVELS; i++) {
274 if (!ape_filter_orders[s->fset][i])
276 FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
277 (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
281 if (s->fileversion < 3860) {
282 s->entropy_decode_mono = entropy_decode_mono_0000;
283 s->entropy_decode_stereo = entropy_decode_stereo_0000;
284 } else if (s->fileversion < 3900) {
285 s->entropy_decode_mono = entropy_decode_mono_3860;
286 s->entropy_decode_stereo = entropy_decode_stereo_3860;
287 } else if (s->fileversion < 3930) {
288 s->entropy_decode_mono = entropy_decode_mono_3900;
289 s->entropy_decode_stereo = entropy_decode_stereo_3900;
290 } else if (s->fileversion < 3990) {
291 s->entropy_decode_mono = entropy_decode_mono_3900;
292 s->entropy_decode_stereo = entropy_decode_stereo_3930;
294 s->entropy_decode_mono = entropy_decode_mono_3990;
295 s->entropy_decode_stereo = entropy_decode_stereo_3990;
298 if (s->fileversion < 3930) {
299 s->predictor_decode_mono = predictor_decode_mono_3800;
300 s->predictor_decode_stereo = predictor_decode_stereo_3800;
301 } else if (s->fileversion < 3950) {
302 s->predictor_decode_mono = predictor_decode_mono_3930;
303 s->predictor_decode_stereo = predictor_decode_stereo_3930;
305 s->predictor_decode_mono = predictor_decode_mono_3950;
306 s->predictor_decode_stereo = predictor_decode_stereo_3950;
309 s->adsp.scalarproduct_and_madd_int16 = scalarproduct_and_madd_int16_c;
312 ff_apedsp_init_arm(&s->adsp);
314 ff_apedsp_init_ppc(&s->adsp);
316 ff_apedsp_init_x86(&s->adsp);
318 ff_bswapdsp_init(&s->bdsp);
319 avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
323 ape_decode_close(avctx);
324 return AVERROR(ENOMEM);
328 * @name APE range decoding functions
333 #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
334 #define SHIFT_BITS (CODE_BITS - 9)
335 #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
336 #define BOTTOM_VALUE (TOP_VALUE >> 8)
338 /** Start the decoder */
339 static inline void range_start_decoding(APEContext *ctx)
341 ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
342 ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
343 ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
346 /** Perform normalization */
347 static inline void range_dec_normalize(APEContext *ctx)
349 while (ctx->rc.range <= BOTTOM_VALUE) {
350 ctx->rc.buffer <<= 8;
351 if(ctx->ptr < ctx->data_end) {
352 ctx->rc.buffer += *ctx->ptr;
357 ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
363 * Calculate cumulative frequency for next symbol. Does NO update!
364 * @param ctx decoder context
365 * @param tot_f is the total frequency or (code_value)1<<shift
366 * @return the cumulative frequency
368 static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
370 range_dec_normalize(ctx);
371 ctx->rc.help = ctx->rc.range / tot_f;
372 return ctx->rc.low / ctx->rc.help;
376 * Decode value with given size in bits
377 * @param ctx decoder context
378 * @param shift number of bits to decode
380 static inline int range_decode_culshift(APEContext *ctx, int shift)
382 range_dec_normalize(ctx);
383 ctx->rc.help = ctx->rc.range >> shift;
384 return ctx->rc.low / ctx->rc.help;
389 * Update decoding state
390 * @param ctx decoder context
391 * @param sy_f the interval length (frequency of the symbol)
392 * @param lt_f the lower end (frequency sum of < symbols)
394 static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
396 ctx->rc.low -= ctx->rc.help * lt_f;
397 ctx->rc.range = ctx->rc.help * sy_f;
400 /** Decode n bits (n <= 16) without modelling */
401 static inline int range_decode_bits(APEContext *ctx, int n)
403 int sym = range_decode_culshift(ctx, n);
404 range_decode_update(ctx, 1, sym);
409 #define MODEL_ELEMENTS 64
412 * Fixed probabilities for symbols in Monkey Audio version 3.97
414 static const uint16_t counts_3970[22] = {
415 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
416 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
417 65450, 65469, 65480, 65487, 65491, 65493,
421 * Probability ranges for symbols in Monkey Audio version 3.97
423 static const uint16_t counts_diff_3970[21] = {
424 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
425 1104, 677, 415, 248, 150, 89, 54, 31,
430 * Fixed probabilities for symbols in Monkey Audio version 3.98
432 static const uint16_t counts_3980[22] = {
433 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
434 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
435 65485, 65488, 65490, 65491, 65492, 65493,
439 * Probability ranges for symbols in Monkey Audio version 3.98
441 static const uint16_t counts_diff_3980[21] = {
442 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
443 261, 119, 65, 31, 19, 10, 6, 3,
449 * @param ctx decoder context
450 * @param counts probability range start position
451 * @param counts_diff probability range widths
453 static inline int range_get_symbol(APEContext *ctx,
454 const uint16_t counts[],
455 const uint16_t counts_diff[])
459 cf = range_decode_culshift(ctx, 16);
462 symbol= cf - 65535 + 63;
463 range_decode_update(ctx, 1, cf);
468 /* figure out the symbol inefficiently; a binary search would be much better */
469 for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
471 range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
475 /** @} */ // group rangecoder
477 static inline void update_rice(APERice *rice, unsigned int x)
479 int lim = rice->k ? (1 << (rice->k + 4)) : 0;
480 rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
482 if (rice->ksum < lim)
484 else if (rice->ksum >= (1 << (rice->k + 5)))
488 static inline int get_rice_ook(BitstreamContext *bc, int k)
492 x = get_unary(bc, 1, bitstream_bits_left(bc));
495 x = (x << k) | bitstream_read(bc, k);
500 static inline int ape_decode_value_3860(APEContext *ctx, BitstreamContext *bc,
503 unsigned int x, overflow;
505 overflow = get_unary(bc, 1, bitstream_bits_left(bc));
507 if (ctx->fileversion > 3880) {
508 while (overflow >= 16) {
517 x = (overflow << rice->k) + bitstream_read(bc, rice->k);
519 rice->ksum += x - (rice->ksum + 8 >> 4);
520 if (rice->ksum < (rice->k ? 1 << (rice->k + 4) : 0))
522 else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
525 /* Convert to signed */
532 static inline int ape_decode_value_3900(APEContext *ctx, APERice *rice)
534 unsigned int x, overflow;
537 overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
539 if (overflow == (MODEL_ELEMENTS - 1)) {
540 tmpk = range_decode_bits(ctx, 5);
543 tmpk = (rice->k < 1) ? 0 : rice->k - 1;
545 if (tmpk <= 16 || ctx->fileversion < 3910)
546 x = range_decode_bits(ctx, tmpk);
547 else if (tmpk <= 32) {
548 x = range_decode_bits(ctx, 16);
549 x |= (range_decode_bits(ctx, tmpk - 16) << 16);
551 av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
552 return AVERROR_INVALIDDATA;
554 x += overflow << tmpk;
556 update_rice(rice, x);
558 /* Convert to signed */
565 static inline int ape_decode_value_3990(APEContext *ctx, APERice *rice)
567 unsigned int x, overflow;
570 pivot = rice->ksum >> 5;
574 overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
576 if (overflow == (MODEL_ELEMENTS - 1)) {
577 overflow = range_decode_bits(ctx, 16) << 16;
578 overflow |= range_decode_bits(ctx, 16);
581 if (pivot < 0x10000) {
582 base = range_decode_culfreq(ctx, pivot);
583 range_decode_update(ctx, 1, base);
585 int base_hi = pivot, base_lo;
588 while (base_hi & ~0xFFFF) {
592 base_hi = range_decode_culfreq(ctx, base_hi + 1);
593 range_decode_update(ctx, 1, base_hi);
594 base_lo = range_decode_culfreq(ctx, 1 << bbits);
595 range_decode_update(ctx, 1, base_lo);
597 base = (base_hi << bbits) + base_lo;
600 x = base + overflow * pivot;
602 update_rice(rice, x);
604 /* Convert to signed */
611 static void decode_array_0000(APEContext *ctx, BitstreamContext *bc,
612 int32_t *out, APERice *rice, int blockstodecode)
615 int ksummax, ksummin;
618 for (i = 0; i < FFMIN(blockstodecode, 5); i++) {
619 out[i] = get_rice_ook(&ctx->bc, 10);
620 rice->ksum += out[i];
622 rice->k = av_log2(rice->ksum / 10) + 1;
623 for (; i < FFMIN(blockstodecode, 64); i++) {
624 out[i] = get_rice_ook(&ctx->bc, rice->k);
625 rice->ksum += out[i];
626 rice->k = av_log2(rice->ksum / ((i + 1) * 2)) + 1;
628 ksummax = 1 << rice->k + 7;
629 ksummin = rice->k ? (1 << rice->k + 6) : 0;
630 for (; i < blockstodecode; i++) {
631 out[i] = get_rice_ook(&ctx->bc, rice->k);
632 rice->ksum += out[i] - out[i - 64];
633 while (rice->ksum < ksummin) {
635 ksummin = rice->k ? ksummin >> 1 : 0;
638 while (rice->ksum >= ksummax) {
643 ksummin = ksummin ? ksummin << 1 : 128;
647 for (i = 0; i < blockstodecode; i++) {
649 out[i] = (out[i] >> 1) + 1;
651 out[i] = -(out[i] >> 1);
655 static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode)
657 decode_array_0000(ctx, &ctx->bc, ctx->decoded[0], &ctx->riceY,
661 static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode)
663 decode_array_0000(ctx, &ctx->bc, ctx->decoded[0], &ctx->riceY,
665 decode_array_0000(ctx, &ctx->bc, ctx->decoded[1], &ctx->riceX,
669 static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode)
671 int32_t *decoded0 = ctx->decoded[0];
673 while (blockstodecode--)
674 *decoded0++ = ape_decode_value_3860(ctx, &ctx->bc, &ctx->riceY);
677 static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode)
679 int32_t *decoded0 = ctx->decoded[0];
680 int32_t *decoded1 = ctx->decoded[1];
681 int blocks = blockstodecode;
683 while (blockstodecode--)
684 *decoded0++ = ape_decode_value_3860(ctx, &ctx->bc, &ctx->riceY);
686 *decoded1++ = ape_decode_value_3860(ctx, &ctx->bc, &ctx->riceX);
689 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode)
691 int32_t *decoded0 = ctx->decoded[0];
693 while (blockstodecode--)
694 *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
697 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode)
699 int32_t *decoded0 = ctx->decoded[0];
700 int32_t *decoded1 = ctx->decoded[1];
701 int blocks = blockstodecode;
703 while (blockstodecode--)
704 *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
705 range_dec_normalize(ctx);
706 // because of some implementation peculiarities we need to backpedal here
708 range_start_decoding(ctx);
710 *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
713 static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode)
715 int32_t *decoded0 = ctx->decoded[0];
716 int32_t *decoded1 = ctx->decoded[1];
718 while (blockstodecode--) {
719 *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
720 *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
724 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode)
726 int32_t *decoded0 = ctx->decoded[0];
728 while (blockstodecode--)
729 *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
732 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode)
734 int32_t *decoded0 = ctx->decoded[0];
735 int32_t *decoded1 = ctx->decoded[1];
737 while (blockstodecode--) {
738 *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
739 *decoded1++ = ape_decode_value_3990(ctx, &ctx->riceX);
743 static int init_entropy_decoder(APEContext *ctx)
746 if (ctx->fileversion >= 3900) {
747 if (ctx->data_end - ctx->ptr < 6)
748 return AVERROR_INVALIDDATA;
749 ctx->CRC = bytestream_get_be32(&ctx->ptr);
751 ctx->CRC = bitstream_read(&ctx->bc, 32);
754 /* Read the frame flags if they exist */
756 if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
757 ctx->CRC &= ~0x80000000;
759 if (ctx->data_end - ctx->ptr < 6)
760 return AVERROR_INVALIDDATA;
761 ctx->frameflags = bytestream_get_be32(&ctx->ptr);
764 /* Initialize the rice structs */
766 ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
768 ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
770 if (ctx->fileversion >= 3900) {
771 /* The first 8 bits of input are ignored. */
774 range_start_decoding(ctx);
780 static const int32_t initial_coeffs_fast_3320[1] = {
784 static const int32_t initial_coeffs_a_3800[3] = {
788 static const int32_t initial_coeffs_b_3800[2] = {
792 static const int32_t initial_coeffs_3930[4] = {
796 static void init_predictor_decoder(APEContext *ctx)
798 APEPredictor *p = &ctx->predictor;
800 /* Zero the history buffers */
801 memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
802 p->buf = p->historybuffer;
804 /* Initialize and zero the coefficients */
805 if (ctx->fileversion < 3930) {
806 if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
807 memcpy(p->coeffsA[0], initial_coeffs_fast_3320,
808 sizeof(initial_coeffs_fast_3320));
809 memcpy(p->coeffsA[1], initial_coeffs_fast_3320,
810 sizeof(initial_coeffs_fast_3320));
812 memcpy(p->coeffsA[0], initial_coeffs_a_3800,
813 sizeof(initial_coeffs_a_3800));
814 memcpy(p->coeffsA[1], initial_coeffs_a_3800,
815 sizeof(initial_coeffs_a_3800));
818 memcpy(p->coeffsA[0], initial_coeffs_3930, sizeof(initial_coeffs_3930));
819 memcpy(p->coeffsA[1], initial_coeffs_3930, sizeof(initial_coeffs_3930));
821 memset(p->coeffsB, 0, sizeof(p->coeffsB));
822 if (ctx->fileversion < 3930) {
823 memcpy(p->coeffsB[0], initial_coeffs_b_3800,
824 sizeof(initial_coeffs_b_3800));
825 memcpy(p->coeffsB[1], initial_coeffs_b_3800,
826 sizeof(initial_coeffs_b_3800));
829 p->filterA[0] = p->filterA[1] = 0;
830 p->filterB[0] = p->filterB[1] = 0;
831 p->lastA[0] = p->lastA[1] = 0;
836 /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
837 static inline int APESIGN(int32_t x) {
838 return (x < 0) - (x > 0);
841 static av_always_inline int filter_fast_3320(APEPredictor *p,
842 const int decoded, const int filter,
847 p->buf[delayA] = p->lastA[filter];
848 if (p->sample_pos < 3) {
849 p->lastA[filter] = decoded;
850 p->filterA[filter] = decoded;
854 predictionA = p->buf[delayA] * 2 - p->buf[delayA - 1];
855 p->lastA[filter] = decoded + (predictionA * p->coeffsA[filter][0] >> 9);
857 if ((decoded ^ predictionA) > 0)
858 p->coeffsA[filter][0]++;
860 p->coeffsA[filter][0]--;
862 p->filterA[filter] += p->lastA[filter];
864 return p->filterA[filter];
867 static av_always_inline int filter_3800(APEPredictor *p,
868 const int decoded, const int filter,
869 const int delayA, const int delayB,
870 const int start, const int shift)
872 int32_t predictionA, predictionB, sign;
873 int32_t d0, d1, d2, d3, d4;
875 p->buf[delayA] = p->lastA[filter];
876 p->buf[delayB] = p->filterB[filter];
877 if (p->sample_pos < start) {
878 predictionA = decoded + p->filterA[filter];
879 p->lastA[filter] = decoded;
880 p->filterB[filter] = decoded;
881 p->filterA[filter] = predictionA;
885 d1 = (p->buf[delayA] - p->buf[delayA - 1]) << 1;
886 d0 = p->buf[delayA] + ((p->buf[delayA - 2] - p->buf[delayA - 1]) << 3);
887 d3 = p->buf[delayB] * 2 - p->buf[delayB - 1];
890 predictionA = d0 * p->coeffsA[filter][0] +
891 d1 * p->coeffsA[filter][1] +
892 d2 * p->coeffsA[filter][2];
894 sign = APESIGN(decoded);
895 p->coeffsA[filter][0] += (((d0 >> 30) & 2) - 1) * sign;
896 p->coeffsA[filter][1] += (((d1 >> 28) & 8) - 4) * sign;
897 p->coeffsA[filter][2] += (((d2 >> 28) & 8) - 4) * sign;
899 predictionB = d3 * p->coeffsB[filter][0] -
900 d4 * p->coeffsB[filter][1];
901 p->lastA[filter] = decoded + (predictionA >> 11);
902 sign = APESIGN(p->lastA[filter]);
903 p->coeffsB[filter][0] += (((d3 >> 29) & 4) - 2) * sign;
904 p->coeffsB[filter][1] -= (((d4 >> 30) & 2) - 1) * sign;
906 p->filterB[filter] = p->lastA[filter] + (predictionB >> shift);
907 p->filterA[filter] = p->filterB[filter] + ((p->filterA[filter] * 31) >> 5);
909 return p->filterA[filter];
912 static void long_filter_high_3800(int32_t *buffer, int order, int shift,
913 int32_t *coeffs, int32_t *delay, int length)
916 int32_t dotprod, sign;
918 memset(coeffs, 0, order * sizeof(*coeffs));
919 for (i = 0; i < order; i++)
920 delay[i] = buffer[i];
921 for (i = order; i < length; i++) {
923 sign = APESIGN(buffer[i]);
924 for (j = 0; j < order; j++) {
925 dotprod += delay[j] * coeffs[j];
926 coeffs[j] -= (((delay[j] >> 30) & 2) - 1) * sign;
928 buffer[i] -= dotprod >> shift;
929 for (j = 0; j < order - 1; j++)
930 delay[j] = delay[j + 1];
931 delay[order - 1] = buffer[i];
935 static void long_filter_ehigh_3830(int32_t *buffer, int length)
938 int32_t dotprod, sign;
939 int32_t coeffs[8] = { 0 }, delay[8] = { 0 };
941 for (i = 0; i < length; i++) {
943 sign = APESIGN(buffer[i]);
944 for (j = 7; j >= 0; j--) {
945 dotprod += delay[j] * coeffs[j];
946 coeffs[j] -= (((delay[j] >> 30) & 2) - 1) * sign;
948 for (j = 7; j > 0; j--)
949 delay[j] = delay[j - 1];
950 delay[0] = buffer[i];
951 buffer[i] -= dotprod >> 9;
955 static void predictor_decode_stereo_3800(APEContext *ctx, int count)
957 APEPredictor *p = &ctx->predictor;
958 int32_t *decoded0 = ctx->decoded[0];
959 int32_t *decoded1 = ctx->decoded[1];
960 int32_t coeffs[256], delay[256];
961 int start = 4, shift = 10;
963 if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
965 long_filter_high_3800(decoded0, 16, 9, coeffs, delay, count);
966 long_filter_high_3800(decoded1, 16, 9, coeffs, delay, count);
967 } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
968 int order = 128, shift2 = 11;
970 if (ctx->fileversion >= 3830) {
974 long_filter_ehigh_3830(decoded0 + order, count - order);
975 long_filter_ehigh_3830(decoded1 + order, count - order);
978 long_filter_high_3800(decoded0, order, shift2, coeffs, delay, count);
979 long_filter_high_3800(decoded1, order, shift2, coeffs, delay, count);
983 int X = *decoded0, Y = *decoded1;
984 if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
985 *decoded0 = filter_fast_3320(p, Y, 0, YDELAYA);
987 *decoded1 = filter_fast_3320(p, X, 1, XDELAYA);
990 *decoded0 = filter_3800(p, Y, 0, YDELAYA, YDELAYB,
993 *decoded1 = filter_3800(p, X, 1, XDELAYA, XDELAYB,
1002 /* Have we filled the history buffer? */
1003 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1004 memmove(p->historybuffer, p->buf,
1005 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1006 p->buf = p->historybuffer;
1011 static void predictor_decode_mono_3800(APEContext *ctx, int count)
1013 APEPredictor *p = &ctx->predictor;
1014 int32_t *decoded0 = ctx->decoded[0];
1015 int32_t coeffs[256], delay[256];
1016 int start = 4, shift = 10;
1018 if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
1020 long_filter_high_3800(decoded0, 16, 9, coeffs, delay, count);
1021 } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
1022 int order = 128, shift2 = 11;
1024 if (ctx->fileversion >= 3830) {
1028 long_filter_ehigh_3830(decoded0 + order, count - order);
1031 long_filter_high_3800(decoded0, order, shift2, coeffs, delay, count);
1035 if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
1036 *decoded0 = filter_fast_3320(p, *decoded0, 0, YDELAYA);
1039 *decoded0 = filter_3800(p, *decoded0, 0, YDELAYA, YDELAYB,
1048 /* Have we filled the history buffer? */
1049 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1050 memmove(p->historybuffer, p->buf,
1051 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1052 p->buf = p->historybuffer;
1057 static av_always_inline int predictor_update_3930(APEPredictor *p,
1058 const int decoded, const int filter,
1061 int32_t predictionA, sign;
1062 int32_t d0, d1, d2, d3;
1064 p->buf[delayA] = p->lastA[filter];
1065 d0 = p->buf[delayA ];
1066 d1 = p->buf[delayA ] - p->buf[delayA - 1];
1067 d2 = p->buf[delayA - 1] - p->buf[delayA - 2];
1068 d3 = p->buf[delayA - 2] - p->buf[delayA - 3];
1070 predictionA = d0 * p->coeffsA[filter][0] +
1071 d1 * p->coeffsA[filter][1] +
1072 d2 * p->coeffsA[filter][2] +
1073 d3 * p->coeffsA[filter][3];
1075 p->lastA[filter] = decoded + (predictionA >> 9);
1076 p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
1078 sign = APESIGN(decoded);
1079 p->coeffsA[filter][0] += ((d0 < 0) * 2 - 1) * sign;
1080 p->coeffsA[filter][1] += ((d1 < 0) * 2 - 1) * sign;
1081 p->coeffsA[filter][2] += ((d2 < 0) * 2 - 1) * sign;
1082 p->coeffsA[filter][3] += ((d3 < 0) * 2 - 1) * sign;
1084 return p->filterA[filter];
1087 static void predictor_decode_stereo_3930(APEContext *ctx, int count)
1089 APEPredictor *p = &ctx->predictor;
1090 int32_t *decoded0 = ctx->decoded[0];
1091 int32_t *decoded1 = ctx->decoded[1];
1093 ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1097 int Y = *decoded1, X = *decoded0;
1098 *decoded0 = predictor_update_3930(p, Y, 0, YDELAYA);
1100 *decoded1 = predictor_update_3930(p, X, 1, XDELAYA);
1106 /* Have we filled the history buffer? */
1107 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1108 memmove(p->historybuffer, p->buf,
1109 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1110 p->buf = p->historybuffer;
1115 static void predictor_decode_mono_3930(APEContext *ctx, int count)
1117 APEPredictor *p = &ctx->predictor;
1118 int32_t *decoded0 = ctx->decoded[0];
1120 ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1123 *decoded0 = predictor_update_3930(p, *decoded0, 0, YDELAYA);
1128 /* Have we filled the history buffer? */
1129 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1130 memmove(p->historybuffer, p->buf,
1131 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1132 p->buf = p->historybuffer;
1137 static av_always_inline int predictor_update_filter(APEPredictor *p,
1138 const int decoded, const int filter,
1139 const int delayA, const int delayB,
1140 const int adaptA, const int adaptB)
1142 int32_t predictionA, predictionB, sign;
1144 p->buf[delayA] = p->lastA[filter];
1145 p->buf[adaptA] = APESIGN(p->buf[delayA]);
1146 p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
1147 p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
1149 predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
1150 p->buf[delayA - 1] * p->coeffsA[filter][1] +
1151 p->buf[delayA - 2] * p->coeffsA[filter][2] +
1152 p->buf[delayA - 3] * p->coeffsA[filter][3];
1154 /* Apply a scaled first-order filter compression */
1155 p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
1156 p->buf[adaptB] = APESIGN(p->buf[delayB]);
1157 p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
1158 p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
1159 p->filterB[filter] = p->filterA[filter ^ 1];
1161 predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
1162 p->buf[delayB - 1] * p->coeffsB[filter][1] +
1163 p->buf[delayB - 2] * p->coeffsB[filter][2] +
1164 p->buf[delayB - 3] * p->coeffsB[filter][3] +
1165 p->buf[delayB - 4] * p->coeffsB[filter][4];
1167 p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
1168 p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
1170 sign = APESIGN(decoded);
1171 p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
1172 p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
1173 p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
1174 p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
1175 p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
1176 p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
1177 p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
1178 p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
1179 p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
1181 return p->filterA[filter];
1184 static void predictor_decode_stereo_3950(APEContext *ctx, int count)
1186 APEPredictor *p = &ctx->predictor;
1187 int32_t *decoded0 = ctx->decoded[0];
1188 int32_t *decoded1 = ctx->decoded[1];
1190 ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1194 *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
1195 YADAPTCOEFFSA, YADAPTCOEFFSB);
1197 *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
1198 XADAPTCOEFFSA, XADAPTCOEFFSB);
1204 /* Have we filled the history buffer? */
1205 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1206 memmove(p->historybuffer, p->buf,
1207 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1208 p->buf = p->historybuffer;
1213 static void predictor_decode_mono_3950(APEContext *ctx, int count)
1215 APEPredictor *p = &ctx->predictor;
1216 int32_t *decoded0 = ctx->decoded[0];
1217 int32_t predictionA, currentA, A, sign;
1219 ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1221 currentA = p->lastA[0];
1226 p->buf[YDELAYA] = currentA;
1227 p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
1229 predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
1230 p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
1231 p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
1232 p->buf[YDELAYA - 3] * p->coeffsA[0][3];
1234 currentA = A + (predictionA >> 10);
1236 p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
1237 p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
1240 p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
1241 p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
1242 p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
1243 p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
1247 /* Have we filled the history buffer? */
1248 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1249 memmove(p->historybuffer, p->buf,
1250 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1251 p->buf = p->historybuffer;
1254 p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
1255 *(decoded0++) = p->filterA[0];
1258 p->lastA[0] = currentA;
1261 static void do_init_filter(APEFilter *f, int16_t *buf, int order)
1264 f->historybuffer = buf + order;
1265 f->delay = f->historybuffer + order * 2;
1266 f->adaptcoeffs = f->historybuffer + order;
1268 memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
1269 memset(f->coeffs, 0, order * sizeof(*f->coeffs));
1273 static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
1275 do_init_filter(&f[0], buf, order);
1276 do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
1279 static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
1280 int32_t *data, int count, int order, int fracbits)
1286 /* round fixedpoint scalar product */
1287 res = ctx->adsp.scalarproduct_and_madd_int16(f->coeffs,
1289 f->adaptcoeffs - order,
1290 order, APESIGN(*data));
1291 res = (res + (1 << (fracbits - 1))) >> fracbits;
1295 /* Update the output history */
1296 *f->delay++ = av_clip_int16(res);
1298 if (version < 3980) {
1299 /* Version ??? to < 3.98 files (untested) */
1300 f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
1301 f->adaptcoeffs[-4] >>= 1;
1302 f->adaptcoeffs[-8] >>= 1;
1304 /* Version 3.98 and later files */
1306 /* Update the adaption coefficients */
1307 absres = FFABS(res);
1309 *f->adaptcoeffs = APESIGN(res) *
1310 (8 << ((absres > f->avg * 3) + (absres > f->avg * 4 / 3)));
1311 /* equivalent to the following code
1312 if (absres <= f->avg * 4 / 3)
1313 *f->adaptcoeffs = APESIGN(res) * 8;
1314 else if (absres <= f->avg * 3)
1315 *f->adaptcoeffs = APESIGN(res) * 16;
1317 *f->adaptcoeffs = APESIGN(res) * 32;
1320 *f->adaptcoeffs = 0;
1322 f->avg += (absres - f->avg) / 16;
1324 f->adaptcoeffs[-1] >>= 1;
1325 f->adaptcoeffs[-2] >>= 1;
1326 f->adaptcoeffs[-8] >>= 1;
1331 /* Have we filled the history buffer? */
1332 if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
1333 memmove(f->historybuffer, f->delay - (order * 2),
1334 (order * 2) * sizeof(*f->historybuffer));
1335 f->delay = f->historybuffer + order * 2;
1336 f->adaptcoeffs = f->historybuffer + order;
1341 static void apply_filter(APEContext *ctx, APEFilter *f,
1342 int32_t *data0, int32_t *data1,
1343 int count, int order, int fracbits)
1345 do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
1347 do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
1350 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
1351 int32_t *decoded1, int count)
1355 for (i = 0; i < APE_FILTER_LEVELS; i++) {
1356 if (!ape_filter_orders[ctx->fset][i])
1358 apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
1359 ape_filter_orders[ctx->fset][i],
1360 ape_filter_fracbits[ctx->fset][i]);
1364 static int init_frame_decoder(APEContext *ctx)
1367 if ((ret = init_entropy_decoder(ctx)) < 0)
1369 init_predictor_decoder(ctx);
1371 for (i = 0; i < APE_FILTER_LEVELS; i++) {
1372 if (!ape_filter_orders[ctx->fset][i])
1374 init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
1375 ape_filter_orders[ctx->fset][i]);
1380 static void ape_unpack_mono(APEContext *ctx, int count)
1382 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
1383 /* We are pure silence, so we're done. */
1384 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
1388 ctx->entropy_decode_mono(ctx, count);
1390 /* Now apply the predictor decoding */
1391 ctx->predictor_decode_mono(ctx, count);
1393 /* Pseudo-stereo - just copy left channel to right channel */
1394 if (ctx->channels == 2) {
1395 memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
1399 static void ape_unpack_stereo(APEContext *ctx, int count)
1401 int32_t left, right;
1402 int32_t *decoded0 = ctx->decoded[0];
1403 int32_t *decoded1 = ctx->decoded[1];
1405 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
1406 /* We are pure silence, so we're done. */
1407 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
1411 ctx->entropy_decode_stereo(ctx, count);
1413 /* Now apply the predictor decoding */
1414 ctx->predictor_decode_stereo(ctx, count);
1416 /* Decorrelate and scale to output depth */
1418 left = *decoded1 - (*decoded0 / 2);
1419 right = left + *decoded0;
1421 *(decoded0++) = left;
1422 *(decoded1++) = right;
1426 static int ape_decode_frame(AVCodecContext *avctx, void *data,
1427 int *got_frame_ptr, AVPacket *avpkt)
1429 AVFrame *frame = data;
1430 const uint8_t *buf = avpkt->data;
1431 APEContext *s = avctx->priv_data;
1438 /* this should never be negative, but bad things will happen if it is, so
1439 check it just to make sure. */
1440 av_assert0(s->samples >= 0);
1443 uint32_t nblocks, offset;
1450 if (avpkt->size < 8) {
1451 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1452 return AVERROR_INVALIDDATA;
1454 buf_size = avpkt->size & ~3;
1455 if (buf_size != avpkt->size) {
1456 av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
1457 "extra bytes at the end will be skipped.\n");
1459 if (s->fileversion < 3950) // previous versions overread two bytes
1461 av_fast_malloc(&s->data, &s->data_size, buf_size);
1463 return AVERROR(ENOMEM);
1464 s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,
1466 memset(s->data + (buf_size & ~3), 0, buf_size & 3);
1468 s->data_end = s->data + buf_size;
1470 nblocks = bytestream_get_be32(&s->ptr);
1471 offset = bytestream_get_be32(&s->ptr);
1472 if (s->fileversion >= 3900) {
1474 av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
1476 return AVERROR_INVALIDDATA;
1478 if (s->data_end - s->ptr < offset) {
1479 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1480 return AVERROR_INVALIDDATA;
1484 bitstream_init8(&s->bc, s->ptr, s->data_end - s->ptr);
1485 if (s->fileversion > 3800)
1486 bitstream_skip(&s->bc, offset * 8);
1488 bitstream_skip(&s->bc, offset);
1491 if (!nblocks || nblocks > INT_MAX) {
1492 av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n",
1494 return AVERROR_INVALIDDATA;
1496 s->samples = nblocks;
1498 /* Initialize the frame decoder */
1499 if (init_frame_decoder(s) < 0) {
1500 av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
1501 return AVERROR_INVALIDDATA;
1511 blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
1512 // for old files coefficients were not interleaved,
1513 // so we need to decode all of them at once
1514 if (s->fileversion < 3930)
1515 blockstodecode = s->samples;
1517 /* reallocate decoded sample buffer if needed */
1518 av_fast_malloc(&s->decoded_buffer, &s->decoded_size,
1519 2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));
1520 if (!s->decoded_buffer)
1521 return AVERROR(ENOMEM);
1522 memset(s->decoded_buffer, 0, s->decoded_size);
1523 s->decoded[0] = s->decoded_buffer;
1524 s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
1526 /* get output buffer */
1527 frame->nb_samples = blockstodecode;
1528 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
1529 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1535 if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
1536 ape_unpack_mono(s, blockstodecode);
1538 ape_unpack_stereo(s, blockstodecode);
1543 av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
1544 return AVERROR_INVALIDDATA;
1549 for (ch = 0; ch < s->channels; ch++) {
1550 sample8 = (uint8_t *)frame->data[ch];
1551 for (i = 0; i < blockstodecode; i++)
1552 *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
1556 for (ch = 0; ch < s->channels; ch++) {
1557 sample16 = (int16_t *)frame->data[ch];
1558 for (i = 0; i < blockstodecode; i++)
1559 *sample16++ = s->decoded[ch][i];
1563 for (ch = 0; ch < s->channels; ch++) {
1564 sample24 = (int32_t *)frame->data[ch];
1565 for (i = 0; i < blockstodecode; i++)
1566 *sample24++ = s->decoded[ch][i] << 8;
1571 s->samples -= blockstodecode;
1575 return (s->samples == 0) ? avpkt->size : 0;
1578 static void ape_flush(AVCodecContext *avctx)
1580 APEContext *s = avctx->priv_data;
1584 #define OFFSET(x) offsetof(APEContext, x)
1585 #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
1586 static const AVOption options[] = {
1587 { "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" },
1588 { "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" },
1592 static const AVClass ape_decoder_class = {
1593 .class_name = "APE decoder",
1594 .item_name = av_default_item_name,
1596 .version = LIBAVUTIL_VERSION_INT,
1599 AVCodec ff_ape_decoder = {
1601 .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
1602 .type = AVMEDIA_TYPE_AUDIO,
1603 .id = AV_CODEC_ID_APE,
1604 .priv_data_size = sizeof(APEContext),
1605 .init = ape_decode_init,
1606 .close = ape_decode_close,
1607 .decode = ape_decode_frame,
1608 .capabilities = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DELAY |
1611 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
1614 AV_SAMPLE_FMT_NONE },
1615 .priv_class = &ape_decoder_class,