Coverage Report

Created: 2026-07-25 07:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libavcodec/apedec.c
Line
Count
Source
1
/*
2
 * Monkey's Audio lossless audio decoder
3
 * Copyright (c) 2007 Benjamin Zores <ben@geexbox.org>
4
 *  based upon libdemac from Dave Chapman.
5
 *
6
 * This file is part of FFmpeg.
7
 *
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.
12
 *
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.
17
 *
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
21
 */
22
23
#include <inttypes.h>
24
25
#include "libavutil/attributes.h"
26
#include "libavutil/avassert.h"
27
#include "libavutil/channel_layout.h"
28
#include "libavutil/crc.h"
29
#include "libavutil/mem.h"
30
#include "libavutil/opt.h"
31
#include "lossless_audiodsp.h"
32
#include "avcodec.h"
33
#include "bswapdsp.h"
34
#include "bytestream.h"
35
#include "codec_internal.h"
36
#include "decode.h"
37
#include "get_bits.h"
38
#include "unary.h"
39
40
/**
41
 * @file
42
 * Monkey's Audio lossless audio decoder
43
 */
44
45
#define MAX_CHANNELS        2
46
#define MAX_BYTESPERSAMPLE  3
47
48
#define APE_FRAMECODE_MONO_SILENCE    1
49
58.1k
#define APE_FRAMECODE_STEREO_SILENCE  3
50
26.6k
#define APE_FRAMECODE_PSEUDO_STEREO   4
51
52
3.60M
#define HISTORY_SIZE 512
53
8.27M
#define PREDICTOR_ORDER 8
54
/** Total size of all predictor histories */
55
70.8k
#define PREDICTOR_SIZE 50
56
57
3.99M
#define YDELAYA (18 + PREDICTOR_ORDER*4)
58
1.67M
#define YDELAYB (18 + PREDICTOR_ORDER*3)
59
1.51M
#define XDELAYA (18 + PREDICTOR_ORDER*2)
60
1.08M
#define XDELAYB (18 + PREDICTOR_ORDER)
61
62
1.11M
#define YADAPTCOEFFSA 18
63
219k
#define XADAPTCOEFFSA 14
64
219k
#define YADAPTCOEFFSB 10
65
219k
#define XADAPTCOEFFSB 5
66
67
/**
68
 * Possible compression levels
69
 * @{
70
 */
71
enum APECompressionLevel {
72
    COMPRESSION_LEVEL_FAST       = 1000,
73
    COMPRESSION_LEVEL_NORMAL     = 2000,
74
    COMPRESSION_LEVEL_HIGH       = 3000,
75
    COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
76
    COMPRESSION_LEVEL_INSANE     = 5000
77
};
78
/** @} */
79
80
86.4k
#define APE_FILTER_LEVELS 3
81
82
/** Filter orders depending on compression level */
83
static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
84
    {  0,   0,    0 },
85
    { 16,   0,    0 },
86
    { 64,   0,    0 },
87
    { 32, 256,    0 },
88
    { 16, 256, 1280 }
89
};
90
91
/** Filter fraction bits depending on compression level */
92
static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
93
    {  0,  0,  0 },
94
    { 11,  0,  0 },
95
    { 11,  0,  0 },
96
    { 10, 13,  0 },
97
    { 11, 13, 15 }
98
};
99
100
101
/** Filters applied to the decoded data */
102
typedef struct APEFilter {
103
    int16_t *coeffs;        ///< actual coefficients used in filtering
104
    int16_t *adaptcoeffs;   ///< adaptive filter coefficients used for correcting of actual filter coefficients
105
    int16_t *historybuffer; ///< filter memory
106
    int16_t *delay;         ///< filtered values
107
108
    uint32_t avg;
109
} APEFilter;
110
111
typedef struct APERice {
112
    uint32_t k;
113
    uint32_t ksum;
114
} APERice;
115
116
typedef struct APERangecoder {
117
    uint32_t low;           ///< low end of interval
118
    uint32_t range;         ///< length of interval
119
    uint32_t help;          ///< bytes_to_follow resp. intermediate value
120
    unsigned int buffer;    ///< buffer for input/output
121
} APERangecoder;
122
123
/** Filter histories */
124
typedef struct APEPredictor {
125
    int32_t *buf;
126
127
    int32_t lastA[2];
128
129
    int32_t filterA[2];
130
    int32_t filterB[2];
131
132
    uint32_t coeffsA[2][4];  ///< adaption coefficients
133
    uint32_t coeffsB[2][5];  ///< adaption coefficients
134
    int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
135
136
    unsigned int sample_pos;
137
} APEPredictor;
138
139
typedef struct APEPredictor64 {
140
    int64_t *buf;
141
142
    int64_t lastA[2];
143
144
    int64_t filterA[2];
145
    int64_t filterB[2];
146
147
    uint64_t coeffsA[2][4];  ///< adaption coefficients
148
    uint64_t coeffsB[2][5];  ///< adaption coefficients
149
    int64_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
150
} APEPredictor64;
151
152
/** Decoder context */
153
typedef struct APEContext {
154
    AVClass *class;                          ///< class for AVOptions
155
    AVCodecContext *avctx;
156
    BswapDSPContext bdsp;
157
    LLAudDSPContext adsp;
158
    int channels;
159
    int samples;                             ///< samples left to decode in current frame
160
    int bps;
161
162
    int fileversion;                         ///< codec version, very important in decoding process
163
    int compression_level;                   ///< compression levels
164
    int fset;                                ///< which filter set to use (calculated from compression level)
165
    int flags;                               ///< global decoder flags
166
167
    uint32_t CRC;                            ///< signalled frame CRC
168
    uint32_t CRC_state;                      ///< accumulated CRC
169
    int frameflags;                          ///< frame flags
170
    APEPredictor predictor;                  ///< predictor used for final reconstruction
171
    APEPredictor64 predictor64;              ///< 64bit predictor used for final reconstruction
172
173
    int32_t *decoded_buffer;
174
    int decoded_size;
175
    int32_t *decoded[MAX_CHANNELS];          ///< decoded data for each channel
176
    int32_t *interim_buffer;
177
    int interim_size;
178
    int32_t *interim[MAX_CHANNELS];          ///< decoded data for each channel
179
    int blocks_per_loop;                     ///< maximum number of samples to decode for each call
180
181
    int16_t* filterbuf[APE_FILTER_LEVELS];   ///< filter memory
182
183
    APERangecoder rc;                        ///< rangecoder used to decode actual values
184
    APERice riceX;                           ///< rice code parameters for the second channel
185
    APERice riceY;                           ///< rice code parameters for the first channel
186
    APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
187
    GetBitContext gb;
188
189
    uint8_t *data;                           ///< current frame data
190
    uint8_t *data_end;                       ///< frame data end
191
    int data_size;                           ///< frame data allocated size
192
    const uint8_t *ptr;                      ///< current position in frame data
193
194
    int error;
195
    int interim_mode;
196
197
    void (*entropy_decode_mono)(struct APEContext *ctx, int blockstodecode);
198
    void (*entropy_decode_stereo)(struct APEContext *ctx, int blockstodecode);
199
    void (*predictor_decode_mono)(struct APEContext *ctx, int count);
200
    void (*predictor_decode_stereo)(struct APEContext *ctx, int count);
201
} APEContext;
202
203
static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
204
                              int32_t *decoded1, int count);
205
206
static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode);
207
static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode);
208
static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode);
209
static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode);
210
static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode);
211
static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode);
212
static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode);
213
static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode);
214
static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode);
215
216
static void predictor_decode_mono_3800(APEContext *ctx, int count);
217
static void predictor_decode_stereo_3800(APEContext *ctx, int count);
218
static void predictor_decode_mono_3930(APEContext *ctx, int count);
219
static void predictor_decode_stereo_3930(APEContext *ctx, int count);
220
static void predictor_decode_mono_3950(APEContext *ctx, int count);
221
static void predictor_decode_stereo_3950(APEContext *ctx, int count);
222
223
static av_cold int ape_decode_close(AVCodecContext *avctx)
224
1.34k
{
225
1.34k
    APEContext *s = avctx->priv_data;
226
1.34k
    int i;
227
228
5.38k
    for (i = 0; i < APE_FILTER_LEVELS; i++)
229
4.03k
        av_freep(&s->filterbuf[i]);
230
231
1.34k
    av_freep(&s->decoded_buffer);
232
1.34k
    av_freep(&s->interim_buffer);
233
1.34k
    av_freep(&s->data);
234
1.34k
    s->decoded_size = s->data_size = 0;
235
236
1.34k
    return 0;
237
1.34k
}
238
239
static av_cold int ape_decode_init(AVCodecContext *avctx)
240
1.34k
{
241
1.34k
    APEContext *s = avctx->priv_data;
242
1.34k
    int channels = avctx->ch_layout.nb_channels;
243
1.34k
    int i;
244
245
1.34k
    if (avctx->extradata_size != 6) {
246
101
        av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
247
101
        return AVERROR(EINVAL);
248
101
    }
249
1.24k
    if (channels > 2) {
250
1
        av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
251
1
        return AVERROR(EINVAL);
252
1
    }
253
1.24k
    avctx->bits_per_raw_sample =
254
1.24k
    s->bps = avctx->bits_per_coded_sample;
255
1.24k
    switch (s->bps) {
256
406
    case 8:
257
406
        avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
258
406
        s->interim_mode = 0;
259
406
        break;
260
228
    case 16:
261
228
        avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
262
228
        s->interim_mode = 0;
263
228
        break;
264
608
    case 24:
265
608
        avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
266
608
        s->interim_mode = -1;
267
608
        break;
268
1
    default:
269
1
        avpriv_request_sample(avctx,
270
1
                              "%d bits per coded sample", s->bps);
271
1
        return AVERROR_PATCHWELCOME;
272
1.24k
    }
273
1.24k
    s->avctx             = avctx;
274
1.24k
    s->channels          = channels;
275
1.24k
    s->fileversion       = AV_RL16(avctx->extradata);
276
1.24k
    s->compression_level = AV_RL16(avctx->extradata + 2);
277
1.24k
    s->flags             = AV_RL16(avctx->extradata + 4);
278
279
1.24k
    av_log(avctx, AV_LOG_VERBOSE, "Compression Level: %d - Flags: %d\n",
280
1.24k
           s->compression_level, s->flags);
281
1.24k
    if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE ||
282
1.23k
        !s->compression_level ||
283
1.23k
        (s->fileversion < 3930 && s->compression_level == COMPRESSION_LEVEL_INSANE)) {
284
5
        av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
285
5
               s->compression_level);
286
5
        return AVERROR_INVALIDDATA;
287
5
    }
288
1.23k
    s->fset = s->compression_level / 1000 - 1;
289
2.80k
    for (i = 0; i < APE_FILTER_LEVELS; i++) {
290
2.66k
        if (!ape_filter_orders[s->fset][i])
291
1.09k
            break;
292
1.57k
        if (!(s->filterbuf[i] = av_malloc((ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4)))
293
0
            return AVERROR(ENOMEM);
294
1.57k
    }
295
296
1.23k
    if (s->fileversion < 3860) {
297
479
        s->entropy_decode_mono   = entropy_decode_mono_0000;
298
479
        s->entropy_decode_stereo = entropy_decode_stereo_0000;
299
758
    } else if (s->fileversion < 3900) {
300
231
        s->entropy_decode_mono   = entropy_decode_mono_3860;
301
231
        s->entropy_decode_stereo = entropy_decode_stereo_3860;
302
527
    } else if (s->fileversion < 3930) {
303
56
        s->entropy_decode_mono   = entropy_decode_mono_3900;
304
56
        s->entropy_decode_stereo = entropy_decode_stereo_3900;
305
471
    } else if (s->fileversion < 3990) {
306
188
        s->entropy_decode_mono   = entropy_decode_mono_3900;
307
188
        s->entropy_decode_stereo = entropy_decode_stereo_3930;
308
283
    } else {
309
283
        s->entropy_decode_mono   = entropy_decode_mono_3990;
310
283
        s->entropy_decode_stereo = entropy_decode_stereo_3990;
311
283
    }
312
313
1.23k
    if (s->fileversion < 3930) {
314
766
        s->predictor_decode_mono   = predictor_decode_mono_3800;
315
766
        s->predictor_decode_stereo = predictor_decode_stereo_3800;
316
766
    } else if (s->fileversion < 3950) {
317
144
        s->predictor_decode_mono   = predictor_decode_mono_3930;
318
144
        s->predictor_decode_stereo = predictor_decode_stereo_3930;
319
327
    } else {
320
327
        s->predictor_decode_mono   = predictor_decode_mono_3950;
321
327
        s->predictor_decode_stereo = predictor_decode_stereo_3950;
322
327
    }
323
324
1.23k
    ff_bswapdsp_init(&s->bdsp);
325
1.23k
    ff_llauddsp_init(&s->adsp);
326
1.23k
    av_channel_layout_uninit(&avctx->ch_layout);
327
1.23k
    avctx->ch_layout = (channels == 2) ? (AVChannelLayout)AV_CHANNEL_LAYOUT_STEREO
328
1.23k
                                       : (AVChannelLayout)AV_CHANNEL_LAYOUT_MONO;
329
330
1.23k
    return 0;
331
1.23k
}
332
333
/**
334
 * @name APE range decoding functions
335
 * @{
336
 */
337
338
20.6M
#define CODE_BITS    32
339
20.6M
#define TOP_VALUE    ((unsigned int)1 << (CODE_BITS-1))
340
#define SHIFT_BITS   (CODE_BITS - 9)
341
15.9k
#define EXTRA_BITS   ((CODE_BITS-2) % 8 + 1)
342
20.6M
#define BOTTOM_VALUE (TOP_VALUE >> 8)
343
344
/** Start the decoder */
345
static inline void range_start_decoding(APEContext *ctx)
346
7.97k
{
347
7.97k
    ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
348
7.97k
    ctx->rc.low    = ctx->rc.buffer >> (8 - EXTRA_BITS);
349
7.97k
    ctx->rc.range  = (uint32_t) 1 << EXTRA_BITS;
350
7.97k
}
351
352
/** Perform normalization */
353
static inline void range_dec_normalize(APEContext *ctx)
354
15.2M
{
355
20.6M
    while (ctx->rc.range <= BOTTOM_VALUE) {
356
5.37M
        ctx->rc.buffer <<= 8;
357
5.37M
        if(ctx->ptr < ctx->data_end) {
358
785k
            ctx->rc.buffer += *ctx->ptr;
359
785k
            ctx->ptr++;
360
4.58M
        } else {
361
4.58M
            ctx->error = 1;
362
4.58M
        }
363
5.37M
        ctx->rc.low    = (ctx->rc.low << 8)    | ((ctx->rc.buffer >> 1) & 0xFF);
364
5.37M
        ctx->rc.range  <<= 8;
365
5.37M
    }
366
15.2M
}
367
368
/**
369
 * Calculate cumulative frequency for next symbol. Does NO update!
370
 * @param ctx decoder context
371
 * @param tot_f is the total frequency or (code_value)1<<shift
372
 * @return the cumulative frequency
373
 */
374
static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
375
4.51M
{
376
4.51M
    range_dec_normalize(ctx);
377
4.51M
    ctx->rc.help = ctx->rc.range / tot_f;
378
4.51M
    return ctx->rc.low / ctx->rc.help;
379
4.51M
}
380
381
/**
382
 * Decode value with given size in bits
383
 * @param ctx decoder context
384
 * @param shift number of bits to decode
385
 */
386
static inline int range_decode_culshift(APEContext *ctx, int shift)
387
10.7M
{
388
10.7M
    range_dec_normalize(ctx);
389
10.7M
    ctx->rc.help = ctx->rc.range >> shift;
390
10.7M
    return ctx->rc.low / ctx->rc.help;
391
10.7M
}
392
393
394
/**
395
 * Update decoding state
396
 * @param ctx decoder context
397
 * @param sy_f the interval length (frequency of the symbol)
398
 * @param lt_f the lower end (frequency sum of < symbols)
399
 */
400
static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
401
15.2M
{
402
15.2M
    ctx->rc.low  -= ctx->rc.help * lt_f;
403
15.2M
    ctx->rc.range = ctx->rc.help * sy_f;
404
15.2M
}
405
406
/** Decode n bits (n <= 16) without modelling */
407
static inline int range_decode_bits(APEContext *ctx, int n)
408
3.22M
{
409
3.22M
    int sym = range_decode_culshift(ctx, n);
410
3.22M
    range_decode_update(ctx, 1, sym);
411
3.22M
    return sym;
412
3.22M
}
413
414
415
7.48M
#define MODEL_ELEMENTS 64
416
417
/**
418
 * Fixed probabilities for symbols in Monkey Audio version 3.97
419
 */
420
static const uint16_t counts_3970[22] = {
421
        0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
422
    62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
423
    65450, 65469, 65480, 65487, 65491, 65493,
424
};
425
426
/**
427
 * Probability ranges for symbols in Monkey Audio version 3.97
428
 */
429
static const uint16_t counts_diff_3970[21] = {
430
    14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
431
    1104, 677, 415, 248, 150, 89, 54, 31,
432
    19, 11, 7, 4, 2,
433
};
434
435
/**
436
 * Fixed probabilities for symbols in Monkey Audio version 3.98
437
 */
438
static const uint16_t counts_3980[22] = {
439
        0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
440
    64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
441
    65485, 65488, 65490, 65491, 65492, 65493,
442
};
443
444
/**
445
 * Probability ranges for symbols in Monkey Audio version 3.98
446
 */
447
static const uint16_t counts_diff_3980[21] = {
448
    19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
449
    261, 119, 65, 31, 19, 10, 6, 3,
450
    3, 2, 1, 1, 1,
451
};
452
453
/**
454
 * Decode symbol
455
 * @param ctx decoder context
456
 * @param counts probability range start position
457
 * @param counts_diff probability range widths
458
 */
459
static inline int range_get_symbol(APEContext *ctx,
460
                                   const uint16_t counts[],
461
                                   const uint16_t counts_diff[])
462
7.48M
{
463
7.48M
    int symbol, cf;
464
465
7.48M
    cf = range_decode_culshift(ctx, 16);
466
467
7.48M
    if(cf > 65492){
468
6.37k
        symbol= cf - 65535 + 63;
469
6.37k
        range_decode_update(ctx, 1, cf);
470
6.37k
        if(cf > 65535)
471
1.52k
            ctx->error=1;
472
6.37k
        return symbol;
473
6.37k
    }
474
    /* figure out the symbol inefficiently; a binary search would be much better */
475
12.0M
    for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
476
477
7.48M
    range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
478
479
7.48M
    return symbol;
480
7.48M
}
481
/** @} */ // group rangecoder
482
483
static inline void update_rice(APERice *rice, unsigned int x)
484
7.48M
{
485
7.48M
    int lim = rice->k ? (1 << (rice->k + 4)) : 0;
486
7.48M
    rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
487
488
7.48M
    if (rice->ksum < lim)
489
45.4k
        rice->k--;
490
7.44M
    else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
491
31.4k
        rice->k++;
492
7.48M
}
493
494
static inline int get_rice_ook(GetBitContext *gb, int k)
495
828k
{
496
828k
    unsigned int x;
497
498
828k
    x = get_unary(gb, 1, get_bits_left(gb));
499
500
828k
    if (k)
501
313k
        x = (x << k) | get_bits(gb, k);
502
503
828k
    return x;
504
828k
}
505
506
static inline int ape_decode_value_3860(APEContext *ctx, GetBitContext *gb,
507
                                        APERice *rice)
508
1.72M
{
509
1.72M
    unsigned int x, overflow;
510
511
1.72M
    overflow = get_unary(gb, 1, get_bits_left(gb));
512
513
1.72M
    if (ctx->fileversion > 3880) {
514
2.73M
        while (overflow >= 16) {
515
1.85M
            overflow -= 16;
516
1.85M
            rice->k  += 4;
517
1.85M
        }
518
874k
    }
519
520
1.72M
    if (!rice->k)
521
760k
        x = overflow;
522
964k
    else if(rice->k <= MIN_CACHE_BITS) {
523
579k
        x = (overflow << rice->k) + get_bits(gb, rice->k);
524
579k
    } else {
525
385k
        av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %"PRIu32"\n", rice->k);
526
385k
        ctx->error = 1;
527
385k
        return AVERROR_INVALIDDATA;
528
385k
    }
529
1.34M
    rice->ksum += x - (rice->ksum + 8 >> 4);
530
1.34M
    if (rice->ksum < (rice->k ? 1 << (rice->k + 4) : 0))
531
70.0k
        rice->k--;
532
1.26M
    else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
533
3.73k
        rice->k++;
534
535
    /* Convert to signed */
536
1.34M
    return ((x >> 1) ^ ((x & 1) - 1)) + 1;
537
1.72M
}
538
539
static inline int ape_decode_value_3900(APEContext *ctx, APERice *rice)
540
3.13M
{
541
3.13M
    unsigned int x, overflow;
542
3.13M
    int tmpk;
543
544
3.13M
    overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
545
546
3.13M
    if (overflow == (MODEL_ELEMENTS - 1)) {
547
2.39k
        tmpk = range_decode_bits(ctx, 5);
548
2.39k
        overflow = 0;
549
2.39k
    } else
550
3.13M
        tmpk = (rice->k < 1) ? 0 : rice->k - 1;
551
552
3.13M
    if (tmpk <= 16 || ctx->fileversion < 3910) {
553
3.05M
        if (tmpk > 23) {
554
450
            av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
555
450
            return AVERROR_INVALIDDATA;
556
450
        }
557
3.05M
        x = range_decode_bits(ctx, tmpk);
558
3.05M
    } else if (tmpk <= 31) {
559
86.1k
        x = range_decode_bits(ctx, 16);
560
86.1k
        x |= (range_decode_bits(ctx, tmpk - 16) << 16);
561
86.1k
    } else {
562
0
        av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
563
0
        return AVERROR_INVALIDDATA;
564
0
    }
565
3.13M
    x += overflow << tmpk;
566
567
3.13M
    update_rice(rice, x);
568
569
    /* Convert to signed */
570
3.13M
    return ((x >> 1) ^ ((x & 1) - 1)) + 1;
571
3.13M
}
572
573
static inline int ape_decode_value_3990(APEContext *ctx, APERice *rice)
574
4.34M
{
575
4.34M
    unsigned int x, overflow, pivot;
576
4.34M
    int base;
577
578
4.34M
    pivot = FFMAX(rice->ksum >> 5, 1);
579
580
4.34M
    overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
581
582
4.34M
    if (overflow == (MODEL_ELEMENTS - 1)) {
583
1.16k
        overflow  = (unsigned)range_decode_bits(ctx, 16) << 16;
584
1.16k
        overflow |= range_decode_bits(ctx, 16);
585
1.16k
    }
586
587
4.34M
    if (pivot < 0x10000) {
588
4.18M
        base = range_decode_culfreq(ctx, pivot);
589
4.18M
        range_decode_update(ctx, 1, base);
590
4.18M
    } else {
591
167k
        int base_hi = pivot, base_lo;
592
167k
        int bbits = 0;
593
594
1.23M
        while (base_hi & ~0xFFFF) {
595
1.06M
            base_hi >>= 1;
596
1.06M
            bbits++;
597
1.06M
        }
598
167k
        base_hi = range_decode_culfreq(ctx, base_hi + 1);
599
167k
        range_decode_update(ctx, 1, base_hi);
600
167k
        base_lo = range_decode_culfreq(ctx, 1 << bbits);
601
167k
        range_decode_update(ctx, 1, base_lo);
602
603
167k
        base = (base_hi << bbits) + base_lo;
604
167k
    }
605
606
4.34M
    x = base + overflow * pivot;
607
608
4.34M
    update_rice(rice, x);
609
610
    /* Convert to signed */
611
4.34M
    return ((x >> 1) ^ ((x & 1) - 1)) + 1;
612
4.34M
}
613
614
static int get_k(int ksum)
615
691k
{
616
691k
    return av_log2(ksum) + !!ksum;
617
691k
}
618
619
static void decode_array_0000(APEContext *ctx, GetBitContext *gb,
620
                              int32_t *out, APERice *rice, int blockstodecode)
621
19.9k
{
622
19.9k
    int i;
623
19.9k
    unsigned ksummax, ksummin;
624
625
19.9k
    rice->ksum = 0;
626
97.5k
    for (i = 0; i < FFMIN(blockstodecode, 5); i++) {
627
77.6k
        out[i] = get_rice_ook(&ctx->gb, 10);
628
77.6k
        rice->ksum += out[i];
629
77.6k
    }
630
631
19.9k
    if (blockstodecode <= 5)
632
7.35k
        goto end;
633
634
12.5k
    rice->k = get_k(rice->ksum / 10);
635
12.5k
    if (rice->k >= 24)
636
151
        return;
637
681k
    for (; i < FFMIN(blockstodecode, 64); i++) {
638
669k
        out[i] = get_rice_ook(&ctx->gb, rice->k);
639
669k
        rice->ksum += out[i];
640
669k
        rice->k = get_k(rice->ksum / ((i + 1) * 2));
641
669k
        if (rice->k >= 24)
642
483
            return;
643
669k
    }
644
645
11.9k
    if (blockstodecode <= 64)
646
3.12k
        goto end;
647
648
8.83k
    rice->k = get_k(rice->ksum >> 7);
649
8.83k
    ksummax = 1 << rice->k + 7;
650
8.83k
    ksummin = rice->k ? (1 << rice->k + 6) : 0;
651
89.3k
    for (; i < blockstodecode; i++) {
652
89.0k
        if (get_bits_left(&ctx->gb) < 1) {
653
8.03k
            ctx->error = 1;
654
8.03k
            return;
655
8.03k
        }
656
80.9k
        out[i] = get_rice_ook(&ctx->gb, rice->k);
657
80.9k
        rice->ksum += out[i] - (unsigned)out[i - 64];
658
82.4k
        while (rice->ksum < ksummin) {
659
1.44k
            rice->k--;
660
1.44k
            ksummin = rice->k ? ksummin >> 1 : 0;
661
1.44k
            ksummax >>= 1;
662
1.44k
        }
663
84.6k
        while (rice->ksum >= ksummax) {
664
4.18k
            rice->k++;
665
4.18k
            if (rice->k > 24)
666
512
                return;
667
3.67k
            ksummax <<= 1;
668
3.67k
            ksummin = ksummin ? ksummin << 1 : 128;
669
3.67k
        }
670
80.9k
    }
671
672
10.7k
end:
673
224k
    for (i = 0; i < blockstodecode; i++)
674
213k
        out[i] = ((out[i] >> 1) ^ ((out[i] & 1) - 1)) + 1;
675
10.7k
}
676
677
static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode)
678
1.56k
{
679
1.56k
    decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
680
1.56k
                      blockstodecode);
681
1.56k
}
682
683
static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode)
684
9.18k
{
685
9.18k
    decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
686
9.18k
                      blockstodecode);
687
9.18k
    decode_array_0000(ctx, &ctx->gb, ctx->decoded[1], &ctx->riceX,
688
9.18k
                      blockstodecode);
689
9.18k
}
690
691
static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode)
692
2.20k
{
693
2.20k
    int32_t *decoded0 = ctx->decoded[0];
694
695
818k
    while (blockstodecode--)
696
816k
        *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
697
2.20k
}
698
699
static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode)
700
11.4k
{
701
11.4k
    int32_t *decoded0 = ctx->decoded[0];
702
11.4k
    int32_t *decoded1 = ctx->decoded[1];
703
11.4k
    int blocks = blockstodecode;
704
705
465k
    while (blockstodecode--)
706
454k
        *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
707
465k
    while (blocks--)
708
454k
        *decoded1++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceX);
709
11.4k
}
710
711
static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode)
712
1.36k
{
713
1.36k
    int32_t *decoded0 = ctx->decoded[0];
714
715
803k
    while (blockstodecode--)
716
802k
        *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
717
1.36k
}
718
719
static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode)
720
960
{
721
960
    int32_t *decoded0 = ctx->decoded[0];
722
960
    int32_t *decoded1 = ctx->decoded[1];
723
960
    int blocks = blockstodecode;
724
725
341k
    while (blockstodecode--)
726
340k
        *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
727
960
    range_dec_normalize(ctx);
728
    // because of some implementation peculiarities we need to backpedal here
729
960
    ctx->ptr -= 1;
730
960
    range_start_decoding(ctx);
731
341k
    while (blocks--)
732
340k
        *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
733
960
}
734
735
static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode)
736
1.30k
{
737
1.30k
    int32_t *decoded0 = ctx->decoded[0];
738
1.30k
    int32_t *decoded1 = ctx->decoded[1];
739
740
829k
    while (blockstodecode--) {
741
828k
        *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
742
828k
        *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
743
828k
    }
744
1.30k
}
745
746
static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode)
747
1.01k
{
748
1.01k
    int32_t *decoded0 = ctx->decoded[0];
749
750
760k
    while (blockstodecode--)
751
759k
        *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
752
1.01k
}
753
754
static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode)
755
2.00k
{
756
2.00k
    int32_t *decoded0 = ctx->decoded[0];
757
2.00k
    int32_t *decoded1 = ctx->decoded[1];
758
759
1.79M
    while (blockstodecode--) {
760
1.79M
        *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
761
1.79M
        *decoded1++ = ape_decode_value_3990(ctx, &ctx->riceX);
762
1.79M
    }
763
2.00k
}
764
765
static int init_entropy_decoder(APEContext *ctx)
766
34.1k
{
767
    /* Read the CRC */
768
34.1k
    if (ctx->fileversion >= 3900) {
769
7.75k
        if (ctx->data_end - ctx->ptr < 6)
770
468
            return AVERROR_INVALIDDATA;
771
7.29k
        ctx->CRC = bytestream_get_be32(&ctx->ptr);
772
26.4k
    } else {
773
26.4k
        ctx->CRC = get_bits_long(&ctx->gb, 32);
774
26.4k
    }
775
776
    /* Read the frame flags if they exist */
777
33.7k
    ctx->frameflags = 0;
778
33.7k
    ctx->CRC_state = UINT32_MAX;
779
33.7k
    if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
780
2.33k
        ctx->CRC &= ~0x80000000;
781
782
2.33k
        if (ctx->data_end - ctx->ptr < 6)
783
275
            return AVERROR_INVALIDDATA;
784
2.05k
        ctx->frameflags = bytestream_get_be32(&ctx->ptr);
785
2.05k
    }
786
787
    /* Initialize the rice structs */
788
33.4k
    ctx->riceX.k = 10;
789
33.4k
    ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
790
33.4k
    ctx->riceY.k = 10;
791
33.4k
    ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
792
793
33.4k
    if (ctx->fileversion >= 3900) {
794
        /* The first 8 bits of input are ignored. */
795
7.01k
        ctx->ptr++;
796
797
7.01k
        range_start_decoding(ctx);
798
7.01k
    }
799
800
33.4k
    return 0;
801
33.7k
}
802
803
static const int32_t initial_coeffs_fast_3320[1] = {
804
    375,
805
};
806
807
static const int32_t initial_coeffs_a_3800[3] = {
808
    64, 115, 64,
809
};
810
811
static const int32_t initial_coeffs_b_3800[2] = {
812
    740, 0
813
};
814
815
static const int32_t initial_coeffs_3930[4] = {
816
    360, 317, -109, 98
817
};
818
819
static const int64_t initial_coeffs_3930_64bit[4] = {
820
    360, 317, -109, 98
821
};
822
823
static void init_predictor_decoder(APEContext *ctx)
824
33.4k
{
825
33.4k
    APEPredictor *p = &ctx->predictor;
826
33.4k
    APEPredictor64 *p64 = &ctx->predictor64;
827
828
    /* Zero the history buffers */
829
33.4k
    memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
830
33.4k
    memset(p64->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p64->historybuffer));
831
33.4k
    p->buf = p->historybuffer;
832
33.4k
    p64->buf = p64->historybuffer;
833
834
    /* Initialize and zero the coefficients */
835
33.4k
    if (ctx->fileversion < 3930) {
836
27.4k
        if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
837
14.6k
            memcpy(p->coeffsA[0], initial_coeffs_fast_3320,
838
14.6k
                   sizeof(initial_coeffs_fast_3320));
839
14.6k
            memcpy(p->coeffsA[1], initial_coeffs_fast_3320,
840
14.6k
                   sizeof(initial_coeffs_fast_3320));
841
14.6k
        } else {
842
12.8k
            memcpy(p->coeffsA[0], initial_coeffs_a_3800,
843
12.8k
                   sizeof(initial_coeffs_a_3800));
844
12.8k
            memcpy(p->coeffsA[1], initial_coeffs_a_3800,
845
12.8k
                   sizeof(initial_coeffs_a_3800));
846
12.8k
        }
847
27.4k
    } else {
848
5.96k
        memcpy(p->coeffsA[0], initial_coeffs_3930, sizeof(initial_coeffs_3930));
849
5.96k
        memcpy(p->coeffsA[1], initial_coeffs_3930, sizeof(initial_coeffs_3930));
850
5.96k
        memcpy(p64->coeffsA[0], initial_coeffs_3930_64bit, sizeof(initial_coeffs_3930_64bit));
851
5.96k
        memcpy(p64->coeffsA[1], initial_coeffs_3930_64bit, sizeof(initial_coeffs_3930_64bit));
852
5.96k
    }
853
33.4k
    memset(p->coeffsB, 0, sizeof(p->coeffsB));
854
33.4k
    memset(p64->coeffsB, 0, sizeof(p64->coeffsB));
855
33.4k
    if (ctx->fileversion < 3930) {
856
27.4k
        memcpy(p->coeffsB[0], initial_coeffs_b_3800,
857
27.4k
               sizeof(initial_coeffs_b_3800));
858
27.4k
        memcpy(p->coeffsB[1], initial_coeffs_b_3800,
859
27.4k
               sizeof(initial_coeffs_b_3800));
860
27.4k
    }
861
862
33.4k
    p->filterA[0] = p->filterA[1] = 0;
863
33.4k
    p->filterB[0] = p->filterB[1] = 0;
864
33.4k
    p->lastA[0]   = p->lastA[1]   = 0;
865
866
33.4k
    p64->filterA[0] = p64->filterA[1] = 0;
867
33.4k
    p64->filterB[0] = p64->filterB[1] = 0;
868
33.4k
    p64->lastA[0]   = p64->lastA[1]   = 0;
869
870
33.4k
    p->sample_pos = 0;
871
33.4k
}
872
873
/** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
874
10.1M
static inline int APESIGN(int32_t x) {
875
10.1M
    return (x < 0) - (x > 0);
876
10.1M
}
877
878
static av_always_inline int filter_fast_3320(APEPredictor *p,
879
                                             const int decoded, const int filter,
880
                                             const int delayA)
881
821k
{
882
821k
    int32_t predictionA;
883
884
821k
    p->buf[delayA] = p->lastA[filter];
885
821k
    if (p->sample_pos < 3) {
886
46.9k
        p->lastA[filter]   = decoded;
887
46.9k
        p->filterA[filter] = decoded;
888
46.9k
        return decoded;
889
46.9k
    }
890
891
774k
    predictionA = p->buf[delayA] * 2U - p->buf[delayA - 1];
892
774k
    p->lastA[filter] = decoded + (unsigned)((int32_t)(predictionA  * p->coeffsA[filter][0]) >> 9);
893
894
774k
    if ((decoded ^ predictionA) > 0)
895
82.9k
        p->coeffsA[filter][0]++;
896
691k
    else
897
691k
        p->coeffsA[filter][0]--;
898
899
774k
    p->filterA[filter] += (unsigned)p->lastA[filter];
900
901
774k
    return p->filterA[filter];
902
821k
}
903
904
static av_always_inline int filter_3800(APEPredictor *p,
905
                                        const unsigned decoded, const int filter,
906
                                        const int delayA,  const int delayB,
907
                                        const int start,   const int shift)
908
2.32M
{
909
2.32M
    int32_t predictionA, predictionB, sign;
910
2.32M
    int32_t d0, d1, d2, d3, d4;
911
912
2.32M
    p->buf[delayA] = p->lastA[filter];
913
2.32M
    p->buf[delayB] = p->filterB[filter];
914
2.32M
    if (p->sample_pos < start) {
915
489k
        predictionA = decoded + p->filterA[filter];
916
489k
        p->lastA[filter]   = decoded;
917
489k
        p->filterB[filter] = decoded;
918
489k
        p->filterA[filter] = predictionA;
919
489k
        return predictionA;
920
489k
    }
921
1.83M
    d2 =  p->buf[delayA];
922
1.83M
    d1 = (p->buf[delayA] - (unsigned)p->buf[delayA - 1]) * 2;
923
1.83M
    d0 =  p->buf[delayA] + ((p->buf[delayA - 2] - (unsigned)p->buf[delayA - 1]) * 8);
924
1.83M
    d3 =  p->buf[delayB] * 2U - p->buf[delayB - 1];
925
1.83M
    d4 =  p->buf[delayB];
926
927
1.83M
    predictionA = d0 * p->coeffsA[filter][0] +
928
1.83M
                  d1 * p->coeffsA[filter][1] +
929
1.83M
                  d2 * p->coeffsA[filter][2];
930
931
1.83M
    sign = APESIGN(decoded);
932
1.83M
    p->coeffsA[filter][0] += (((d0 >> 30) & 2) - 1) * sign;
933
1.83M
    p->coeffsA[filter][1] += (((d1 >> 28) & 8) - 4) * sign;
934
1.83M
    p->coeffsA[filter][2] += (((d2 >> 28) & 8) - 4) * sign;
935
936
1.83M
    predictionB = d3 * p->coeffsB[filter][0] -
937
1.83M
                  d4 * p->coeffsB[filter][1];
938
1.83M
    p->lastA[filter] = decoded + (predictionA >> 11);
939
1.83M
    sign = APESIGN(p->lastA[filter]);
940
1.83M
    p->coeffsB[filter][0] += (((d3 >> 29) & 4) - 2) * sign;
941
1.83M
    p->coeffsB[filter][1] -= (((d4 >> 30) & 2) - 1) * sign;
942
943
1.83M
    p->filterB[filter] = p->lastA[filter] + (unsigned)(predictionB >> shift);
944
1.83M
    p->filterA[filter] = p->filterB[filter] + (unsigned)((int)(p->filterA[filter] * 31U) >> 5);
945
946
1.83M
    return p->filterA[filter];
947
2.32M
}
948
949
static void long_filter_high_3800(int32_t *buffer, int order, int shift, int length)
950
15.0k
{
951
15.0k
    int i, j;
952
15.0k
    int32_t dotprod, sign;
953
15.0k
    int32_t coeffs[256], delay[256+256], *delayp = delay;
954
955
15.0k
    if (order >= length)
956
11.5k
        return;
957
958
3.50k
    memset(coeffs, 0, order * sizeof(*coeffs));
959
197k
    for (i = 0; i < order; i++)
960
193k
        delay[i] = buffer[i];
961
1.83M
    for (i = order; i < length; i++) {
962
1.83M
        dotprod = 0;
963
1.83M
        sign = APESIGN(buffer[i]);
964
1.83M
        if (sign == 1) {
965
913k
            for (j = 0; j < order; j++) {
966
907k
                dotprod += delayp[j] * (unsigned)coeffs[j];
967
907k
                coeffs[j] += (delayp[j] >> 31) | 1;
968
907k
            }
969
1.82M
        } else if (sign == -1) {
970
2.89M
            for (j = 0; j < order; j++) {
971
2.86M
                dotprod += delayp[j] * (unsigned)coeffs[j];
972
2.86M
                coeffs[j] -= (delayp[j] >> 31) | 1;
973
2.86M
            }
974
1.79M
        } else {
975
218M
            for (j = 0; j < order; j++) {
976
216M
                dotprod += delayp[j] * (unsigned)coeffs[j];
977
216M
            }
978
1.79M
        }
979
1.83M
        buffer[i] -= (unsigned)(dotprod >> shift);
980
1.83M
        delayp ++;
981
1.83M
        delayp[order - 1] = buffer[i];
982
1.83M
        if (delayp - delay == 256) {
983
6.40k
            memcpy(delay, delayp, sizeof(*delay)*256);
984
6.40k
            delayp = delay;
985
6.40k
        }
986
1.83M
    }
987
3.50k
}
988
989
static void long_filter_ehigh_3830(int32_t *buffer, int length)
990
3.61k
{
991
3.61k
    int i, j;
992
3.61k
    int32_t dotprod, sign;
993
3.61k
    int32_t delay[8] = { 0 };
994
3.61k
    uint32_t coeffs[8] = { 0 };
995
996
416k
    for (i = 0; i < length; i++) {
997
412k
        dotprod = 0;
998
412k
        sign = APESIGN(buffer[i]);
999
3.71M
        for (j = 7; j >= 0; j--) {
1000
3.29M
            dotprod += delay[j] * coeffs[j];
1001
3.29M
            coeffs[j] += ((delay[j] >> 31) | 1) * sign;
1002
3.29M
        }
1003
3.29M
        for (j = 7; j > 0; j--)
1004
2.88M
            delay[j] = delay[j - 1];
1005
412k
        delay[0] = buffer[i];
1006
412k
        buffer[i] -= (unsigned)(dotprod >> 9);
1007
412k
    }
1008
3.61k
}
1009
1010
static void predictor_decode_stereo_3800(APEContext *ctx, int count)
1011
17.0k
{
1012
17.0k
    APEPredictor *p = &ctx->predictor;
1013
17.0k
    int32_t *decoded0 = ctx->decoded[0];
1014
17.0k
    int32_t *decoded1 = ctx->decoded[1];
1015
17.0k
    int start = 4, shift = 10;
1016
1017
17.0k
    if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
1018
1.27k
        start = 16;
1019
1.27k
        long_filter_high_3800(decoded0, 16, 9, count);
1020
1.27k
        long_filter_high_3800(decoded1, 16, 9, count);
1021
15.7k
    } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
1022
5.32k
        int order = 128, shift2 = 11;
1023
1024
5.32k
        if (ctx->fileversion >= 3830) {
1025
1.29k
            order <<= 1;
1026
1.29k
            shift++;
1027
1.29k
            shift2++;
1028
1.29k
            long_filter_ehigh_3830(decoded0 + order, count - order);
1029
1.29k
            long_filter_ehigh_3830(decoded1 + order, count - order);
1030
1.29k
        }
1031
5.32k
        start = order;
1032
5.32k
        long_filter_high_3800(decoded0, order, shift2, count);
1033
5.32k
        long_filter_high_3800(decoded1, order, shift2, count);
1034
5.32k
    }
1035
1036
1.16M
    while (count--) {
1037
1.14M
        int X = *decoded0, Y = *decoded1;
1038
1.14M
        if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
1039
275k
            *decoded0 = filter_fast_3320(p, Y, 0, YDELAYA);
1040
275k
            decoded0++;
1041
275k
            *decoded1 = filter_fast_3320(p, X, 1, XDELAYA);
1042
275k
            decoded1++;
1043
868k
        } else {
1044
868k
            *decoded0 = filter_3800(p, Y, 0, YDELAYA, YDELAYB,
1045
868k
                                    start, shift);
1046
868k
            decoded0++;
1047
868k
            *decoded1 = filter_3800(p, X, 1, XDELAYA, XDELAYB,
1048
868k
                                    start, shift);
1049
868k
            decoded1++;
1050
868k
        }
1051
1052
        /* Combined */
1053
1.14M
        p->buf++;
1054
1.14M
        p->sample_pos++;
1055
1056
        /* Have we filled the history buffer? */
1057
1.14M
        if (p->buf == p->historybuffer + HISTORY_SIZE) {
1058
1.46k
            memmove(p->historybuffer, p->buf,
1059
1.46k
                    PREDICTOR_SIZE * sizeof(*p->historybuffer));
1060
1.46k
            p->buf = p->historybuffer;
1061
1.46k
        }
1062
1.14M
    }
1063
17.0k
}
1064
1065
static void predictor_decode_mono_3800(APEContext *ctx, int count)
1066
2.66k
{
1067
2.66k
    APEPredictor *p = &ctx->predictor;
1068
2.66k
    int32_t *decoded0 = ctx->decoded[0];
1069
2.66k
    int start = 4, shift = 10;
1070
1071
2.66k
    if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
1072
471
        start = 16;
1073
471
        long_filter_high_3800(decoded0, 16, 9, count);
1074
2.19k
    } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
1075
1.39k
        int order = 128, shift2 = 11;
1076
1077
1.39k
        if (ctx->fileversion >= 3830) {
1078
1.03k
            order <<= 1;
1079
1.03k
            shift++;
1080
1.03k
            shift2++;
1081
1.03k
            long_filter_ehigh_3830(decoded0 + order, count - order);
1082
1.03k
        }
1083
1.39k
        start = order;
1084
1.39k
        long_filter_high_3800(decoded0, order, shift2, count);
1085
1.39k
    }
1086
1087
860k
    while (count--) {
1088
857k
        if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
1089
271k
            *decoded0 = filter_fast_3320(p, *decoded0, 0, YDELAYA);
1090
271k
            decoded0++;
1091
585k
        } else {
1092
585k
            *decoded0 = filter_3800(p, *decoded0, 0, YDELAYA, YDELAYB,
1093
585k
                                    start, shift);
1094
585k
            decoded0++;
1095
585k
        }
1096
1097
        /* Combined */
1098
857k
        p->buf++;
1099
857k
        p->sample_pos++;
1100
1101
        /* Have we filled the history buffer? */
1102
857k
        if (p->buf == p->historybuffer + HISTORY_SIZE) {
1103
1.25k
            memmove(p->historybuffer, p->buf,
1104
1.25k
                    PREDICTOR_SIZE * sizeof(*p->historybuffer));
1105
1.25k
            p->buf = p->historybuffer;
1106
1.25k
        }
1107
857k
    }
1108
2.66k
}
1109
1110
static av_always_inline int predictor_update_3930(APEPredictor *p,
1111
                                                  const int decoded, const int filter,
1112
                                                  const int delayA)
1113
443k
{
1114
443k
    int32_t predictionA, sign;
1115
443k
    uint32_t d0, d1, d2, d3;
1116
1117
443k
    p->buf[delayA]     = p->lastA[filter];
1118
443k
    d0 = p->buf[delayA    ];
1119
443k
    d1 = p->buf[delayA    ] - (unsigned)p->buf[delayA - 1];
1120
443k
    d2 = p->buf[delayA - 1] - (unsigned)p->buf[delayA - 2];
1121
443k
    d3 = p->buf[delayA - 2] - (unsigned)p->buf[delayA - 3];
1122
1123
443k
    predictionA = d0 * p->coeffsA[filter][0] +
1124
443k
                  d1 * p->coeffsA[filter][1] +
1125
443k
                  d2 * p->coeffsA[filter][2] +
1126
443k
                  d3 * p->coeffsA[filter][3];
1127
1128
443k
    p->lastA[filter] = decoded + (predictionA >> 9);
1129
443k
    p->filterA[filter] = p->lastA[filter] + ((int)(p->filterA[filter] * 31U) >> 5);
1130
1131
443k
    sign = APESIGN(decoded);
1132
443k
    p->coeffsA[filter][0] += (((int32_t)d0 < 0) * 2 - 1) * sign;
1133
443k
    p->coeffsA[filter][1] += (((int32_t)d1 < 0) * 2 - 1) * sign;
1134
443k
    p->coeffsA[filter][2] += (((int32_t)d2 < 0) * 2 - 1) * sign;
1135
443k
    p->coeffsA[filter][3] += (((int32_t)d3 < 0) * 2 - 1) * sign;
1136
1137
443k
    return p->filterA[filter];
1138
443k
}
1139
1140
static void predictor_decode_stereo_3930(APEContext *ctx, int count)
1141
945
{
1142
945
    APEPredictor *p = &ctx->predictor;
1143
945
    int32_t *decoded0 = ctx->decoded[0];
1144
945
    int32_t *decoded1 = ctx->decoded[1];
1145
1146
945
    ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1147
1148
151k
    while (count--) {
1149
        /* Predictor Y */
1150
150k
        int Y = *decoded1, X = *decoded0;
1151
150k
        *decoded0 = predictor_update_3930(p, Y, 0, YDELAYA);
1152
150k
        decoded0++;
1153
150k
        *decoded1 = predictor_update_3930(p, X, 1, XDELAYA);
1154
150k
        decoded1++;
1155
1156
        /* Combined */
1157
150k
        p->buf++;
1158
1159
        /* Have we filled the history buffer? */
1160
150k
        if (p->buf == p->historybuffer + HISTORY_SIZE) {
1161
284
            memmove(p->historybuffer, p->buf,
1162
284
                    PREDICTOR_SIZE * sizeof(*p->historybuffer));
1163
284
            p->buf = p->historybuffer;
1164
284
        }
1165
150k
    }
1166
945
}
1167
1168
static void predictor_decode_mono_3930(APEContext *ctx, int count)
1169
1.08k
{
1170
1.08k
    APEPredictor *p = &ctx->predictor;
1171
1.08k
    int32_t *decoded0 = ctx->decoded[0];
1172
1173
1.08k
    ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1174
1175
143k
    while (count--) {
1176
142k
        *decoded0 = predictor_update_3930(p, *decoded0, 0, YDELAYA);
1177
142k
        decoded0++;
1178
1179
142k
        p->buf++;
1180
1181
        /* Have we filled the history buffer? */
1182
142k
        if (p->buf == p->historybuffer + HISTORY_SIZE) {
1183
263
            memmove(p->historybuffer, p->buf,
1184
263
                    PREDICTOR_SIZE * sizeof(*p->historybuffer));
1185
263
            p->buf = p->historybuffer;
1186
263
        }
1187
142k
    }
1188
1.08k
}
1189
1190
static av_always_inline int predictor_update_filter(APEPredictor64 *p,
1191
                                                    const int decoded, const int filter,
1192
                                                    const int delayA,  const int delayB,
1193
                                                    const int adaptA,  const int adaptB,
1194
                                                    int interim_mode)
1195
439k
{
1196
439k
    int64_t predictionA, predictionB;
1197
439k
    int32_t sign;
1198
1199
439k
    p->buf[delayA]     = p->lastA[filter];
1200
439k
    p->buf[adaptA]     = APESIGN(p->buf[delayA]);
1201
439k
    p->buf[delayA - 1] = p->buf[delayA] - (uint64_t)p->buf[delayA - 1];
1202
439k
    p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
1203
1204
439k
    predictionA = p->buf[delayA    ] * p->coeffsA[filter][0] +
1205
439k
                  p->buf[delayA - 1] * p->coeffsA[filter][1] +
1206
439k
                  p->buf[delayA - 2] * p->coeffsA[filter][2] +
1207
439k
                  p->buf[delayA - 3] * p->coeffsA[filter][3];
1208
1209
    /*  Apply a scaled first-order filter compression */
1210
439k
    p->buf[delayB]     = p->filterA[filter ^ 1] - ((int64_t)(p->filterB[filter] * 31ULL) >> 5);
1211
439k
    p->buf[adaptB]     = APESIGN(p->buf[delayB]);
1212
439k
    p->buf[delayB - 1] = p->buf[delayB] - (uint64_t)p->buf[delayB - 1];
1213
439k
    p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
1214
439k
    p->filterB[filter] = p->filterA[filter ^ 1];
1215
1216
439k
    predictionB = p->buf[delayB    ] * p->coeffsB[filter][0] +
1217
439k
                  p->buf[delayB - 1] * p->coeffsB[filter][1] +
1218
439k
                  p->buf[delayB - 2] * p->coeffsB[filter][2] +
1219
439k
                  p->buf[delayB - 3] * p->coeffsB[filter][3] +
1220
439k
                  p->buf[delayB - 4] * p->coeffsB[filter][4];
1221
1222
439k
    if (interim_mode < 1) {
1223
270k
        predictionA = (int32_t)predictionA;
1224
270k
        predictionB = (int32_t)predictionB;
1225
270k
        p->lastA[filter] = (int32_t)(decoded + (unsigned)((int32_t)(predictionA + (predictionB >> 1)) >> 10));
1226
270k
    } else {
1227
168k
        p->lastA[filter] = decoded + ((int64_t)((uint64_t)predictionA + (predictionB >> 1)) >> 10);
1228
168k
    }
1229
439k
    p->filterA[filter] = p->lastA[filter] + ((int64_t)(p->filterA[filter] * 31ULL) >> 5);
1230
1231
439k
    sign = APESIGN(decoded);
1232
439k
    p->coeffsA[filter][0] += p->buf[adaptA    ] * sign;
1233
439k
    p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
1234
439k
    p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
1235
439k
    p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
1236
439k
    p->coeffsB[filter][0] += p->buf[adaptB    ] * sign;
1237
439k
    p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
1238
439k
    p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
1239
439k
    p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
1240
439k
    p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
1241
1242
439k
    return p->filterA[filter];
1243
439k
}
1244
1245
static void predictor_decode_stereo_3950(APEContext *ctx, int count)
1246
1.22k
{
1247
1.22k
    APEPredictor64 *p_default = &ctx->predictor64;
1248
1.22k
    APEPredictor64 p_interim;
1249
1.22k
    int lcount = count;
1250
1.22k
    int num_passes = 1;
1251
1252
1.22k
    ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1253
1.22k
    if (ctx->interim_mode == -1) {
1254
429
        p_interim = *p_default;
1255
429
        num_passes ++;
1256
429
        memcpy(ctx->interim[0], ctx->decoded[0], sizeof(*ctx->interim[0])*count);
1257
429
        memcpy(ctx->interim[1], ctx->decoded[1], sizeof(*ctx->interim[1])*count);
1258
429
    }
1259
1260
2.88k
    for (int pass = 0; pass < num_passes; pass++) {
1261
1.65k
        int32_t *decoded0, *decoded1;
1262
1.65k
        int interim_mode = ctx->interim_mode > 0 || pass;
1263
1.65k
        APEPredictor64 *p;
1264
1265
1.65k
        if (pass) {
1266
429
            p        = &p_interim;
1267
429
            decoded0 = ctx->interim[0];
1268
429
            decoded1 = ctx->interim[1];
1269
1.22k
        } else {
1270
1.22k
            p        = p_default;
1271
1.22k
            decoded0 = ctx->decoded[0];
1272
1.22k
            decoded1 = ctx->decoded[1];
1273
1.22k
        }
1274
1.65k
        p->buf = p->historybuffer;
1275
1276
1.65k
        count = lcount;
1277
221k
        while (count--) {
1278
            /* Predictor Y */
1279
219k
            int32_t a0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
1280
219k
                                                YADAPTCOEFFSA, YADAPTCOEFFSB,
1281
219k
                                                interim_mode);
1282
219k
            int32_t a1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
1283
219k
                                                XADAPTCOEFFSA, XADAPTCOEFFSB,
1284
219k
                                                interim_mode);
1285
219k
            *decoded0++ = a0;
1286
219k
            *decoded1++ = a1;
1287
219k
            if (num_passes > 1) {
1288
168k
                int32_t left  = a1 - (unsigned)(a0 / 2);
1289
168k
                int32_t right = left + (unsigned)a0;
1290
1291
168k
                if (FFMIN(FFNABS(left), FFNABS(right)) < -(1<<23)) {
1292
119
                    ctx->interim_mode = !interim_mode;
1293
119
                    av_log(ctx->avctx, AV_LOG_VERBOSE, "Interim mode: %d\n", ctx->interim_mode);
1294
119
                    break;
1295
119
                }
1296
168k
            }
1297
1298
            /* Combined */
1299
219k
            p->buf++;
1300
1301
            /* Have we filled the history buffer? */
1302
219k
            if (p->buf == p->historybuffer + HISTORY_SIZE) {
1303
397
                memmove(p->historybuffer, p->buf,
1304
397
                        PREDICTOR_SIZE * sizeof(*p->historybuffer));
1305
397
                p->buf = p->historybuffer;
1306
397
            }
1307
219k
        }
1308
1.65k
    }
1309
1.22k
    if (num_passes > 1 && ctx->interim_mode > 0) {
1310
7
        memcpy(ctx->decoded[0], ctx->interim[0], sizeof(*ctx->interim[0])*lcount);
1311
7
        memcpy(ctx->decoded[1], ctx->interim[1], sizeof(*ctx->interim[1])*lcount);
1312
7
        *p_default = p_interim;
1313
7
        p_default->buf = p_default->historybuffer;
1314
7
    }
1315
1.22k
}
1316
1317
static void predictor_decode_mono_3950(APEContext *ctx, int count)
1318
665
{
1319
665
    APEPredictor64 *p = &ctx->predictor64;
1320
665
    int32_t *decoded0 = ctx->decoded[0];
1321
665
    int32_t predictionA, currentA, A, sign;
1322
1323
665
    ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1324
1325
665
    currentA = p->lastA[0];
1326
1327
149k
    while (count--) {
1328
148k
        A = *decoded0;
1329
1330
148k
        p->buf[YDELAYA] = currentA;
1331
148k
        p->buf[YDELAYA - 1] = p->buf[YDELAYA] - (uint64_t)p->buf[YDELAYA - 1];
1332
1333
148k
        predictionA = p->buf[YDELAYA    ] * p->coeffsA[0][0] +
1334
148k
                      p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
1335
148k
                      p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
1336
148k
                      p->buf[YDELAYA - 3] * p->coeffsA[0][3];
1337
1338
148k
        currentA = A + (uint64_t)(predictionA >> 10);
1339
1340
148k
        p->buf[YADAPTCOEFFSA]     = APESIGN(p->buf[YDELAYA    ]);
1341
148k
        p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
1342
1343
148k
        sign = APESIGN(A);
1344
148k
        p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA    ] * sign;
1345
148k
        p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
1346
148k
        p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
1347
148k
        p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
1348
1349
148k
        p->buf++;
1350
1351
        /* Have we filled the history buffer? */
1352
148k
        if (p->buf == p->historybuffer + HISTORY_SIZE) {
1353
277
            memmove(p->historybuffer, p->buf,
1354
277
                    PREDICTOR_SIZE * sizeof(*p->historybuffer));
1355
277
            p->buf = p->historybuffer;
1356
277
        }
1357
1358
148k
        p->filterA[0] = currentA + (uint64_t)((int64_t)(p->filterA[0] * 31U) >> 5);
1359
148k
        *(decoded0++) = p->filterA[0];
1360
148k
    }
1361
1362
665
    p->lastA[0] = currentA;
1363
665
}
1364
1365
static void do_init_filter(APEFilter *f, int16_t *buf, int order)
1366
65.6k
{
1367
65.6k
    f->coeffs = buf;
1368
65.6k
    f->historybuffer = buf + order;
1369
65.6k
    f->delay       = f->historybuffer + order * 2;
1370
65.6k
    f->adaptcoeffs = f->historybuffer + order;
1371
1372
65.6k
    memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
1373
65.6k
    memset(f->coeffs, 0, order * sizeof(*f->coeffs));
1374
65.6k
    f->avg = 0;
1375
65.6k
}
1376
1377
static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
1378
32.8k
{
1379
32.8k
    do_init_filter(&f[0], buf, order);
1380
32.8k
    do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
1381
32.8k
}
1382
1383
static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
1384
                            int32_t *data, int count, int order, int fracbits)
1385
12.5k
{
1386
12.5k
    int res;
1387
12.5k
    unsigned absres;
1388
1389
918k
    while (count--) {
1390
        /* round fixedpoint scalar product */
1391
905k
        res = ctx->adsp.scalarproduct_and_madd_int16(f->coeffs,
1392
905k
                                                     f->delay - order,
1393
905k
                                                     f->adaptcoeffs - order,
1394
905k
                                                     order, APESIGN(*data));
1395
905k
        res = (int64_t)(res + (1LL << (fracbits - 1))) >> fracbits;
1396
905k
        res += (unsigned)*data;
1397
905k
        *data++ = res;
1398
1399
        /* Update the output history */
1400
905k
        *f->delay++ = av_clip_int16(res);
1401
1402
905k
        if (version < 3980) {
1403
            /* Version ??? to < 3.98 files (untested) */
1404
52.3k
            f->adaptcoeffs[0]  = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
1405
52.3k
            f->adaptcoeffs[-4] >>= 1;
1406
52.3k
            f->adaptcoeffs[-8] >>= 1;
1407
853k
        } else {
1408
            /* Version 3.98 and later files */
1409
1410
            /* Update the adaption coefficients */
1411
853k
            absres = FFABSU(res);
1412
853k
            if (absres)
1413
269k
                *f->adaptcoeffs = APESIGN(res) *
1414
269k
                                  (8 << ((absres > f->avg * 3LL) + (absres > (f->avg + f->avg / 3))));
1415
                /* equivalent to the following code
1416
                    if (absres <= f->avg * 4 / 3)
1417
                        *f->adaptcoeffs = APESIGN(res) * 8;
1418
                    else if (absres <= f->avg * 3)
1419
                        *f->adaptcoeffs = APESIGN(res) * 16;
1420
                    else
1421
                        *f->adaptcoeffs = APESIGN(res) * 32;
1422
                */
1423
583k
            else
1424
583k
                *f->adaptcoeffs = 0;
1425
1426
853k
            f->avg += (int)(absres - (unsigned)f->avg) / 16;
1427
1428
853k
            f->adaptcoeffs[-1] >>= 1;
1429
853k
            f->adaptcoeffs[-2] >>= 1;
1430
853k
            f->adaptcoeffs[-8] >>= 1;
1431
853k
        }
1432
1433
905k
        f->adaptcoeffs++;
1434
1435
        /* Have we filled the history buffer? */
1436
905k
        if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
1437
1.61k
            memmove(f->historybuffer, f->delay - (order * 2),
1438
1.61k
                    (order * 2) * sizeof(*f->historybuffer));
1439
1.61k
            f->delay = f->historybuffer + order * 2;
1440
1.61k
            f->adaptcoeffs = f->historybuffer + order;
1441
1.61k
        }
1442
905k
    }
1443
12.5k
}
1444
1445
static void apply_filter(APEContext *ctx, APEFilter *f,
1446
                         int32_t *data0, int32_t *data1,
1447
                         int count, int order, int fracbits)
1448
8.05k
{
1449
8.05k
    do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
1450
8.05k
    if (data1)
1451
4.45k
        do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
1452
8.05k
}
1453
1454
static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
1455
                              int32_t *decoded1, int count)
1456
3.92k
{
1457
3.92k
    int i;
1458
1459
11.9k
    for (i = 0; i < APE_FILTER_LEVELS; i++) {
1460
9.92k
        if (!ape_filter_orders[ctx->fset][i])
1461
1.86k
            break;
1462
8.05k
        apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
1463
8.05k
                     ape_filter_orders[ctx->fset][i],
1464
8.05k
                     ape_filter_fracbits[ctx->fset][i]);
1465
8.05k
    }
1466
3.92k
}
1467
1468
static int init_frame_decoder(APEContext *ctx)
1469
34.1k
{
1470
34.1k
    int i, ret;
1471
34.1k
    if ((ret = init_entropy_decoder(ctx)) < 0)
1472
743
        return ret;
1473
33.4k
    init_predictor_decoder(ctx);
1474
1475
66.2k
    for (i = 0; i < APE_FILTER_LEVELS; i++) {
1476
63.5k
        if (!ape_filter_orders[ctx->fset][i])
1477
30.7k
            break;
1478
32.8k
        init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
1479
32.8k
                    ape_filter_orders[ctx->fset][i]);
1480
32.8k
    }
1481
33.4k
    return 0;
1482
34.1k
}
1483
1484
static void ape_unpack_mono(APEContext *ctx, int count)
1485
7.56k
{
1486
7.56k
    if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
1487
        /* We are pure silence, so we're done. */
1488
1.41k
        av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
1489
1.41k
        return;
1490
1.41k
    }
1491
1492
6.15k
    ctx->entropy_decode_mono(ctx, count);
1493
6.15k
    if (ctx->error)
1494
1.73k
        return;
1495
1496
    /* Now apply the predictor decoding */
1497
4.41k
    ctx->predictor_decode_mono(ctx, count);
1498
1499
    /* Pseudo-stereo - just copy left channel to right channel */
1500
4.41k
    if (ctx->channels == 2) {
1501
217
        memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
1502
217
    }
1503
4.41k
}
1504
1505
static void ape_unpack_stereo(APEContext *ctx, int count)
1506
25.3k
{
1507
25.3k
    unsigned left, right;
1508
25.3k
    int32_t *decoded0 = ctx->decoded[0];
1509
25.3k
    int32_t *decoded1 = ctx->decoded[1];
1510
1511
25.3k
    if ((ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) == APE_FRAMECODE_STEREO_SILENCE) {
1512
        /* We are pure silence, so we're done. */
1513
450
        av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
1514
450
        return;
1515
450
    }
1516
1517
24.8k
    ctx->entropy_decode_stereo(ctx, count);
1518
24.8k
    if (ctx->error)
1519
5.63k
        return;
1520
1521
    /* Now apply the predictor decoding */
1522
19.2k
    ctx->predictor_decode_stereo(ctx, count);
1523
1524
    /* Decorrelate and scale to output depth */
1525
1.45M
    while (count--) {
1526
1.43M
        left = *decoded1 - (unsigned)(*decoded0 / 2);
1527
1.43M
        right = left + *decoded0;
1528
1529
1.43M
        *(decoded0++) = left;
1530
1.43M
        *(decoded1++) = right;
1531
1.43M
    }
1532
19.2k
}
1533
1534
static int ape_decode_frame(AVCodecContext *avctx, AVFrame *frame,
1535
                            int *got_frame_ptr, AVPacket *avpkt)
1536
90.9k
{
1537
90.9k
    const uint8_t *buf = avpkt->data;
1538
90.9k
    APEContext *s = avctx->priv_data;
1539
90.9k
    uint8_t *sample8;
1540
90.9k
    int16_t *sample16;
1541
90.9k
    int32_t *sample24;
1542
90.9k
    int i, ch, ret;
1543
90.9k
    int blockstodecode;
1544
90.9k
    uint64_t decoded_buffer_size;
1545
1546
    /* this should never be negative, but bad things will happen if it is, so
1547
       check it just to make sure. */
1548
90.9k
    av_assert0(s->samples >= 0);
1549
1550
90.9k
    if(!s->samples){
1551
90.0k
        uint32_t nblocks, offset;
1552
90.0k
        int buf_size;
1553
1554
90.0k
        if (!avpkt->size) {
1555
1.18k
            *got_frame_ptr = 0;
1556
1.18k
            return 0;
1557
1.18k
        }
1558
88.8k
        if (avpkt->size < 8) {
1559
48.2k
            av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1560
48.2k
            return AVERROR_INVALIDDATA;
1561
48.2k
        }
1562
40.5k
        buf_size = avpkt->size & ~3;
1563
40.5k
        if (buf_size != avpkt->size) {
1564
23.9k
            av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
1565
23.9k
                   "extra bytes at the end will be skipped.\n");
1566
23.9k
        }
1567
40.5k
        if (s->fileversion < 3950) // previous versions overread two bytes
1568
33.5k
            buf_size += 2;
1569
40.5k
        av_fast_padded_malloc(&s->data, &s->data_size, buf_size);
1570
40.5k
        if (!s->data)
1571
0
            return AVERROR(ENOMEM);
1572
40.5k
        s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,
1573
40.5k
                          buf_size >> 2);
1574
40.5k
        memset(s->data + (buf_size & ~3), 0, buf_size & 3);
1575
40.5k
        s->ptr = s->data;
1576
40.5k
        s->data_end = s->data + buf_size;
1577
1578
40.5k
        nblocks = bytestream_get_be32(&s->ptr);
1579
40.5k
        offset  = bytestream_get_be32(&s->ptr);
1580
40.5k
        if (s->fileversion >= 3900) {
1581
11.7k
            if (offset > 3) {
1582
3.72k
                av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
1583
3.72k
                av_freep(&s->data);
1584
3.72k
                s->data_size = 0;
1585
3.72k
                return AVERROR_INVALIDDATA;
1586
3.72k
            }
1587
8.03k
            if (s->data_end - s->ptr < offset) {
1588
212
                av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1589
212
                return AVERROR_INVALIDDATA;
1590
212
            }
1591
7.82k
            s->ptr += offset;
1592
28.8k
        } else {
1593
28.8k
            if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0)
1594
0
                return ret;
1595
28.8k
            if (s->fileversion > 3800)
1596
16.5k
                skip_bits_long(&s->gb, offset * 8);
1597
12.2k
            else
1598
12.2k
                skip_bits_long(&s->gb, offset);
1599
28.8k
        }
1600
1601
36.6k
        if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) {
1602
2.46k
            av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n",
1603
2.46k
                   nblocks);
1604
2.46k
            return AVERROR_INVALIDDATA;
1605
2.46k
        }
1606
1607
        /* Initialize the frame decoder */
1608
34.1k
        if (init_frame_decoder(s) < 0) {
1609
743
            av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
1610
743
            return AVERROR_INVALIDDATA;
1611
743
        }
1612
33.4k
        s->samples = nblocks;
1613
33.4k
    }
1614
1615
34.3k
    if (!s->data) {
1616
0
        *got_frame_ptr = 0;
1617
0
        return avpkt->size;
1618
0
    }
1619
1620
34.3k
    blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
1621
    // for old files coefficients were not interleaved,
1622
    // so we need to decode all of them at once
1623
34.3k
    if (s->fileversion < 3930)
1624
27.4k
        blockstodecode = s->samples;
1625
1626
    /* reallocate decoded sample buffer if needed */
1627
34.3k
    decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer);
1628
34.3k
    av_assert0(decoded_buffer_size <= INT_MAX);
1629
1630
    /* get output buffer */
1631
34.3k
    frame->nb_samples = blockstodecode;
1632
34.3k
    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
1633
1.52k
        s->samples=0;
1634
1.52k
        return ret;
1635
1.52k
    }
1636
1637
32.8k
    av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size);
1638
32.8k
    if (!s->decoded_buffer)
1639
0
        return AVERROR(ENOMEM);
1640
32.8k
    memset(s->decoded_buffer, 0, decoded_buffer_size);
1641
32.8k
    s->decoded[0] = s->decoded_buffer;
1642
32.8k
    s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
1643
1644
32.8k
    if (s->interim_mode < 0) {
1645
13.9k
        av_fast_malloc(&s->interim_buffer, &s->interim_size, decoded_buffer_size);
1646
13.9k
        if (!s->interim_buffer)
1647
0
            return AVERROR(ENOMEM);
1648
13.9k
        memset(s->interim_buffer, 0, decoded_buffer_size);
1649
13.9k
        s->interim[0] = s->interim_buffer;
1650
13.9k
        s->interim[1] = s->interim_buffer + FFALIGN(blockstodecode, 8);
1651
18.9k
    } else {
1652
18.9k
        av_freep(&s->interim_buffer);
1653
18.9k
        s->interim_size = 0;
1654
18.9k
        memset(s->interim, 0, sizeof(s->interim));
1655
18.9k
    }
1656
1657
32.8k
    s->error=0;
1658
1659
32.8k
    if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
1660
7.56k
        ape_unpack_mono(s, blockstodecode);
1661
25.3k
    else
1662
25.3k
        ape_unpack_stereo(s, blockstodecode);
1663
1664
32.8k
    if (s->error) {
1665
7.36k
        s->samples=0;
1666
7.36k
        av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
1667
7.36k
        return AVERROR_INVALIDDATA;
1668
7.36k
    }
1669
1670
25.5k
    switch (s->bps) {
1671
12.5k
    case 8:
1672
36.5k
        for (ch = 0; ch < s->channels; ch++) {
1673
24.0k
            sample8 = (uint8_t *)frame->data[ch];
1674
2.47M
            for (i = 0; i < blockstodecode; i++)
1675
2.45M
                *sample8++ = (s->decoded[ch][i] + 0x80U) & 0xff;
1676
24.0k
        }
1677
12.5k
        break;
1678
2.25k
    case 16:
1679
6.20k
        for (ch = 0; ch < s->channels; ch++) {
1680
3.94k
            sample16 = (int16_t *)frame->data[ch];
1681
5.64M
            for (i = 0; i < blockstodecode; i++)
1682
5.64M
                *sample16++ = s->decoded[ch][i];
1683
3.94k
        }
1684
2.25k
        break;
1685
10.7k
    case 24:
1686
29.2k
        for (ch = 0; ch < s->channels; ch++) {
1687
18.5k
            sample24 = (int32_t *)frame->data[ch];
1688
4.32M
            for (i = 0; i < blockstodecode; i++)
1689
4.30M
                *sample24++ = s->decoded[ch][i] * 256U;
1690
18.5k
        }
1691
10.7k
        break;
1692
25.5k
    }
1693
1694
25.5k
    s->samples -= blockstodecode;
1695
1696
25.5k
    if (avctx->err_recognition & AV_EF_CRCCHECK &&
1697
15.4k
        s->fileversion >= 3900) {
1698
4.13k
        uint32_t crc = s->CRC_state;
1699
4.13k
        const AVCRC *crc_tab = av_crc_get_table(AV_CRC_32_IEEE_LE);
1700
4.13k
        int stride = s->bps == 24 ? 4 : (s->bps>>3);
1701
4.13k
        int offset = s->bps == 24;
1702
4.13k
        int bytes  = s->bps >> 3;
1703
1704
4.56M
        for (i = 0; i < blockstodecode; i++) {
1705
12.5M
            for (ch = 0; ch < s->channels; ch++) {
1706
#if HAVE_BIGENDIAN
1707
                uint8_t *smp_native = frame->data[ch] + i*stride;
1708
                uint8_t smp[4];
1709
                for(int j = 0; j<stride; j++)
1710
                    smp[j] = smp_native[stride-j-1];
1711
#else
1712
7.99M
                uint8_t *smp = frame->data[ch] + i*stride;
1713
7.99M
#endif
1714
7.99M
                crc = av_crc(crc_tab, crc, smp+offset, bytes);
1715
7.99M
            }
1716
4.56M
        }
1717
1718
4.13k
        if (!s->samples && (~crc >> 1) ^ s->CRC) {
1719
3.04k
            av_log(avctx, AV_LOG_ERROR, "CRC mismatch! Previously decoded "
1720
3.04k
                   "frames may have been affected as well.\n");
1721
3.04k
            if (avctx->err_recognition & AV_EF_EXPLODE)
1722
819
                return AVERROR_INVALIDDATA;
1723
3.04k
        }
1724
1725
3.32k
        s->CRC_state = crc;
1726
3.32k
    }
1727
1728
24.6k
    *got_frame_ptr = 1;
1729
1730
24.6k
    return !s->samples ? avpkt->size : 0;
1731
25.5k
}
1732
1733
static av_cold void ape_flush(AVCodecContext *avctx)
1734
45.7k
{
1735
45.7k
    APEContext *s = avctx->priv_data;
1736
45.7k
    s->samples= 0;
1737
45.7k
}
1738
1739
#define OFFSET(x) offsetof(APEContext, x)
1740
#define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
1741
static const AVOption options[] = {
1742
    { "max_samples", "maximum number of samples decoded per call",             OFFSET(blocks_per_loop), AV_OPT_TYPE_INT,   { .i64 = 4608 },    1,       INT_MAX, PAR, .unit = "max_samples" },
1743
    { "all",         "no maximum. decode all samples for each packet at once", 0,                       AV_OPT_TYPE_CONST, { .i64 = INT_MAX }, INT_MIN, INT_MAX, PAR, .unit = "max_samples" },
1744
    { NULL},
1745
};
1746
1747
static const AVClass ape_decoder_class = {
1748
    .class_name = "APE decoder",
1749
    .item_name  = av_default_item_name,
1750
    .option     = options,
1751
    .version    = LIBAVUTIL_VERSION_INT,
1752
};
1753
1754
const FFCodec ff_ape_decoder = {
1755
    .p.name         = "ape",
1756
    CODEC_LONG_NAME("Monkey's Audio"),
1757
    .p.type         = AVMEDIA_TYPE_AUDIO,
1758
    .p.id           = AV_CODEC_ID_APE,
1759
    .priv_data_size = sizeof(APEContext),
1760
    .init           = ape_decode_init,
1761
    .close          = ape_decode_close,
1762
    FF_CODEC_DECODE_CB(ape_decode_frame),
1763
    .p.capabilities = AV_CODEC_CAP_DELAY |
1764
                      AV_CODEC_CAP_DR1,
1765
    .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP,
1766
    .flush          = ape_flush,
1767
    .p.priv_class   = &ape_decoder_class,
1768
};