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/opt.h"
28 #include "lossless_audiodsp.h"
31 #include "bytestream.h"
38 * Monkey's Audio lossless audio decoder
41 #define MAX_CHANNELS 2
42 #define MAX_BYTESPERSAMPLE 3
44 #define APE_FRAMECODE_MONO_SILENCE 1
45 #define APE_FRAMECODE_STEREO_SILENCE 3
46 #define APE_FRAMECODE_PSEUDO_STEREO 4
48 #define HISTORY_SIZE 512
49 #define PREDICTOR_ORDER 8
50 /** Total size of all predictor histories */
51 #define PREDICTOR_SIZE 50
53 #define YDELAYA (18 + PREDICTOR_ORDER*4)
54 #define YDELAYB (18 + PREDICTOR_ORDER*3)
55 #define XDELAYA (18 + PREDICTOR_ORDER*2)
56 #define XDELAYB (18 + PREDICTOR_ORDER)
58 #define YADAPTCOEFFSA 18
59 #define XADAPTCOEFFSA 14
60 #define YADAPTCOEFFSB 10
61 #define XADAPTCOEFFSB 5
64 * Possible compression levels
67 enum APECompressionLevel {
68 COMPRESSION_LEVEL_FAST = 1000,
69 COMPRESSION_LEVEL_NORMAL = 2000,
70 COMPRESSION_LEVEL_HIGH = 3000,
71 COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
72 COMPRESSION_LEVEL_INSANE = 5000
76 #define APE_FILTER_LEVELS 3
78 /** Filter orders depending on compression level */
79 static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
87 /** Filter fraction bits depending on compression level */
88 static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
97 /** Filters applied to the decoded data */
98 typedef struct APEFilter {
99 int16_t *coeffs; ///< actual coefficients used in filtering
100 int16_t *adaptcoeffs; ///< adaptive filter coefficients used for correcting of actual filter coefficients
101 int16_t *historybuffer; ///< filter memory
102 int16_t *delay; ///< filtered values
107 typedef struct APERice {
112 typedef struct APERangecoder {
113 uint32_t low; ///< low end of interval
114 uint32_t range; ///< length of interval
115 uint32_t help; ///< bytes_to_follow resp. intermediate value
116 unsigned int buffer; ///< buffer for input/output
119 /** Filter histories */
120 typedef struct APEPredictor {
128 uint32_t coeffsA[2][4]; ///< adaption coefficients
129 uint32_t coeffsB[2][5]; ///< adaption coefficients
130 int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
132 unsigned int sample_pos;
135 /** Decoder context */
136 typedef struct APEContext {
137 AVClass *class; ///< class for AVOptions
138 AVCodecContext *avctx;
139 BswapDSPContext bdsp;
140 LLAudDSPContext adsp;
142 int samples; ///< samples left to decode in current frame
145 int fileversion; ///< codec version, very important in decoding process
146 int compression_level; ///< compression levels
147 int fset; ///< which filter set to use (calculated from compression level)
148 int flags; ///< global decoder flags
150 uint32_t CRC; ///< frame CRC
151 int frameflags; ///< frame flags
152 APEPredictor predictor; ///< predictor used for final reconstruction
154 int32_t *decoded_buffer;
156 int32_t *decoded[MAX_CHANNELS]; ///< decoded data for each channel
157 int blocks_per_loop; ///< maximum number of samples to decode for each call
159 int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory
161 APERangecoder rc; ///< rangecoder used to decode actual values
162 APERice riceX; ///< rice code parameters for the second channel
163 APERice riceY; ///< rice code parameters for the first channel
164 APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
167 uint8_t *data; ///< current frame data
168 uint8_t *data_end; ///< frame data end
169 int data_size; ///< frame data allocated size
170 const uint8_t *ptr; ///< current position in frame data
174 void (*entropy_decode_mono)(struct APEContext *ctx, int blockstodecode);
175 void (*entropy_decode_stereo)(struct APEContext *ctx, int blockstodecode);
176 void (*predictor_decode_mono)(struct APEContext *ctx, int count);
177 void (*predictor_decode_stereo)(struct APEContext *ctx, int count);
180 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
181 int32_t *decoded1, int count);
183 static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode);
184 static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode);
185 static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode);
186 static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode);
187 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode);
188 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode);
189 static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode);
190 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode);
191 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode);
193 static void predictor_decode_mono_3800(APEContext *ctx, int count);
194 static void predictor_decode_stereo_3800(APEContext *ctx, int count);
195 static void predictor_decode_mono_3930(APEContext *ctx, int count);
196 static void predictor_decode_stereo_3930(APEContext *ctx, int count);
197 static void predictor_decode_mono_3950(APEContext *ctx, int count);
198 static void predictor_decode_stereo_3950(APEContext *ctx, int count);
200 static av_cold int ape_decode_close(AVCodecContext *avctx)
202 APEContext *s = avctx->priv_data;
205 for (i = 0; i < APE_FILTER_LEVELS; i++)
206 av_freep(&s->filterbuf[i]);
208 av_freep(&s->decoded_buffer);
210 s->decoded_size = s->data_size = 0;
215 static av_cold int ape_decode_init(AVCodecContext *avctx)
217 APEContext *s = avctx->priv_data;
220 if (avctx->extradata_size != 6) {
221 av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
222 return AVERROR(EINVAL);
224 if (avctx->channels > 2) {
225 av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
226 return AVERROR(EINVAL);
228 s->bps = avctx->bits_per_coded_sample;
231 avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
234 avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
237 avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
240 avpriv_request_sample(avctx,
241 "%d bits per coded sample", s->bps);
242 return AVERROR_PATCHWELCOME;
245 s->channels = avctx->channels;
246 s->fileversion = AV_RL16(avctx->extradata);
247 s->compression_level = AV_RL16(avctx->extradata + 2);
248 s->flags = AV_RL16(avctx->extradata + 4);
250 av_log(avctx, AV_LOG_VERBOSE, "Compression Level: %d - Flags: %d\n",
251 s->compression_level, s->flags);
252 if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE ||
253 !s->compression_level ||
254 (s->fileversion < 3930 && s->compression_level == COMPRESSION_LEVEL_INSANE)) {
255 av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
256 s->compression_level);
257 return AVERROR_INVALIDDATA;
259 s->fset = s->compression_level / 1000 - 1;
260 for (i = 0; i < APE_FILTER_LEVELS; i++) {
261 if (!ape_filter_orders[s->fset][i])
263 FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
264 (ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
268 if (s->fileversion < 3860) {
269 s->entropy_decode_mono = entropy_decode_mono_0000;
270 s->entropy_decode_stereo = entropy_decode_stereo_0000;
271 } else if (s->fileversion < 3900) {
272 s->entropy_decode_mono = entropy_decode_mono_3860;
273 s->entropy_decode_stereo = entropy_decode_stereo_3860;
274 } else if (s->fileversion < 3930) {
275 s->entropy_decode_mono = entropy_decode_mono_3900;
276 s->entropy_decode_stereo = entropy_decode_stereo_3900;
277 } else if (s->fileversion < 3990) {
278 s->entropy_decode_mono = entropy_decode_mono_3900;
279 s->entropy_decode_stereo = entropy_decode_stereo_3930;
281 s->entropy_decode_mono = entropy_decode_mono_3990;
282 s->entropy_decode_stereo = entropy_decode_stereo_3990;
285 if (s->fileversion < 3930) {
286 s->predictor_decode_mono = predictor_decode_mono_3800;
287 s->predictor_decode_stereo = predictor_decode_stereo_3800;
288 } else if (s->fileversion < 3950) {
289 s->predictor_decode_mono = predictor_decode_mono_3930;
290 s->predictor_decode_stereo = predictor_decode_stereo_3930;
292 s->predictor_decode_mono = predictor_decode_mono_3950;
293 s->predictor_decode_stereo = predictor_decode_stereo_3950;
296 ff_bswapdsp_init(&s->bdsp);
297 ff_llauddsp_init(&s->adsp);
298 avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
302 ape_decode_close(avctx);
303 return AVERROR(ENOMEM);
307 * @name APE range decoding functions
312 #define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
313 #define SHIFT_BITS (CODE_BITS - 9)
314 #define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
315 #define BOTTOM_VALUE (TOP_VALUE >> 8)
317 /** Start the decoder */
318 static inline void range_start_decoding(APEContext *ctx)
320 ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
321 ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
322 ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
325 /** Perform normalization */
326 static inline void range_dec_normalize(APEContext *ctx)
328 while (ctx->rc.range <= BOTTOM_VALUE) {
329 ctx->rc.buffer <<= 8;
330 if(ctx->ptr < ctx->data_end) {
331 ctx->rc.buffer += *ctx->ptr;
336 ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
342 * Calculate cumulative frequency for next symbol. Does NO update!
343 * @param ctx decoder context
344 * @param tot_f is the total frequency or (code_value)1<<shift
345 * @return the cumulative frequency
347 static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
349 range_dec_normalize(ctx);
350 ctx->rc.help = ctx->rc.range / tot_f;
351 return ctx->rc.low / ctx->rc.help;
355 * Decode value with given size in bits
356 * @param ctx decoder context
357 * @param shift number of bits to decode
359 static inline int range_decode_culshift(APEContext *ctx, int shift)
361 range_dec_normalize(ctx);
362 ctx->rc.help = ctx->rc.range >> shift;
363 return ctx->rc.low / ctx->rc.help;
368 * Update decoding state
369 * @param ctx decoder context
370 * @param sy_f the interval length (frequency of the symbol)
371 * @param lt_f the lower end (frequency sum of < symbols)
373 static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
375 ctx->rc.low -= ctx->rc.help * lt_f;
376 ctx->rc.range = ctx->rc.help * sy_f;
379 /** Decode n bits (n <= 16) without modelling */
380 static inline int range_decode_bits(APEContext *ctx, int n)
382 int sym = range_decode_culshift(ctx, n);
383 range_decode_update(ctx, 1, sym);
388 #define MODEL_ELEMENTS 64
391 * Fixed probabilities for symbols in Monkey Audio version 3.97
393 static const uint16_t counts_3970[22] = {
394 0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
395 62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
396 65450, 65469, 65480, 65487, 65491, 65493,
400 * Probability ranges for symbols in Monkey Audio version 3.97
402 static const uint16_t counts_diff_3970[21] = {
403 14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
404 1104, 677, 415, 248, 150, 89, 54, 31,
409 * Fixed probabilities for symbols in Monkey Audio version 3.98
411 static const uint16_t counts_3980[22] = {
412 0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
413 64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
414 65485, 65488, 65490, 65491, 65492, 65493,
418 * Probability ranges for symbols in Monkey Audio version 3.98
420 static const uint16_t counts_diff_3980[21] = {
421 19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
422 261, 119, 65, 31, 19, 10, 6, 3,
428 * @param ctx decoder context
429 * @param counts probability range start position
430 * @param counts_diff probability range widths
432 static inline int range_get_symbol(APEContext *ctx,
433 const uint16_t counts[],
434 const uint16_t counts_diff[])
438 cf = range_decode_culshift(ctx, 16);
441 symbol= cf - 65535 + 63;
442 range_decode_update(ctx, 1, cf);
447 /* figure out the symbol inefficiently; a binary search would be much better */
448 for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
450 range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
454 /** @} */ // group rangecoder
456 static inline void update_rice(APERice *rice, unsigned int x)
458 int lim = rice->k ? (1 << (rice->k + 4)) : 0;
459 rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
461 if (rice->ksum < lim)
463 else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
467 static inline int get_rice_ook(GetBitContext *gb, int k)
471 x = get_unary(gb, 1, get_bits_left(gb));
474 x = (x << k) | get_bits(gb, k);
479 static inline int ape_decode_value_3860(APEContext *ctx, GetBitContext *gb,
482 unsigned int x, overflow;
484 overflow = get_unary(gb, 1, get_bits_left(gb));
486 if (ctx->fileversion > 3880) {
487 while (overflow >= 16) {
495 else if(rice->k <= MIN_CACHE_BITS) {
496 x = (overflow << rice->k) + get_bits(gb, rice->k);
498 av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %"PRIu32"\n", rice->k);
500 return AVERROR_INVALIDDATA;
502 rice->ksum += x - (rice->ksum + 8 >> 4);
503 if (rice->ksum < (rice->k ? 1 << (rice->k + 4) : 0))
505 else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
508 /* Convert to signed */
509 return ((x >> 1) ^ ((x & 1) - 1)) + 1;
512 static inline int ape_decode_value_3900(APEContext *ctx, APERice *rice)
514 unsigned int x, overflow;
517 overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
519 if (overflow == (MODEL_ELEMENTS - 1)) {
520 tmpk = range_decode_bits(ctx, 5);
523 tmpk = (rice->k < 1) ? 0 : rice->k - 1;
525 if (tmpk <= 16 || ctx->fileversion < 3910) {
527 av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
528 return AVERROR_INVALIDDATA;
530 x = range_decode_bits(ctx, tmpk);
531 } else if (tmpk <= 31) {
532 x = range_decode_bits(ctx, 16);
533 x |= (range_decode_bits(ctx, tmpk - 16) << 16);
535 av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
536 return AVERROR_INVALIDDATA;
538 x += overflow << tmpk;
540 update_rice(rice, x);
542 /* Convert to signed */
543 return ((x >> 1) ^ ((x & 1) - 1)) + 1;
546 static inline int ape_decode_value_3990(APEContext *ctx, APERice *rice)
548 unsigned int x, overflow;
551 pivot = rice->ksum >> 5;
555 overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
557 if (overflow == (MODEL_ELEMENTS - 1)) {
558 overflow = (unsigned)range_decode_bits(ctx, 16) << 16;
559 overflow |= range_decode_bits(ctx, 16);
562 if (pivot < 0x10000) {
563 base = range_decode_culfreq(ctx, pivot);
564 range_decode_update(ctx, 1, base);
566 int base_hi = pivot, base_lo;
569 while (base_hi & ~0xFFFF) {
573 base_hi = range_decode_culfreq(ctx, base_hi + 1);
574 range_decode_update(ctx, 1, base_hi);
575 base_lo = range_decode_culfreq(ctx, 1 << bbits);
576 range_decode_update(ctx, 1, base_lo);
578 base = (base_hi << bbits) + base_lo;
581 x = base + overflow * pivot;
583 update_rice(rice, x);
585 /* Convert to signed */
586 return ((x >> 1) ^ ((x & 1) - 1)) + 1;
589 static void decode_array_0000(APEContext *ctx, GetBitContext *gb,
590 int32_t *out, APERice *rice, int blockstodecode)
593 unsigned ksummax, ksummin;
596 for (i = 0; i < FFMIN(blockstodecode, 5); i++) {
597 out[i] = get_rice_ook(&ctx->gb, 10);
598 rice->ksum += out[i];
600 rice->k = av_log2(rice->ksum / 10) + 1;
603 for (; i < FFMIN(blockstodecode, 64); i++) {
604 out[i] = get_rice_ook(&ctx->gb, rice->k);
605 rice->ksum += out[i];
606 rice->k = av_log2(rice->ksum / ((i + 1) * 2)) + 1;
610 ksummax = 1 << rice->k + 7;
611 ksummin = rice->k ? (1 << rice->k + 6) : 0;
612 for (; i < blockstodecode; i++) {
613 if (get_bits_left(&ctx->gb) < 1) {
617 out[i] = get_rice_ook(&ctx->gb, rice->k);
618 rice->ksum += out[i] - (unsigned)out[i - 64];
619 while (rice->ksum < ksummin) {
621 ksummin = rice->k ? ksummin >> 1 : 0;
624 while (rice->ksum >= ksummax) {
629 ksummin = ksummin ? ksummin << 1 : 128;
633 for (i = 0; i < blockstodecode; i++)
634 out[i] = ((out[i] >> 1) ^ ((out[i] & 1) - 1)) + 1;
637 static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode)
639 decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
643 static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode)
645 decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
647 decode_array_0000(ctx, &ctx->gb, ctx->decoded[1], &ctx->riceX,
651 static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode)
653 int32_t *decoded0 = ctx->decoded[0];
655 while (blockstodecode--)
656 *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
659 static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode)
661 int32_t *decoded0 = ctx->decoded[0];
662 int32_t *decoded1 = ctx->decoded[1];
663 int blocks = blockstodecode;
665 while (blockstodecode--)
666 *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
668 *decoded1++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceX);
671 static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode)
673 int32_t *decoded0 = ctx->decoded[0];
675 while (blockstodecode--)
676 *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
679 static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode)
681 int32_t *decoded0 = ctx->decoded[0];
682 int32_t *decoded1 = ctx->decoded[1];
683 int blocks = blockstodecode;
685 while (blockstodecode--)
686 *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
687 range_dec_normalize(ctx);
688 // because of some implementation peculiarities we need to backpedal here
690 range_start_decoding(ctx);
692 *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
695 static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode)
697 int32_t *decoded0 = ctx->decoded[0];
698 int32_t *decoded1 = ctx->decoded[1];
700 while (blockstodecode--) {
701 *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
702 *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
706 static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode)
708 int32_t *decoded0 = ctx->decoded[0];
710 while (blockstodecode--)
711 *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
714 static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode)
716 int32_t *decoded0 = ctx->decoded[0];
717 int32_t *decoded1 = ctx->decoded[1];
719 while (blockstodecode--) {
720 *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
721 *decoded1++ = ape_decode_value_3990(ctx, &ctx->riceX);
725 static int init_entropy_decoder(APEContext *ctx)
728 if (ctx->fileversion >= 3900) {
729 if (ctx->data_end - ctx->ptr < 6)
730 return AVERROR_INVALIDDATA;
731 ctx->CRC = bytestream_get_be32(&ctx->ptr);
733 ctx->CRC = get_bits_long(&ctx->gb, 32);
736 /* Read the frame flags if they exist */
738 if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
739 ctx->CRC &= ~0x80000000;
741 if (ctx->data_end - ctx->ptr < 6)
742 return AVERROR_INVALIDDATA;
743 ctx->frameflags = bytestream_get_be32(&ctx->ptr);
746 /* Initialize the rice structs */
748 ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
750 ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
752 if (ctx->fileversion >= 3900) {
753 /* The first 8 bits of input are ignored. */
756 range_start_decoding(ctx);
762 static const int32_t initial_coeffs_fast_3320[1] = {
766 static const int32_t initial_coeffs_a_3800[3] = {
770 static const int32_t initial_coeffs_b_3800[2] = {
774 static const int32_t initial_coeffs_3930[4] = {
778 static void init_predictor_decoder(APEContext *ctx)
780 APEPredictor *p = &ctx->predictor;
782 /* Zero the history buffers */
783 memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
784 p->buf = p->historybuffer;
786 /* Initialize and zero the coefficients */
787 if (ctx->fileversion < 3930) {
788 if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
789 memcpy(p->coeffsA[0], initial_coeffs_fast_3320,
790 sizeof(initial_coeffs_fast_3320));
791 memcpy(p->coeffsA[1], initial_coeffs_fast_3320,
792 sizeof(initial_coeffs_fast_3320));
794 memcpy(p->coeffsA[0], initial_coeffs_a_3800,
795 sizeof(initial_coeffs_a_3800));
796 memcpy(p->coeffsA[1], initial_coeffs_a_3800,
797 sizeof(initial_coeffs_a_3800));
800 memcpy(p->coeffsA[0], initial_coeffs_3930, sizeof(initial_coeffs_3930));
801 memcpy(p->coeffsA[1], initial_coeffs_3930, sizeof(initial_coeffs_3930));
803 memset(p->coeffsB, 0, sizeof(p->coeffsB));
804 if (ctx->fileversion < 3930) {
805 memcpy(p->coeffsB[0], initial_coeffs_b_3800,
806 sizeof(initial_coeffs_b_3800));
807 memcpy(p->coeffsB[1], initial_coeffs_b_3800,
808 sizeof(initial_coeffs_b_3800));
811 p->filterA[0] = p->filterA[1] = 0;
812 p->filterB[0] = p->filterB[1] = 0;
813 p->lastA[0] = p->lastA[1] = 0;
818 /** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
819 static inline int APESIGN(int32_t x) {
820 return (x < 0) - (x > 0);
823 static av_always_inline int filter_fast_3320(APEPredictor *p,
824 const int decoded, const int filter,
829 p->buf[delayA] = p->lastA[filter];
830 if (p->sample_pos < 3) {
831 p->lastA[filter] = decoded;
832 p->filterA[filter] = decoded;
836 predictionA = p->buf[delayA] * 2U - p->buf[delayA - 1];
837 p->lastA[filter] = decoded + ((int32_t)(predictionA * p->coeffsA[filter][0]) >> 9);
839 if ((decoded ^ predictionA) > 0)
840 p->coeffsA[filter][0]++;
842 p->coeffsA[filter][0]--;
844 p->filterA[filter] += (unsigned)p->lastA[filter];
846 return p->filterA[filter];
849 static av_always_inline int filter_3800(APEPredictor *p,
850 const unsigned decoded, const int filter,
851 const int delayA, const int delayB,
852 const int start, const int shift)
854 int32_t predictionA, predictionB, sign;
855 int32_t d0, d1, d2, d3, d4;
857 p->buf[delayA] = p->lastA[filter];
858 p->buf[delayB] = p->filterB[filter];
859 if (p->sample_pos < start) {
860 predictionA = decoded + p->filterA[filter];
861 p->lastA[filter] = decoded;
862 p->filterB[filter] = decoded;
863 p->filterA[filter] = predictionA;
867 d1 = (p->buf[delayA] - p->buf[delayA - 1]) * 2U;
868 d0 = p->buf[delayA] + ((p->buf[delayA - 2] - p->buf[delayA - 1]) * 8U);
869 d3 = p->buf[delayB] * 2U - p->buf[delayB - 1];
872 predictionA = d0 * p->coeffsA[filter][0] +
873 d1 * p->coeffsA[filter][1] +
874 d2 * p->coeffsA[filter][2];
876 sign = APESIGN(decoded);
877 p->coeffsA[filter][0] += (((d0 >> 30) & 2) - 1) * sign;
878 p->coeffsA[filter][1] += (((d1 >> 28) & 8) - 4) * sign;
879 p->coeffsA[filter][2] += (((d2 >> 28) & 8) - 4) * sign;
881 predictionB = d3 * p->coeffsB[filter][0] -
882 d4 * p->coeffsB[filter][1];
883 p->lastA[filter] = decoded + (predictionA >> 11);
884 sign = APESIGN(p->lastA[filter]);
885 p->coeffsB[filter][0] += (((d3 >> 29) & 4) - 2) * sign;
886 p->coeffsB[filter][1] -= (((d4 >> 30) & 2) - 1) * sign;
888 p->filterB[filter] = p->lastA[filter] + (predictionB >> shift);
889 p->filterA[filter] = p->filterB[filter] + (unsigned)((int)(p->filterA[filter] * 31U) >> 5);
891 return p->filterA[filter];
894 static void long_filter_high_3800(int32_t *buffer, int order, int shift, int length)
897 int32_t dotprod, sign;
898 int32_t coeffs[256], delay[256];
903 memset(coeffs, 0, order * sizeof(*coeffs));
904 for (i = 0; i < order; i++)
905 delay[i] = buffer[i];
906 for (i = order; i < length; i++) {
908 sign = APESIGN(buffer[i]);
909 for (j = 0; j < order; j++) {
910 dotprod += delay[j] * (unsigned)coeffs[j];
911 coeffs[j] += ((delay[j] >> 31) | 1) * sign;
913 buffer[i] -= dotprod >> shift;
914 for (j = 0; j < order - 1; j++)
915 delay[j] = delay[j + 1];
916 delay[order - 1] = buffer[i];
920 static void long_filter_ehigh_3830(int32_t *buffer, int length)
923 int32_t dotprod, sign;
924 int32_t delay[8] = { 0 };
925 uint32_t coeffs[8] = { 0 };
927 for (i = 0; i < length; i++) {
929 sign = APESIGN(buffer[i]);
930 for (j = 7; j >= 0; j--) {
931 dotprod += delay[j] * coeffs[j];
932 coeffs[j] += ((delay[j] >> 31) | 1) * sign;
934 for (j = 7; j > 0; j--)
935 delay[j] = delay[j - 1];
936 delay[0] = buffer[i];
937 buffer[i] -= dotprod >> 9;
941 static void predictor_decode_stereo_3800(APEContext *ctx, int count)
943 APEPredictor *p = &ctx->predictor;
944 int32_t *decoded0 = ctx->decoded[0];
945 int32_t *decoded1 = ctx->decoded[1];
946 int start = 4, shift = 10;
948 if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
950 long_filter_high_3800(decoded0, 16, 9, count);
951 long_filter_high_3800(decoded1, 16, 9, count);
952 } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
953 int order = 128, shift2 = 11;
955 if (ctx->fileversion >= 3830) {
959 long_filter_ehigh_3830(decoded0 + order, count - order);
960 long_filter_ehigh_3830(decoded1 + order, count - order);
963 long_filter_high_3800(decoded0, order, shift2, count);
964 long_filter_high_3800(decoded1, order, shift2, count);
968 int X = *decoded0, Y = *decoded1;
969 if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
970 *decoded0 = filter_fast_3320(p, Y, 0, YDELAYA);
972 *decoded1 = filter_fast_3320(p, X, 1, XDELAYA);
975 *decoded0 = filter_3800(p, Y, 0, YDELAYA, YDELAYB,
978 *decoded1 = filter_3800(p, X, 1, XDELAYA, XDELAYB,
987 /* Have we filled the history buffer? */
988 if (p->buf == p->historybuffer + HISTORY_SIZE) {
989 memmove(p->historybuffer, p->buf,
990 PREDICTOR_SIZE * sizeof(*p->historybuffer));
991 p->buf = p->historybuffer;
996 static void predictor_decode_mono_3800(APEContext *ctx, int count)
998 APEPredictor *p = &ctx->predictor;
999 int32_t *decoded0 = ctx->decoded[0];
1000 int start = 4, shift = 10;
1002 if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
1004 long_filter_high_3800(decoded0, 16, 9, count);
1005 } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
1006 int order = 128, shift2 = 11;
1008 if (ctx->fileversion >= 3830) {
1012 long_filter_ehigh_3830(decoded0 + order, count - order);
1015 long_filter_high_3800(decoded0, order, shift2, count);
1019 if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
1020 *decoded0 = filter_fast_3320(p, *decoded0, 0, YDELAYA);
1023 *decoded0 = filter_3800(p, *decoded0, 0, YDELAYA, YDELAYB,
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 av_always_inline int predictor_update_3930(APEPredictor *p,
1042 const int decoded, const int filter,
1045 int32_t predictionA, sign;
1046 int32_t d0, d1, d2, d3;
1048 p->buf[delayA] = p->lastA[filter];
1049 d0 = p->buf[delayA ];
1050 d1 = p->buf[delayA ] - p->buf[delayA - 1];
1051 d2 = p->buf[delayA - 1] - p->buf[delayA - 2];
1052 d3 = p->buf[delayA - 2] - p->buf[delayA - 3];
1054 predictionA = d0 * p->coeffsA[filter][0] +
1055 d1 * p->coeffsA[filter][1] +
1056 d2 * p->coeffsA[filter][2] +
1057 d3 * p->coeffsA[filter][3];
1059 p->lastA[filter] = decoded + (predictionA >> 9);
1060 p->filterA[filter] = p->lastA[filter] + ((int)(p->filterA[filter] * 31U) >> 5);
1062 sign = APESIGN(decoded);
1063 p->coeffsA[filter][0] += ((d0 < 0) * 2 - 1) * sign;
1064 p->coeffsA[filter][1] += ((d1 < 0) * 2 - 1) * sign;
1065 p->coeffsA[filter][2] += ((d2 < 0) * 2 - 1) * sign;
1066 p->coeffsA[filter][3] += ((d3 < 0) * 2 - 1) * sign;
1068 return p->filterA[filter];
1071 static void predictor_decode_stereo_3930(APEContext *ctx, int count)
1073 APEPredictor *p = &ctx->predictor;
1074 int32_t *decoded0 = ctx->decoded[0];
1075 int32_t *decoded1 = ctx->decoded[1];
1077 ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1081 int Y = *decoded1, X = *decoded0;
1082 *decoded0 = predictor_update_3930(p, Y, 0, YDELAYA);
1084 *decoded1 = predictor_update_3930(p, X, 1, XDELAYA);
1090 /* Have we filled the history buffer? */
1091 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1092 memmove(p->historybuffer, p->buf,
1093 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1094 p->buf = p->historybuffer;
1099 static void predictor_decode_mono_3930(APEContext *ctx, int count)
1101 APEPredictor *p = &ctx->predictor;
1102 int32_t *decoded0 = ctx->decoded[0];
1104 ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1107 *decoded0 = predictor_update_3930(p, *decoded0, 0, YDELAYA);
1112 /* Have we filled the history buffer? */
1113 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1114 memmove(p->historybuffer, p->buf,
1115 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1116 p->buf = p->historybuffer;
1121 static av_always_inline int predictor_update_filter(APEPredictor *p,
1122 const int decoded, const int filter,
1123 const int delayA, const int delayB,
1124 const int adaptA, const int adaptB)
1126 int32_t predictionA, predictionB, sign;
1128 p->buf[delayA] = p->lastA[filter];
1129 p->buf[adaptA] = APESIGN(p->buf[delayA]);
1130 p->buf[delayA - 1] = p->buf[delayA] - (unsigned)p->buf[delayA - 1];
1131 p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
1133 predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
1134 p->buf[delayA - 1] * p->coeffsA[filter][1] +
1135 p->buf[delayA - 2] * p->coeffsA[filter][2] +
1136 p->buf[delayA - 3] * p->coeffsA[filter][3];
1138 /* Apply a scaled first-order filter compression */
1139 p->buf[delayB] = p->filterA[filter ^ 1] - ((int)(p->filterB[filter] * 31U) >> 5);
1140 p->buf[adaptB] = APESIGN(p->buf[delayB]);
1141 p->buf[delayB - 1] = p->buf[delayB] - (unsigned)p->buf[delayB - 1];
1142 p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
1143 p->filterB[filter] = p->filterA[filter ^ 1];
1145 predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
1146 p->buf[delayB - 1] * p->coeffsB[filter][1] +
1147 p->buf[delayB - 2] * p->coeffsB[filter][2] +
1148 p->buf[delayB - 3] * p->coeffsB[filter][3] +
1149 p->buf[delayB - 4] * p->coeffsB[filter][4];
1151 p->lastA[filter] = decoded + ((int)((unsigned)predictionA + (predictionB >> 1)) >> 10);
1152 p->filterA[filter] = p->lastA[filter] + ((int)(p->filterA[filter] * 31U) >> 5);
1154 sign = APESIGN(decoded);
1155 p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
1156 p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
1157 p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
1158 p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
1159 p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
1160 p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
1161 p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
1162 p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
1163 p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
1165 return p->filterA[filter];
1168 static void predictor_decode_stereo_3950(APEContext *ctx, int count)
1170 APEPredictor *p = &ctx->predictor;
1171 int32_t *decoded0 = ctx->decoded[0];
1172 int32_t *decoded1 = ctx->decoded[1];
1174 ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1178 *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
1179 YADAPTCOEFFSA, YADAPTCOEFFSB);
1181 *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
1182 XADAPTCOEFFSA, XADAPTCOEFFSB);
1188 /* Have we filled the history buffer? */
1189 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1190 memmove(p->historybuffer, p->buf,
1191 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1192 p->buf = p->historybuffer;
1197 static void predictor_decode_mono_3950(APEContext *ctx, int count)
1199 APEPredictor *p = &ctx->predictor;
1200 int32_t *decoded0 = ctx->decoded[0];
1201 int32_t predictionA, currentA, A, sign;
1203 ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1205 currentA = p->lastA[0];
1210 p->buf[YDELAYA] = currentA;
1211 p->buf[YDELAYA - 1] = p->buf[YDELAYA] - (unsigned)p->buf[YDELAYA - 1];
1213 predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
1214 p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
1215 p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
1216 p->buf[YDELAYA - 3] * p->coeffsA[0][3];
1218 currentA = A + (unsigned)(predictionA >> 10);
1220 p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
1221 p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
1224 p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
1225 p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
1226 p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
1227 p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
1231 /* Have we filled the history buffer? */
1232 if (p->buf == p->historybuffer + HISTORY_SIZE) {
1233 memmove(p->historybuffer, p->buf,
1234 PREDICTOR_SIZE * sizeof(*p->historybuffer));
1235 p->buf = p->historybuffer;
1238 p->filterA[0] = currentA + (unsigned)((int)(p->filterA[0] * 31U) >> 5);
1239 *(decoded0++) = p->filterA[0];
1242 p->lastA[0] = currentA;
1245 static void do_init_filter(APEFilter *f, int16_t *buf, int order)
1248 f->historybuffer = buf + order;
1249 f->delay = f->historybuffer + order * 2;
1250 f->adaptcoeffs = f->historybuffer + order;
1252 memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
1253 memset(f->coeffs, 0, order * sizeof(*f->coeffs));
1257 static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
1259 do_init_filter(&f[0], buf, order);
1260 do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
1263 static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
1264 int32_t *data, int count, int order, int fracbits)
1270 /* round fixedpoint scalar product */
1271 res = ctx->adsp.scalarproduct_and_madd_int16(f->coeffs,
1273 f->adaptcoeffs - order,
1274 order, APESIGN(*data));
1275 res = (int)(res + (1U << (fracbits - 1))) >> fracbits;
1276 res += (unsigned)*data;
1279 /* Update the output history */
1280 *f->delay++ = av_clip_int16(res);
1282 if (version < 3980) {
1283 /* Version ??? to < 3.98 files (untested) */
1284 f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
1285 f->adaptcoeffs[-4] >>= 1;
1286 f->adaptcoeffs[-8] >>= 1;
1288 /* Version 3.98 and later files */
1290 /* Update the adaption coefficients */
1291 absres = res < 0 ? -(unsigned)res : res;
1293 *f->adaptcoeffs = APESIGN(res) *
1294 (8 << ((absres > f->avg * 3) + (absres > f->avg * 4 / 3)));
1295 /* equivalent to the following code
1296 if (absres <= f->avg * 4 / 3)
1297 *f->adaptcoeffs = APESIGN(res) * 8;
1298 else if (absres <= f->avg * 3)
1299 *f->adaptcoeffs = APESIGN(res) * 16;
1301 *f->adaptcoeffs = APESIGN(res) * 32;
1304 *f->adaptcoeffs = 0;
1306 f->avg += (int)(absres - (unsigned)f->avg) / 16;
1308 f->adaptcoeffs[-1] >>= 1;
1309 f->adaptcoeffs[-2] >>= 1;
1310 f->adaptcoeffs[-8] >>= 1;
1315 /* Have we filled the history buffer? */
1316 if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
1317 memmove(f->historybuffer, f->delay - (order * 2),
1318 (order * 2) * sizeof(*f->historybuffer));
1319 f->delay = f->historybuffer + order * 2;
1320 f->adaptcoeffs = f->historybuffer + order;
1325 static void apply_filter(APEContext *ctx, APEFilter *f,
1326 int32_t *data0, int32_t *data1,
1327 int count, int order, int fracbits)
1329 do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
1331 do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
1334 static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
1335 int32_t *decoded1, int count)
1339 for (i = 0; i < APE_FILTER_LEVELS; i++) {
1340 if (!ape_filter_orders[ctx->fset][i])
1342 apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
1343 ape_filter_orders[ctx->fset][i],
1344 ape_filter_fracbits[ctx->fset][i]);
1348 static int init_frame_decoder(APEContext *ctx)
1351 if ((ret = init_entropy_decoder(ctx)) < 0)
1353 init_predictor_decoder(ctx);
1355 for (i = 0; i < APE_FILTER_LEVELS; i++) {
1356 if (!ape_filter_orders[ctx->fset][i])
1358 init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
1359 ape_filter_orders[ctx->fset][i]);
1364 static void ape_unpack_mono(APEContext *ctx, int count)
1366 if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
1367 /* We are pure silence, so we're done. */
1368 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
1372 ctx->entropy_decode_mono(ctx, count);
1376 /* Now apply the predictor decoding */
1377 ctx->predictor_decode_mono(ctx, count);
1379 /* Pseudo-stereo - just copy left channel to right channel */
1380 if (ctx->channels == 2) {
1381 memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
1385 static void ape_unpack_stereo(APEContext *ctx, int count)
1387 unsigned left, right;
1388 int32_t *decoded0 = ctx->decoded[0];
1389 int32_t *decoded1 = ctx->decoded[1];
1391 if ((ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) == APE_FRAMECODE_STEREO_SILENCE) {
1392 /* We are pure silence, so we're done. */
1393 av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
1397 ctx->entropy_decode_stereo(ctx, count);
1401 /* Now apply the predictor decoding */
1402 ctx->predictor_decode_stereo(ctx, count);
1404 /* Decorrelate and scale to output depth */
1406 left = *decoded1 - (unsigned)(*decoded0 / 2);
1407 right = left + *decoded0;
1409 *(decoded0++) = left;
1410 *(decoded1++) = right;
1414 static int ape_decode_frame(AVCodecContext *avctx, void *data,
1415 int *got_frame_ptr, AVPacket *avpkt)
1417 AVFrame *frame = data;
1418 const uint8_t *buf = avpkt->data;
1419 APEContext *s = avctx->priv_data;
1425 uint64_t decoded_buffer_size;
1427 /* this should never be negative, but bad things will happen if it is, so
1428 check it just to make sure. */
1429 av_assert0(s->samples >= 0);
1432 uint32_t nblocks, offset;
1439 if (avpkt->size < 8) {
1440 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1441 return AVERROR_INVALIDDATA;
1443 buf_size = avpkt->size & ~3;
1444 if (buf_size != avpkt->size) {
1445 av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
1446 "extra bytes at the end will be skipped.\n");
1448 if (s->fileversion < 3950) // previous versions overread two bytes
1450 av_fast_padded_malloc(&s->data, &s->data_size, buf_size);
1452 return AVERROR(ENOMEM);
1453 s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,
1455 memset(s->data + (buf_size & ~3), 0, buf_size & 3);
1457 s->data_end = s->data + buf_size;
1459 nblocks = bytestream_get_be32(&s->ptr);
1460 offset = bytestream_get_be32(&s->ptr);
1461 if (s->fileversion >= 3900) {
1463 av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
1466 return AVERROR_INVALIDDATA;
1468 if (s->data_end - s->ptr < offset) {
1469 av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1470 return AVERROR_INVALIDDATA;
1474 if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0)
1476 if (s->fileversion > 3800)
1477 skip_bits_long(&s->gb, offset * 8);
1479 skip_bits_long(&s->gb, offset);
1482 if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) {
1483 av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n",
1485 return AVERROR_INVALIDDATA;
1488 /* Initialize the frame decoder */
1489 if (init_frame_decoder(s) < 0) {
1490 av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
1491 return AVERROR_INVALIDDATA;
1493 s->samples = nblocks;
1501 blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
1502 // for old files coefficients were not interleaved,
1503 // so we need to decode all of them at once
1504 if (s->fileversion < 3930)
1505 blockstodecode = s->samples;
1507 /* reallocate decoded sample buffer if needed */
1508 decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer);
1509 av_assert0(decoded_buffer_size <= INT_MAX);
1511 /* get output buffer */
1512 frame->nb_samples = blockstodecode;
1513 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
1518 av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size);
1519 if (!s->decoded_buffer)
1520 return AVERROR(ENOMEM);
1521 memset(s->decoded_buffer, 0, decoded_buffer_size);
1522 s->decoded[0] = s->decoded_buffer;
1523 s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
1527 if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
1528 ape_unpack_mono(s, blockstodecode);
1530 ape_unpack_stereo(s, blockstodecode);
1535 av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
1536 return AVERROR_INVALIDDATA;
1541 for (ch = 0; ch < s->channels; ch++) {
1542 sample8 = (uint8_t *)frame->data[ch];
1543 for (i = 0; i < blockstodecode; i++)
1544 *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
1548 for (ch = 0; ch < s->channels; ch++) {
1549 sample16 = (int16_t *)frame->data[ch];
1550 for (i = 0; i < blockstodecode; i++)
1551 *sample16++ = s->decoded[ch][i];
1555 for (ch = 0; ch < s->channels; ch++) {
1556 sample24 = (int32_t *)frame->data[ch];
1557 for (i = 0; i < blockstodecode; i++)
1558 *sample24++ = s->decoded[ch][i] << 8;
1563 s->samples -= blockstodecode;
1567 return !s->samples ? avpkt->size : 0;
1570 static void ape_flush(AVCodecContext *avctx)
1572 APEContext *s = avctx->priv_data;
1576 #define OFFSET(x) offsetof(APEContext, x)
1577 #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
1578 static const AVOption options[] = {
1579 { "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" },
1580 { "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" },
1584 static const AVClass ape_decoder_class = {
1585 .class_name = "APE decoder",
1586 .item_name = av_default_item_name,
1588 .version = LIBAVUTIL_VERSION_INT,
1591 AVCodec ff_ape_decoder = {
1593 .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
1594 .type = AVMEDIA_TYPE_AUDIO,
1595 .id = AV_CODEC_ID_APE,
1596 .priv_data_size = sizeof(APEContext),
1597 .init = ape_decode_init,
1598 .close = ape_decode_close,
1599 .decode = ape_decode_frame,
1600 .capabilities = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DELAY |
1603 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
1606 AV_SAMPLE_FMT_NONE },
1607 .priv_class = &ape_decoder_class,