GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/apedec.c Lines: 572 789 72.5 %
Date: 2020-07-11 02:49:52 Branches: 210 340 61.8 %

Line Branch Exec 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/avassert.h"
26
#include "libavutil/channel_layout.h"
27
#include "libavutil/crc.h"
28
#include "libavutil/opt.h"
29
#include "lossless_audiodsp.h"
30
#include "avcodec.h"
31
#include "bswapdsp.h"
32
#include "bytestream.h"
33
#include "internal.h"
34
#include "get_bits.h"
35
#include "unary.h"
36
37
/**
38
 * @file
39
 * Monkey's Audio lossless audio decoder
40
 */
41
42
#define MAX_CHANNELS        2
43
#define MAX_BYTESPERSAMPLE  3
44
45
#define APE_FRAMECODE_MONO_SILENCE    1
46
#define APE_FRAMECODE_STEREO_SILENCE  3
47
#define APE_FRAMECODE_PSEUDO_STEREO   4
48
49
#define HISTORY_SIZE 512
50
#define PREDICTOR_ORDER 8
51
/** Total size of all predictor histories */
52
#define PREDICTOR_SIZE 50
53
54
#define YDELAYA (18 + PREDICTOR_ORDER*4)
55
#define YDELAYB (18 + PREDICTOR_ORDER*3)
56
#define XDELAYA (18 + PREDICTOR_ORDER*2)
57
#define XDELAYB (18 + PREDICTOR_ORDER)
58
59
#define YADAPTCOEFFSA 18
60
#define XADAPTCOEFFSA 14
61
#define YADAPTCOEFFSB 10
62
#define XADAPTCOEFFSB 5
63
64
/**
65
 * Possible compression levels
66
 * @{
67
 */
68
enum APECompressionLevel {
69
    COMPRESSION_LEVEL_FAST       = 1000,
70
    COMPRESSION_LEVEL_NORMAL     = 2000,
71
    COMPRESSION_LEVEL_HIGH       = 3000,
72
    COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
73
    COMPRESSION_LEVEL_INSANE     = 5000
74
};
75
/** @} */
76
77
#define APE_FILTER_LEVELS 3
78
79
/** Filter orders depending on compression level */
80
static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
81
    {  0,   0,    0 },
82
    { 16,   0,    0 },
83
    { 64,   0,    0 },
84
    { 32, 256,    0 },
85
    { 16, 256, 1280 }
86
};
87
88
/** Filter fraction bits depending on compression level */
89
static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
90
    {  0,  0,  0 },
91
    { 11,  0,  0 },
92
    { 11,  0,  0 },
93
    { 10, 13,  0 },
94
    { 11, 13, 15 }
95
};
96
97
98
/** Filters applied to the decoded data */
99
typedef struct APEFilter {
100
    int16_t *coeffs;        ///< actual coefficients used in filtering
101
    int16_t *adaptcoeffs;   ///< adaptive filter coefficients used for correcting of actual filter coefficients
102
    int16_t *historybuffer; ///< filter memory
103
    int16_t *delay;         ///< filtered values
104
105
    int avg;
106
} APEFilter;
107
108
typedef struct APERice {
109
    uint32_t k;
110
    uint32_t ksum;
111
} APERice;
112
113
typedef struct APERangecoder {
114
    uint32_t low;           ///< low end of interval
115
    uint32_t range;         ///< length of interval
116
    uint32_t help;          ///< bytes_to_follow resp. intermediate value
117
    unsigned int buffer;    ///< buffer for input/output
118
} APERangecoder;
119
120
/** Filter histories */
121
typedef struct APEPredictor {
122
    int32_t *buf;
123
124
    int32_t lastA[2];
125
126
    int32_t filterA[2];
127
    int32_t filterB[2];
128
129
    uint32_t coeffsA[2][4];  ///< adaption coefficients
130
    uint32_t coeffsB[2][5];  ///< adaption coefficients
131
    int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
132
133
    unsigned int sample_pos;
134
} APEPredictor;
135
136
/** Decoder context */
137
typedef struct APEContext {
138
    AVClass *class;                          ///< class for AVOptions
139
    AVCodecContext *avctx;
140
    BswapDSPContext bdsp;
141
    LLAudDSPContext adsp;
142
    int channels;
143
    int samples;                             ///< samples left to decode in current frame
144
    int bps;
145
146
    int fileversion;                         ///< codec version, very important in decoding process
147
    int compression_level;                   ///< compression levels
148
    int fset;                                ///< which filter set to use (calculated from compression level)
149
    int flags;                               ///< global decoder flags
150
151
    uint32_t CRC;                            ///< signalled frame CRC
152
    uint32_t CRC_state;                      ///< accumulated CRC
153
    int frameflags;                          ///< frame flags
154
    APEPredictor predictor;                  ///< predictor used for final reconstruction
155
156
    int32_t *decoded_buffer;
157
    int decoded_size;
158
    int32_t *decoded[MAX_CHANNELS];          ///< decoded data for each channel
159
    int blocks_per_loop;                     ///< maximum number of samples to decode for each call
160
161
    int16_t* filterbuf[APE_FILTER_LEVELS];   ///< filter memory
162
163
    APERangecoder rc;                        ///< rangecoder used to decode actual values
164
    APERice riceX;                           ///< rice code parameters for the second channel
165
    APERice riceY;                           ///< rice code parameters for the first channel
166
    APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
167
    GetBitContext gb;
168
169
    uint8_t *data;                           ///< current frame data
170
    uint8_t *data_end;                       ///< frame data end
171
    int data_size;                           ///< frame data allocated size
172
    const uint8_t *ptr;                      ///< current position in frame data
173
174
    int error;
175
176
    void (*entropy_decode_mono)(struct APEContext *ctx, int blockstodecode);
177
    void (*entropy_decode_stereo)(struct APEContext *ctx, int blockstodecode);
178
    void (*predictor_decode_mono)(struct APEContext *ctx, int count);
179
    void (*predictor_decode_stereo)(struct APEContext *ctx, int count);
180
} APEContext;
181
182
static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
183
                              int32_t *decoded1, int count);
184
185
static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode);
186
static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode);
187
static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode);
188
static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode);
189
static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode);
190
static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode);
191
static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode);
192
static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode);
193
static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode);
194
195
static void predictor_decode_mono_3800(APEContext *ctx, int count);
196
static void predictor_decode_stereo_3800(APEContext *ctx, int count);
197
static void predictor_decode_mono_3930(APEContext *ctx, int count);
198
static void predictor_decode_stereo_3930(APEContext *ctx, int count);
199
static void predictor_decode_mono_3950(APEContext *ctx, int count);
200
static void predictor_decode_stereo_3950(APEContext *ctx, int count);
201
202
27
static av_cold int ape_decode_close(AVCodecContext *avctx)
203
{
204
27
    APEContext *s = avctx->priv_data;
205
    int i;
206
207
108
    for (i = 0; i < APE_FILTER_LEVELS; i++)
208
81
        av_freep(&s->filterbuf[i]);
209
210
27
    av_freep(&s->decoded_buffer);
211
27
    av_freep(&s->data);
212
27
    s->decoded_size = s->data_size = 0;
213
214
27
    return 0;
215
}
216
217
27
static av_cold int ape_decode_init(AVCodecContext *avctx)
218
{
219
27
    APEContext *s = avctx->priv_data;
220
    int i;
221
222
27
    if (avctx->extradata_size != 6) {
223
        av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
224
        return AVERROR(EINVAL);
225
    }
226
27
    if (avctx->channels > 2) {
227
        av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
228
        return AVERROR(EINVAL);
229
    }
230
27
    s->bps = avctx->bits_per_coded_sample;
231

27
    switch (s->bps) {
232
    case 8:
233
        avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
234
        break;
235
27
    case 16:
236
27
        avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
237
27
        break;
238
    case 24:
239
        avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
240
        break;
241
    default:
242
        avpriv_request_sample(avctx,
243
                              "%d bits per coded sample", s->bps);
244
        return AVERROR_PATCHWELCOME;
245
    }
246
27
    s->avctx             = avctx;
247
27
    s->channels          = avctx->channels;
248
27
    s->fileversion       = AV_RL16(avctx->extradata);
249
27
    s->compression_level = AV_RL16(avctx->extradata + 2);
250
27
    s->flags             = AV_RL16(avctx->extradata + 4);
251
252
27
    av_log(avctx, AV_LOG_VERBOSE, "Compression Level: %d - Flags: %d\n",
253
           s->compression_level, s->flags);
254

27
    if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE ||
255
27
        !s->compression_level ||
256

27
        (s->fileversion < 3930 && s->compression_level == COMPRESSION_LEVEL_INSANE)) {
257
        av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
258
               s->compression_level);
259
        return AVERROR_INVALIDDATA;
260
    }
261
27
    s->fset = s->compression_level / 1000 - 1;
262
66
    for (i = 0; i < APE_FILTER_LEVELS; i++) {
263
66
        if (!ape_filter_orders[s->fset][i])
264
27
            break;
265
39
        if (!(s->filterbuf[i] = av_malloc((ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4)))
266
            return AVERROR(ENOMEM);
267
    }
268
269
27
    if (s->fileversion < 3860) {
270
4
        s->entropy_decode_mono   = entropy_decode_mono_0000;
271
4
        s->entropy_decode_stereo = entropy_decode_stereo_0000;
272
23
    } else if (s->fileversion < 3900) {
273
8
        s->entropy_decode_mono   = entropy_decode_mono_3860;
274
8
        s->entropy_decode_stereo = entropy_decode_stereo_3860;
275
15
    } else if (s->fileversion < 3930) {
276
8
        s->entropy_decode_mono   = entropy_decode_mono_3900;
277
8
        s->entropy_decode_stereo = entropy_decode_stereo_3900;
278
7
    } else if (s->fileversion < 3990) {
279
4
        s->entropy_decode_mono   = entropy_decode_mono_3900;
280
4
        s->entropy_decode_stereo = entropy_decode_stereo_3930;
281
    } else {
282
3
        s->entropy_decode_mono   = entropy_decode_mono_3990;
283
3
        s->entropy_decode_stereo = entropy_decode_stereo_3990;
284
    }
285
286
27
    if (s->fileversion < 3930) {
287
20
        s->predictor_decode_mono   = predictor_decode_mono_3800;
288
20
        s->predictor_decode_stereo = predictor_decode_stereo_3800;
289
7
    } else if (s->fileversion < 3950) {
290
4
        s->predictor_decode_mono   = predictor_decode_mono_3930;
291
4
        s->predictor_decode_stereo = predictor_decode_stereo_3930;
292
    } else {
293
3
        s->predictor_decode_mono   = predictor_decode_mono_3950;
294
3
        s->predictor_decode_stereo = predictor_decode_stereo_3950;
295
    }
296
297
27
    ff_bswapdsp_init(&s->bdsp);
298
27
    ff_llauddsp_init(&s->adsp);
299
27
    avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
300
301
27
    return 0;
302
}
303
304
/**
305
 * @name APE range decoding functions
306
 * @{
307
 */
308
309
#define CODE_BITS    32
310
#define TOP_VALUE    ((unsigned int)1 << (CODE_BITS-1))
311
#define SHIFT_BITS   (CODE_BITS - 9)
312
#define EXTRA_BITS   ((CODE_BITS-2) % 8 + 1)
313
#define BOTTOM_VALUE (TOP_VALUE >> 8)
314
315
/** Start the decoder */
316
26
static inline void range_start_decoding(APEContext *ctx)
317
{
318
26
    ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
319
26
    ctx->rc.low    = ctx->rc.buffer >> (8 - EXTRA_BITS);
320
26
    ctx->rc.range  = (uint32_t) 1 << EXTRA_BITS;
321
26
}
322
323
/** Perform normalization */
324
5289992
static inline void range_dec_normalize(APEContext *ctx)
325
{
326
8280608
    while (ctx->rc.range <= BOTTOM_VALUE) {
327
2990616
        ctx->rc.buffer <<= 8;
328
2990616
        if(ctx->ptr < ctx->data_end) {
329
2986366
            ctx->rc.buffer += *ctx->ptr;
330
2986366
            ctx->ptr++;
331
        } else {
332
4250
            ctx->error = 1;
333
        }
334
2990616
        ctx->rc.low    = (ctx->rc.low << 8)    | ((ctx->rc.buffer >> 1) & 0xFF);
335
2990616
        ctx->rc.range  <<= 8;
336
    }
337
5289992
}
338
339
/**
340
 * Calculate cumulative frequency for next symbol. Does NO update!
341
 * @param ctx decoder context
342
 * @param tot_f is the total frequency or (code_value)1<<shift
343
 * @return the cumulative frequency
344
 */
345
875520
static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
346
{
347
875520
    range_dec_normalize(ctx);
348
875520
    ctx->rc.help = ctx->rc.range / tot_f;
349
875520
    return ctx->rc.low / ctx->rc.help;
350
}
351
352
/**
353
 * Decode value with given size in bits
354
 * @param ctx decoder context
355
 * @param shift number of bits to decode
356
 */
357
4414464
static inline int range_decode_culshift(APEContext *ctx, int shift)
358
{
359
4414464
    range_dec_normalize(ctx);
360
4414464
    ctx->rc.help = ctx->rc.range >> shift;
361
4414464
    return ctx->rc.low / ctx->rc.help;
362
}
363
364
365
/**
366
 * Update decoding state
367
 * @param ctx decoder context
368
 * @param sy_f the interval length (frequency of the symbol)
369
 * @param lt_f the lower end (frequency sum of < symbols)
370
 */
371
5289984
static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
372
{
373
5289984
    ctx->rc.low  -= ctx->rc.help * lt_f;
374
5289984
    ctx->rc.range = ctx->rc.help * sy_f;
375
5289984
}
376
377
/** Decode n bits (n <= 16) without modelling */
378
1769472
static inline int range_decode_bits(APEContext *ctx, int n)
379
{
380
1769472
    int sym = range_decode_culshift(ctx, n);
381
1769472
    range_decode_update(ctx, 1, sym);
382
1769472
    return sym;
383
}
384
385
386
#define MODEL_ELEMENTS 64
387
388
/**
389
 * Fixed probabilities for symbols in Monkey Audio version 3.97
390
 */
391
static const uint16_t counts_3970[22] = {
392
        0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
393
    62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
394
    65450, 65469, 65480, 65487, 65491, 65493,
395
};
396
397
/**
398
 * Probability ranges for symbols in Monkey Audio version 3.97
399
 */
400
static const uint16_t counts_diff_3970[21] = {
401
    14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
402
    1104, 677, 415, 248, 150, 89, 54, 31,
403
    19, 11, 7, 4, 2,
404
};
405
406
/**
407
 * Fixed probabilities for symbols in Monkey Audio version 3.98
408
 */
409
static const uint16_t counts_3980[22] = {
410
        0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
411
    64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
412
    65485, 65488, 65490, 65491, 65492, 65493,
413
};
414
415
/**
416
 * Probability ranges for symbols in Monkey Audio version 3.98
417
 */
418
static const uint16_t counts_diff_3980[21] = {
419
    19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
420
    261, 119, 65, 31, 19, 10, 6, 3,
421
    3, 2, 1, 1, 1,
422
};
423
424
/**
425
 * Decode symbol
426
 * @param ctx decoder context
427
 * @param counts probability range start position
428
 * @param counts_diff probability range widths
429
 */
430
2644992
static inline int range_get_symbol(APEContext *ctx,
431
                                   const uint16_t counts[],
432
                                   const uint16_t counts_diff[])
433
{
434
    int symbol, cf;
435
436
2644992
    cf = range_decode_culshift(ctx, 16);
437
438
2644992
    if(cf > 65492){
439
183
        symbol= cf - 65535 + 63;
440
183
        range_decode_update(ctx, 1, cf);
441
183
        if(cf > 65535)
442
1
            ctx->error=1;
443
183
        return symbol;
444
    }
445
    /* figure out the symbol inefficiently; a binary search would be much better */
446
8331690
    for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
447
448
2644809
    range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
449
450
2644809
    return symbol;
451
}
452
/** @} */ // group rangecoder
453
454
2644992
static inline void update_rice(APERice *rice, unsigned int x)
455
{
456
2644992
    int lim = rice->k ? (1 << (rice->k + 4)) : 0;
457
2644992
    rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
458
459
2644992
    if (rice->ksum < lim)
460
32925
        rice->k--;
461

2612067
    else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
462
32829
        rice->k++;
463
2644992
}
464
465
460800
static inline int get_rice_ook(GetBitContext *gb, int k)
466
{
467
    unsigned int x;
468
469
460800
    x = get_unary(gb, 1, get_bits_left(gb));
470
471
460800
    if (k)
472
460800
        x = (x << k) | get_bits(gb, k);
473
474
460800
    return x;
475
}
476
477
921600
static inline int ape_decode_value_3860(APEContext *ctx, GetBitContext *gb,
478
                                        APERice *rice)
479
{
480
    unsigned int x, overflow;
481
482
921600
    overflow = get_unary(gb, 1, get_bits_left(gb));
483
484
921600
    if (ctx->fileversion > 3880) {
485
460801
        while (overflow >= 16) {
486
1
            overflow -= 16;
487
1
            rice->k  += 4;
488
        }
489
    }
490
491
921600
    if (!rice->k)
492
        x = overflow;
493
921600
    else if(rice->k <= MIN_CACHE_BITS) {
494
921600
        x = (overflow << rice->k) + get_bits(gb, rice->k);
495
    } else {
496
        av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %"PRIu32"\n", rice->k);
497
        ctx->error = 1;
498
        return AVERROR_INVALIDDATA;
499
    }
500
921600
    rice->ksum += x - (rice->ksum + 8 >> 4);
501

921600
    if (rice->ksum < (rice->k ? 1 << (rice->k + 4) : 0))
502
23449
        rice->k--;
503

898151
    else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
504
23287
        rice->k++;
505
506
    /* Convert to signed */
507
921600
    return ((x >> 1) ^ ((x & 1) - 1)) + 1;
508
}
509
510
1769472
static inline int ape_decode_value_3900(APEContext *ctx, APERice *rice)
511
{
512
    unsigned int x, overflow;
513
    int tmpk;
514
515
1769472
    overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
516
517
1769472
    if (overflow == (MODEL_ELEMENTS - 1)) {
518
        tmpk = range_decode_bits(ctx, 5);
519
        overflow = 0;
520
    } else
521
1769472
        tmpk = (rice->k < 1) ? 0 : rice->k - 1;
522
523

1769472
    if (tmpk <= 16 || ctx->fileversion < 3910) {
524
1769472
        if (tmpk > 23) {
525
            av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
526
            return AVERROR_INVALIDDATA;
527
        }
528
1769472
        x = range_decode_bits(ctx, tmpk);
529
    } else if (tmpk <= 31) {
530
        x = range_decode_bits(ctx, 16);
531
        x |= (range_decode_bits(ctx, tmpk - 16) << 16);
532
    } else {
533
        av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
534
        return AVERROR_INVALIDDATA;
535
    }
536
1769472
    x += overflow << tmpk;
537
538
1769472
    update_rice(rice, x);
539
540
    /* Convert to signed */
541
1769472
    return ((x >> 1) ^ ((x & 1) - 1)) + 1;
542
}
543
544
875520
static inline int ape_decode_value_3990(APEContext *ctx, APERice *rice)
545
{
546
    unsigned int x, overflow;
547
    int base, pivot;
548
549
875520
    pivot = rice->ksum >> 5;
550
875520
    if (pivot == 0)
551
3207
        pivot = 1;
552
553
875520
    overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
554
555
875520
    if (overflow == (MODEL_ELEMENTS - 1)) {
556
        overflow  = (unsigned)range_decode_bits(ctx, 16) << 16;
557
        overflow |= range_decode_bits(ctx, 16);
558
    }
559
560
875520
    if (pivot < 0x10000) {
561
875520
        base = range_decode_culfreq(ctx, pivot);
562
875520
        range_decode_update(ctx, 1, base);
563
    } else {
564
        int base_hi = pivot, base_lo;
565
        int bbits = 0;
566
567
        while (base_hi & ~0xFFFF) {
568
            base_hi >>= 1;
569
            bbits++;
570
        }
571
        base_hi = range_decode_culfreq(ctx, base_hi + 1);
572
        range_decode_update(ctx, 1, base_hi);
573
        base_lo = range_decode_culfreq(ctx, 1 << bbits);
574
        range_decode_update(ctx, 1, base_lo);
575
576
        base = (base_hi << bbits) + base_lo;
577
    }
578
579
875520
    x = base + overflow * pivot;
580
581
875520
    update_rice(rice, x);
582
583
    /* Convert to signed */
584
875520
    return ((x >> 1) ^ ((x & 1) - 1)) + 1;
585
}
586
587
1342
static int get_k(int ksum)
588
{
589
1342
    return av_log2(ksum) + !!ksum;
590
}
591
592
22
static void decode_array_0000(APEContext *ctx, GetBitContext *gb,
593
                              int32_t *out, APERice *rice, int blockstodecode)
594
{
595
    int i;
596
    unsigned ksummax, ksummin;
597
598
22
    rice->ksum = 0;
599
132
    for (i = 0; i < FFMIN(blockstodecode, 5); i++) {
600
110
        out[i] = get_rice_ook(&ctx->gb, 10);
601
110
        rice->ksum += out[i];
602
    }
603
604
22
    if (blockstodecode <= 5)
605
        goto end;
606
607
22
    rice->k = get_k(rice->ksum / 10);
608
22
    if (rice->k >= 24)
609
        return;
610
1320
    for (; i < FFMIN(blockstodecode, 64); i++) {
611
1298
        out[i] = get_rice_ook(&ctx->gb, rice->k);
612
1298
        rice->ksum += out[i];
613
1298
        rice->k = get_k(rice->ksum / ((i + 1) * 2));
614
1298
        if (rice->k >= 24)
615
            return;
616
    }
617
618
22
    if (blockstodecode <= 64)
619
        goto end;
620
621
22
    rice->k = get_k(rice->ksum >> 7);
622
22
    ksummax = 1 << rice->k + 7;
623
22
    ksummin = rice->k ? (1 << rice->k + 6) : 0;
624
459414
    for (; i < blockstodecode; i++) {
625
459392
        if (get_bits_left(&ctx->gb) < 1) {
626
            ctx->error = 1;
627
            return;
628
        }
629
459392
        out[i] = get_rice_ook(&ctx->gb, rice->k);
630
459392
        rice->ksum += out[i] - (unsigned)out[i - 64];
631
463189
        while (rice->ksum < ksummin) {
632
3797
            rice->k--;
633
3797
            ksummin = rice->k ? ksummin >> 1 : 0;
634
3797
            ksummax >>= 1;
635
        }
636
463179
        while (rice->ksum >= ksummax) {
637
3787
            rice->k++;
638
3787
            if (rice->k > 24)
639
                return;
640
3787
            ksummax <<= 1;
641
3787
            ksummin = ksummin ? ksummin << 1 : 128;
642
        }
643
    }
644
645
22
end:
646
460822
    for (i = 0; i < blockstodecode; i++)
647
460800
        out[i] = ((out[i] >> 1) ^ ((out[i] & 1) - 1)) + 1;
648
}
649
650
static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode)
651
{
652
    decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
653
                      blockstodecode);
654
}
655
656
11
static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode)
657
{
658
11
    decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
659
                      blockstodecode);
660
11
    decode_array_0000(ctx, &ctx->gb, ctx->decoded[1], &ctx->riceX,
661
                      blockstodecode);
662
11
}
663
664
static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode)
665
{
666
    int32_t *decoded0 = ctx->decoded[0];
667
668
    while (blockstodecode--)
669
        *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
670
}
671
672
22
static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode)
673
{
674
22
    int32_t *decoded0 = ctx->decoded[0];
675
22
    int32_t *decoded1 = ctx->decoded[1];
676
22
    int blocks = blockstodecode;
677
678
460822
    while (blockstodecode--)
679
460800
        *decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
680
460822
    while (blocks--)
681
460800
        *decoded1++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceX);
682
22
}
683
684
static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode)
685
{
686
    int32_t *decoded0 = ctx->decoded[0];
687
688
    while (blockstodecode--)
689
        *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
690
}
691
692
8
static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode)
693
{
694
8
    int32_t *decoded0 = ctx->decoded[0];
695
8
    int32_t *decoded1 = ctx->decoded[1];
696
8
    int blocks = blockstodecode;
697
698
589832
    while (blockstodecode--)
699
589824
        *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
700
8
    range_dec_normalize(ctx);
701
    // because of some implementation peculiarities we need to backpedal here
702
8
    ctx->ptr -= 1;
703
8
    range_start_decoding(ctx);
704
589832
    while (blocks--)
705
589824
        *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
706
8
}
707
708
64
static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode)
709
{
710
64
    int32_t *decoded0 = ctx->decoded[0];
711
64
    int32_t *decoded1 = ctx->decoded[1];
712
713
294976
    while (blockstodecode--) {
714
294912
        *decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
715
294912
        *decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
716
    }
717
64
}
718
719
static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode)
720
{
721
    int32_t *decoded0 = ctx->decoded[0];
722
723
    while (blockstodecode--)
724
        *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
725
}
726
727
95
static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode)
728
{
729
95
    int32_t *decoded0 = ctx->decoded[0];
730
95
    int32_t *decoded1 = ctx->decoded[1];
731
732
437855
    while (blockstodecode--) {
733
437760
        *decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
734
437760
        *decoded1++ = ape_decode_value_3990(ctx, &ctx->riceX);
735
    }
736
95
}
737
738
51
static int init_entropy_decoder(APEContext *ctx)
739
{
740
    /* Read the CRC */
741
51
    if (ctx->fileversion >= 3900) {
742
18
        if (ctx->data_end - ctx->ptr < 6)
743
            return AVERROR_INVALIDDATA;
744
18
        ctx->CRC = bytestream_get_be32(&ctx->ptr);
745
    } else {
746
33
        ctx->CRC = get_bits_long(&ctx->gb, 32);
747
    }
748
749
    /* Read the frame flags if they exist */
750
51
    ctx->frameflags = 0;
751
51
    ctx->CRC_state = UINT32_MAX;
752

51
    if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
753
        ctx->CRC &= ~0x80000000;
754
755
        if (ctx->data_end - ctx->ptr < 6)
756
            return AVERROR_INVALIDDATA;
757
        ctx->frameflags = bytestream_get_be32(&ctx->ptr);
758
    }
759
760
    /* Initialize the rice structs */
761
51
    ctx->riceX.k = 10;
762
51
    ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
763
51
    ctx->riceY.k = 10;
764
51
    ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
765
766
51
    if (ctx->fileversion >= 3900) {
767
        /* The first 8 bits of input are ignored. */
768
18
        ctx->ptr++;
769
770
18
        range_start_decoding(ctx);
771
    }
772
773
51
    return 0;
774
}
775
776
static const int32_t initial_coeffs_fast_3320[1] = {
777
    375,
778
};
779
780
static const int32_t initial_coeffs_a_3800[3] = {
781
    64, 115, 64,
782
};
783
784
static const int32_t initial_coeffs_b_3800[2] = {
785
    740, 0
786
};
787
788
static const int32_t initial_coeffs_3930[4] = {
789
    360, 317, -109, 98
790
};
791
792
51
static void init_predictor_decoder(APEContext *ctx)
793
{
794
51
    APEPredictor *p = &ctx->predictor;
795
796
    /* Zero the history buffers */
797
51
    memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
798
51
    p->buf = p->historybuffer;
799
800
    /* Initialize and zero the coefficients */
801
51
    if (ctx->fileversion < 3930) {
802
41
        if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
803
            memcpy(p->coeffsA[0], initial_coeffs_fast_3320,
804
                   sizeof(initial_coeffs_fast_3320));
805
            memcpy(p->coeffsA[1], initial_coeffs_fast_3320,
806
                   sizeof(initial_coeffs_fast_3320));
807
        } else {
808
41
            memcpy(p->coeffsA[0], initial_coeffs_a_3800,
809
                   sizeof(initial_coeffs_a_3800));
810
41
            memcpy(p->coeffsA[1], initial_coeffs_a_3800,
811
                   sizeof(initial_coeffs_a_3800));
812
        }
813
    } else {
814
10
        memcpy(p->coeffsA[0], initial_coeffs_3930, sizeof(initial_coeffs_3930));
815
10
        memcpy(p->coeffsA[1], initial_coeffs_3930, sizeof(initial_coeffs_3930));
816
    }
817
51
    memset(p->coeffsB, 0, sizeof(p->coeffsB));
818
51
    if (ctx->fileversion < 3930) {
819
41
        memcpy(p->coeffsB[0], initial_coeffs_b_3800,
820
               sizeof(initial_coeffs_b_3800));
821
41
        memcpy(p->coeffsB[1], initial_coeffs_b_3800,
822
               sizeof(initial_coeffs_b_3800));
823
    }
824
825
51
    p->filterA[0] = p->filterA[1] = 0;
826
51
    p->filterB[0] = p->filterB[1] = 0;
827
51
    p->lastA[0]   = p->lastA[1]   = 0;
828
829
51
    p->sample_pos = 0;
830
51
}
831
832
/** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
833
15295453
static inline int APESIGN(int32_t x) {
834
15295453
    return (x < 0) - (x > 0);
835
}
836
837
static av_always_inline int filter_fast_3320(APEPredictor *p,
838
                                             const int decoded, const int filter,
839
                                             const int delayA)
840
{
841
    int32_t predictionA;
842
843
    p->buf[delayA] = p->lastA[filter];
844
    if (p->sample_pos < 3) {
845
        p->lastA[filter]   = decoded;
846
        p->filterA[filter] = decoded;
847
        return decoded;
848
    }
849
850
    predictionA = p->buf[delayA] * 2U - p->buf[delayA - 1];
851
    p->lastA[filter] = decoded + ((int32_t)(predictionA  * p->coeffsA[filter][0]) >> 9);
852
853
    if ((decoded ^ predictionA) > 0)
854
        p->coeffsA[filter][0]++;
855
    else
856
        p->coeffsA[filter][0]--;
857
858
    p->filterA[filter] += (unsigned)p->lastA[filter];
859
860
    return p->filterA[filter];
861
}
862
863
2562048
static av_always_inline int filter_3800(APEPredictor *p,
864
                                        const unsigned decoded, const int filter,
865
                                        const int delayA,  const int delayB,
866
                                        const int start,   const int shift)
867
{
868
    int32_t predictionA, predictionB, sign;
869
    int32_t d0, d1, d2, d3, d4;
870
871
2562048
    p->buf[delayA] = p->lastA[filter];
872
2562048
    p->buf[delayB] = p->filterB[filter];
873
2562048
    if (p->sample_pos < start) {
874
4856
        predictionA = decoded + p->filterA[filter];
875
4856
        p->lastA[filter]   = decoded;
876
4856
        p->filterB[filter] = decoded;
877
4856
        p->filterA[filter] = predictionA;
878
4856
        return predictionA;
879
    }
880
2557192
    d2 =  p->buf[delayA];
881
2557192
    d1 = (p->buf[delayA] - p->buf[delayA - 1]) * 2U;
882
2557192
    d0 =  p->buf[delayA] + ((p->buf[delayA - 2] - p->buf[delayA - 1]) * 8U);
883
2557192
    d3 =  p->buf[delayB] * 2U - p->buf[delayB - 1];
884
2557192
    d4 =  p->buf[delayB];
885
886
2557192
    predictionA = d0 * p->coeffsA[filter][0] +
887
2557192
                  d1 * p->coeffsA[filter][1] +
888
2557192
                  d2 * p->coeffsA[filter][2];
889
890
2557192
    sign = APESIGN(decoded);
891
2557192
    p->coeffsA[filter][0] += (((d0 >> 30) & 2) - 1) * sign;
892
2557192
    p->coeffsA[filter][1] += (((d1 >> 28) & 8) - 4) * sign;
893
2557192
    p->coeffsA[filter][2] += (((d2 >> 28) & 8) - 4) * sign;
894
895
2557192
    predictionB = d3 * p->coeffsB[filter][0] -
896
2557192
                  d4 * p->coeffsB[filter][1];
897
2557192
    p->lastA[filter] = decoded + (predictionA >> 11);
898
2557192
    sign = APESIGN(p->lastA[filter]);
899
2557192
    p->coeffsB[filter][0] += (((d3 >> 29) & 4) - 2) * sign;
900
2557192
    p->coeffsB[filter][1] -= (((d4 >> 30) & 2) - 1) * sign;
901
902
2557192
    p->filterB[filter] = p->lastA[filter] + (predictionB >> shift);
903
2557192
    p->filterA[filter] = p->filterB[filter] + (unsigned)((int)(p->filterA[filter] * 31U) >> 5);
904
905
2557192
    return p->filterA[filter];
906
}
907
908
20
static void long_filter_high_3800(int32_t *buffer, int order, int shift, int length)
909
{
910
    int i, j;
911
    int32_t dotprod, sign;
912
    int32_t coeffs[256], delay[256];
913
914
20
    if (order >= length)
915
        return;
916
917
20
    memset(coeffs, 0, order * sizeof(*coeffs));
918
4628
    for (i = 0; i < order; i++)
919
4608
        delay[i] = buffer[i];
920
1469972
    for (i = order; i < length; i++) {
921
1469952
        dotprod = 0;
922
1469952
        sign = APESIGN(buffer[i]);
923
340094464
        for (j = 0; j < order; j++) {
924
338624512
            dotprod += delay[j] * (unsigned)coeffs[j];
925
338624512
            coeffs[j] += ((delay[j] >> 31) | 1) * sign;
926
        }
927
1469952
        buffer[i] -= dotprod >> shift;
928
338624512
        for (j = 0; j < order - 1; j++)
929
337154560
            delay[j] = delay[j + 1];
930
1469952
        delay[order - 1] = buffer[i];
931
    }
932
}
933
934
16
static void long_filter_ehigh_3830(int32_t *buffer, int length)
935
{
936
    int i, j;
937
    int32_t dotprod, sign;
938
16
    int32_t delay[8] = { 0 };
939
16
    uint32_t coeffs[8] = { 0 };
940
941
1175568
    for (i = 0; i < length; i++) {
942
1175552
        dotprod = 0;
943
1175552
        sign = APESIGN(buffer[i]);
944
10579968
        for (j = 7; j >= 0; j--) {
945
9404416
            dotprod += delay[j] * coeffs[j];
946
9404416
            coeffs[j] += ((delay[j] >> 31) | 1) * sign;
947
        }
948
9404416
        for (j = 7; j > 0; j--)
949
8228864
            delay[j] = delay[j - 1];
950
1175552
        delay[0] = buffer[i];
951
1175552
        buffer[i] -= dotprod >> 9;
952
    }
953
16
}
954
955
41
static void predictor_decode_stereo_3800(APEContext *ctx, int count)
956
{
957
41
    APEPredictor *p = &ctx->predictor;
958
41
    int32_t *decoded0 = ctx->decoded[0];
959
41
    int32_t *decoded1 = ctx->decoded[1];
960
41
    int start = 4, shift = 10;
961
962
41
    if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
963
        start = 16;
964
        long_filter_high_3800(decoded0, 16, 9, count);
965
        long_filter_high_3800(decoded1, 16, 9, count);
966
41
    } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
967
10
        int order = 128, shift2 = 11;
968
969
10
        if (ctx->fileversion >= 3830) {
970
8
            order <<= 1;
971
8
            shift++;
972
8
            shift2++;
973
8
            long_filter_ehigh_3830(decoded0 + order, count - order);
974
8
            long_filter_ehigh_3830(decoded1 + order, count - order);
975
        }
976
10
        start = order;
977
10
        long_filter_high_3800(decoded0, order, shift2, count);
978
10
        long_filter_high_3800(decoded1, order, shift2, count);
979
    }
980
981
1281065
    while (count--) {
982
1281024
        int X = *decoded0, Y = *decoded1;
983
1281024
        if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
984
            *decoded0 = filter_fast_3320(p, Y, 0, YDELAYA);
985
            decoded0++;
986
            *decoded1 = filter_fast_3320(p, X, 1, XDELAYA);
987
            decoded1++;
988
        } else {
989
1281024
            *decoded0 = filter_3800(p, Y, 0, YDELAYA, YDELAYB,
990
                                    start, shift);
991
1281024
            decoded0++;
992
1281024
            *decoded1 = filter_3800(p, X, 1, XDELAYA, XDELAYB,
993
                                    start, shift);
994
1281024
            decoded1++;
995
        }
996
997
        /* Combined */
998
1281024
        p->buf++;
999
1281024
        p->sample_pos++;
1000
1001
        /* Have we filled the history buffer? */
1002
1281024
        if (p->buf == p->historybuffer + HISTORY_SIZE) {
1003
2502
            memmove(p->historybuffer, p->buf,
1004
                    PREDICTOR_SIZE * sizeof(*p->historybuffer));
1005
2502
            p->buf = p->historybuffer;
1006
        }
1007
    }
1008
41
}
1009
1010
static void predictor_decode_mono_3800(APEContext *ctx, int count)
1011
{
1012
    APEPredictor *p = &ctx->predictor;
1013
    int32_t *decoded0 = ctx->decoded[0];
1014
    int start = 4, shift = 10;
1015
1016
    if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
1017
        start = 16;
1018
        long_filter_high_3800(decoded0, 16, 9, count);
1019
    } else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
1020
        int order = 128, shift2 = 11;
1021
1022
        if (ctx->fileversion >= 3830) {
1023
            order <<= 1;
1024
            shift++;
1025
            shift2++;
1026
            long_filter_ehigh_3830(decoded0 + order, count - order);
1027
        }
1028
        start = order;
1029
        long_filter_high_3800(decoded0, order, shift2, count);
1030
    }
1031
1032
    while (count--) {
1033
        if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
1034
            *decoded0 = filter_fast_3320(p, *decoded0, 0, YDELAYA);
1035
            decoded0++;
1036
        } else {
1037
            *decoded0 = filter_3800(p, *decoded0, 0, YDELAYA, YDELAYB,
1038
                                    start, shift);
1039
            decoded0++;
1040
        }
1041
1042
        /* Combined */
1043
        p->buf++;
1044
        p->sample_pos++;
1045
1046
        /* Have we filled the history buffer? */
1047
        if (p->buf == p->historybuffer + HISTORY_SIZE) {
1048
            memmove(p->historybuffer, p->buf,
1049
                    PREDICTOR_SIZE * sizeof(*p->historybuffer));
1050
            p->buf = p->historybuffer;
1051
        }
1052
    }
1053
}
1054
1055
589824
static av_always_inline int predictor_update_3930(APEPredictor *p,
1056
                                                  const int decoded, const int filter,
1057
                                                  const int delayA)
1058
{
1059
    int32_t predictionA, sign;
1060
    int32_t d0, d1, d2, d3;
1061
1062
589824
    p->buf[delayA]     = p->lastA[filter];
1063
589824
    d0 = p->buf[delayA    ];
1064
589824
    d1 = p->buf[delayA    ] - p->buf[delayA - 1];
1065
589824
    d2 = p->buf[delayA - 1] - p->buf[delayA - 2];
1066
589824
    d3 = p->buf[delayA - 2] - p->buf[delayA - 3];
1067
1068
589824
    predictionA = d0 * p->coeffsA[filter][0] +
1069
589824
                  d1 * p->coeffsA[filter][1] +
1070
589824
                  d2 * p->coeffsA[filter][2] +
1071
589824
                  d3 * p->coeffsA[filter][3];
1072
1073
589824
    p->lastA[filter] = decoded + (predictionA >> 9);
1074
589824
    p->filterA[filter] = p->lastA[filter] + ((int)(p->filterA[filter] * 31U) >> 5);
1075
1076
589824
    sign = APESIGN(decoded);
1077
589824
    p->coeffsA[filter][0] += ((d0 < 0) * 2 - 1) * sign;
1078
589824
    p->coeffsA[filter][1] += ((d1 < 0) * 2 - 1) * sign;
1079
589824
    p->coeffsA[filter][2] += ((d2 < 0) * 2 - 1) * sign;
1080
589824
    p->coeffsA[filter][3] += ((d3 < 0) * 2 - 1) * sign;
1081
1082
589824
    return p->filterA[filter];
1083
}
1084
1085
64
static void predictor_decode_stereo_3930(APEContext *ctx, int count)
1086
{
1087
64
    APEPredictor *p = &ctx->predictor;
1088
64
    int32_t *decoded0 = ctx->decoded[0];
1089
64
    int32_t *decoded1 = ctx->decoded[1];
1090
1091
64
    ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1092
1093
294976
    while (count--) {
1094
        /* Predictor Y */
1095
294912
        int Y = *decoded1, X = *decoded0;
1096
294912
        *decoded0 = predictor_update_3930(p, Y, 0, YDELAYA);
1097
294912
        decoded0++;
1098
294912
        *decoded1 = predictor_update_3930(p, X, 1, XDELAYA);
1099
294912
        decoded1++;
1100
1101
        /* Combined */
1102
294912
        p->buf++;
1103
1104
        /* Have we filled the history buffer? */
1105
294912
        if (p->buf == p->historybuffer + HISTORY_SIZE) {
1106
576
            memmove(p->historybuffer, p->buf,
1107
                    PREDICTOR_SIZE * sizeof(*p->historybuffer));
1108
576
            p->buf = p->historybuffer;
1109
        }
1110
    }
1111
64
}
1112
1113
static void predictor_decode_mono_3930(APEContext *ctx, int count)
1114
{
1115
    APEPredictor *p = &ctx->predictor;
1116
    int32_t *decoded0 = ctx->decoded[0];
1117
1118
    ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1119
1120
    while (count--) {
1121
        *decoded0 = predictor_update_3930(p, *decoded0, 0, YDELAYA);
1122
        decoded0++;
1123
1124
        p->buf++;
1125
1126
        /* Have we filled the history buffer? */
1127
        if (p->buf == p->historybuffer + HISTORY_SIZE) {
1128
            memmove(p->historybuffer, p->buf,
1129
                    PREDICTOR_SIZE * sizeof(*p->historybuffer));
1130
            p->buf = p->historybuffer;
1131
        }
1132
    }
1133
}
1134
1135
866304
static av_always_inline int predictor_update_filter(APEPredictor *p,
1136
                                                    const int decoded, const int filter,
1137
                                                    const int delayA,  const int delayB,
1138
                                                    const int adaptA,  const int adaptB)
1139
{
1140
    int32_t predictionA, predictionB, sign;
1141
1142
866304
    p->buf[delayA]     = p->lastA[filter];
1143
866304
    p->buf[adaptA]     = APESIGN(p->buf[delayA]);
1144
866304
    p->buf[delayA - 1] = p->buf[delayA] - (unsigned)p->buf[delayA - 1];
1145
866304
    p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
1146
1147
866304
    predictionA = p->buf[delayA    ] * p->coeffsA[filter][0] +
1148
866304
                  p->buf[delayA - 1] * p->coeffsA[filter][1] +
1149
866304
                  p->buf[delayA - 2] * p->coeffsA[filter][2] +
1150
866304
                  p->buf[delayA - 3] * p->coeffsA[filter][3];
1151
1152
    /*  Apply a scaled first-order filter compression */
1153
866304
    p->buf[delayB]     = p->filterA[filter ^ 1] - ((int)(p->filterB[filter] * 31U) >> 5);
1154
866304
    p->buf[adaptB]     = APESIGN(p->buf[delayB]);
1155
866304
    p->buf[delayB - 1] = p->buf[delayB] - (unsigned)p->buf[delayB - 1];
1156
866304
    p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
1157
866304
    p->filterB[filter] = p->filterA[filter ^ 1];
1158
1159
866304
    predictionB = p->buf[delayB    ] * p->coeffsB[filter][0] +
1160
866304
                  p->buf[delayB - 1] * p->coeffsB[filter][1] +
1161
866304
                  p->buf[delayB - 2] * p->coeffsB[filter][2] +
1162
866304
                  p->buf[delayB - 3] * p->coeffsB[filter][3] +
1163
866304
                  p->buf[delayB - 4] * p->coeffsB[filter][4];
1164
1165
866304
    p->lastA[filter] = decoded + ((int)((unsigned)predictionA + (predictionB >> 1)) >> 10);
1166
866304
    p->filterA[filter] = p->lastA[filter] + ((int)(p->filterA[filter] * 31U) >> 5);
1167
1168
866304
    sign = APESIGN(decoded);
1169
866304
    p->coeffsA[filter][0] += p->buf[adaptA    ] * sign;
1170
866304
    p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
1171
866304
    p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
1172
866304
    p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
1173
866304
    p->coeffsB[filter][0] += p->buf[adaptB    ] * sign;
1174
866304
    p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
1175
866304
    p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
1176
866304
    p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
1177
866304
    p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
1178
1179
866304
    return p->filterA[filter];
1180
}
1181
1182
94
static void predictor_decode_stereo_3950(APEContext *ctx, int count)
1183
{
1184
94
    APEPredictor *p = &ctx->predictor;
1185
94
    int32_t *decoded0 = ctx->decoded[0];
1186
94
    int32_t *decoded1 = ctx->decoded[1];
1187
1188
94
    ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
1189
1190
433246
    while (count--) {
1191
        /* Predictor Y */
1192
433152
        *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
1193
                                            YADAPTCOEFFSA, YADAPTCOEFFSB);
1194
433152
        decoded0++;
1195
433152
        *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
1196
                                            XADAPTCOEFFSA, XADAPTCOEFFSB);
1197
433152
        decoded1++;
1198
1199
        /* Combined */
1200
433152
        p->buf++;
1201
1202
        /* Have we filled the history buffer? */
1203
433152
        if (p->buf == p->historybuffer + HISTORY_SIZE) {
1204
846
            memmove(p->historybuffer, p->buf,
1205
                    PREDICTOR_SIZE * sizeof(*p->historybuffer));
1206
846
            p->buf = p->historybuffer;
1207
        }
1208
    }
1209
94
}
1210
1211
static void predictor_decode_mono_3950(APEContext *ctx, int count)
1212
{
1213
    APEPredictor *p = &ctx->predictor;
1214
    int32_t *decoded0 = ctx->decoded[0];
1215
    int32_t predictionA, currentA, A, sign;
1216
1217
    ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
1218
1219
    currentA = p->lastA[0];
1220
1221
    while (count--) {
1222
        A = *decoded0;
1223
1224
        p->buf[YDELAYA] = currentA;
1225
        p->buf[YDELAYA - 1] = p->buf[YDELAYA] - (unsigned)p->buf[YDELAYA - 1];
1226
1227
        predictionA = p->buf[YDELAYA    ] * p->coeffsA[0][0] +
1228
                      p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
1229
                      p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
1230
                      p->buf[YDELAYA - 3] * p->coeffsA[0][3];
1231
1232
        currentA = A + (unsigned)(predictionA >> 10);
1233
1234
        p->buf[YADAPTCOEFFSA]     = APESIGN(p->buf[YDELAYA    ]);
1235
        p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
1236
1237
        sign = APESIGN(A);
1238
        p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA    ] * sign;
1239
        p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
1240
        p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
1241
        p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
1242
1243
        p->buf++;
1244
1245
        /* Have we filled the history buffer? */
1246
        if (p->buf == p->historybuffer + HISTORY_SIZE) {
1247
            memmove(p->historybuffer, p->buf,
1248
                    PREDICTOR_SIZE * sizeof(*p->historybuffer));
1249
            p->buf = p->historybuffer;
1250
        }
1251
1252
        p->filterA[0] = currentA + (unsigned)((int)(p->filterA[0] * 31U) >> 5);
1253
        *(decoded0++) = p->filterA[0];
1254
    }
1255
1256
    p->lastA[0] = currentA;
1257
}
1258
1259
126
static void do_init_filter(APEFilter *f, int16_t *buf, int order)
1260
{
1261
126
    f->coeffs = buf;
1262
126
    f->historybuffer = buf + order;
1263
126
    f->delay       = f->historybuffer + order * 2;
1264
126
    f->adaptcoeffs = f->historybuffer + order;
1265
1266
126
    memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
1267
126
    memset(f->coeffs, 0, order * sizeof(*f->coeffs));
1268
126
    f->avg = 0;
1269
126
}
1270
1271
63
static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
1272
{
1273
63
    do_init_filter(&f[0], buf, order);
1274
63
    do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
1275
63
}
1276
1277
380
static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
1278
                            int32_t *data, int count, int order, int fracbits)
1279
{
1280
    int res;
1281
    int absres;
1282
1283
1751420
    while (count--) {
1284
        /* round fixedpoint scalar product */
1285
1751040
        res = ctx->adsp.scalarproduct_and_madd_int16(f->coeffs,
1286
1751040
                                                     f->delay - order,
1287
1751040
                                                     f->adaptcoeffs - order,
1288
                                                     order, APESIGN(*data));
1289
1751040
        res = (int)(res + (1U << (fracbits - 1))) >> fracbits;
1290
1751040
        res += (unsigned)*data;
1291
1751040
        *data++ = res;
1292
1293
        /* Update the output history */
1294
1751040
        *f->delay++ = av_clip_int16(res);
1295
1296
1751040
        if (version < 3980) {
1297
            /* Version ??? to < 3.98 files (untested) */
1298
884736
            f->adaptcoeffs[0]  = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
1299
884736
            f->adaptcoeffs[-4] >>= 1;
1300
884736
            f->adaptcoeffs[-8] >>= 1;
1301
        } else {
1302
            /* Version 3.98 and later files */
1303
1304
            /* Update the adaption coefficients */
1305
866304
            absres = res < 0 ? -(unsigned)res : res;
1306
866304
            if (absres)
1307
863181
                *f->adaptcoeffs = APESIGN(res) *
1308
863181
                                  (8 << ((absres > f->avg * 3) + (absres > f->avg * 4 / 3)));
1309
                /* equivalent to the following code
1310
                    if (absres <= f->avg * 4 / 3)
1311
                        *f->adaptcoeffs = APESIGN(res) * 8;
1312
                    else if (absres <= f->avg * 3)
1313
                        *f->adaptcoeffs = APESIGN(res) * 16;
1314
                    else
1315
                        *f->adaptcoeffs = APESIGN(res) * 32;
1316
                */
1317
            else
1318
3123
                *f->adaptcoeffs = 0;
1319
1320
866304
            f->avg += (int)(absres - (unsigned)f->avg) / 16;
1321
1322
866304
            f->adaptcoeffs[-1] >>= 1;
1323
866304
            f->adaptcoeffs[-2] >>= 1;
1324
866304
            f->adaptcoeffs[-8] >>= 1;
1325
        }
1326
1327
1751040
        f->adaptcoeffs++;
1328
1329
        /* Have we filled the history buffer? */
1330
1751040
        if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
1331
3420
            memmove(f->historybuffer, f->delay - (order * 2),
1332
3420
                    (order * 2) * sizeof(*f->historybuffer));
1333
3420
            f->delay = f->historybuffer + order * 2;
1334
3420
            f->adaptcoeffs = f->historybuffer + order;
1335
        }
1336
    }
1337
380
}
1338
1339
190
static void apply_filter(APEContext *ctx, APEFilter *f,
1340
                         int32_t *data0, int32_t *data1,
1341
                         int count, int order, int fracbits)
1342
{
1343
190
    do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
1344
190
    if (data1)
1345
190
        do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
1346
190
}
1347
1348
158
static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
1349
                              int32_t *decoded1, int count)
1350
{
1351
    int i;
1352
1353
348
    for (i = 0; i < APE_FILTER_LEVELS; i++) {
1354
348
        if (!ape_filter_orders[ctx->fset][i])
1355
158
            break;
1356
190
        apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
1357
190
                     ape_filter_orders[ctx->fset][i],
1358
190
                     ape_filter_fracbits[ctx->fset][i]);
1359
    }
1360
158
}
1361
1362
51
static int init_frame_decoder(APEContext *ctx)
1363
{
1364
    int i, ret;
1365
51
    if ((ret = init_entropy_decoder(ctx)) < 0)
1366
        return ret;
1367
51
    init_predictor_decoder(ctx);
1368
1369
114
    for (i = 0; i < APE_FILTER_LEVELS; i++) {
1370
114
        if (!ape_filter_orders[ctx->fset][i])
1371
51
            break;
1372
63
        init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
1373
63
                    ape_filter_orders[ctx->fset][i]);
1374
    }
1375
51
    return 0;
1376
}
1377
1378
static void ape_unpack_mono(APEContext *ctx, int count)
1379
{
1380
    if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
1381
        /* We are pure silence, so we're done. */
1382
        av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
1383
        return;
1384
    }
1385
1386
    ctx->entropy_decode_mono(ctx, count);
1387
    if (ctx->error)
1388
        return;
1389
1390
    /* Now apply the predictor decoding */
1391
    ctx->predictor_decode_mono(ctx, count);
1392
1393
    /* Pseudo-stereo - just copy left channel to right channel */
1394
    if (ctx->channels == 2) {
1395
        memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
1396
    }
1397
}
1398
1399
200
static void ape_unpack_stereo(APEContext *ctx, int count)
1400
{
1401
    unsigned left, right;
1402
200
    int32_t *decoded0 = ctx->decoded[0];
1403
200
    int32_t *decoded1 = ctx->decoded[1];
1404
1405
200
    if ((ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) == APE_FRAMECODE_STEREO_SILENCE) {
1406
        /* We are pure silence, so we're done. */
1407
        av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
1408
        return;
1409
    }
1410
1411
200
    ctx->entropy_decode_stereo(ctx, count);
1412
200
    if (ctx->error)
1413
1
        return;
1414
1415
    /* Now apply the predictor decoding */
1416
199
    ctx->predictor_decode_stereo(ctx, count);
1417
1418
    /* Decorrelate and scale to output depth */
1419
2009287
    while (count--) {
1420
2009088
        left = *decoded1 - (unsigned)(*decoded0 / 2);
1421
2009088
        right = left + *decoded0;
1422
1423
2009088
        *(decoded0++) = left;
1424
2009088
        *(decoded1++) = right;
1425
    }
1426
}
1427
1428
213
static int ape_decode_frame(AVCodecContext *avctx, void *data,
1429
                            int *got_frame_ptr, AVPacket *avpkt)
1430
{
1431
213
    AVFrame *frame     = data;
1432
213
    const uint8_t *buf = avpkt->data;
1433
213
    APEContext *s = avctx->priv_data;
1434
    uint8_t *sample8;
1435
    int16_t *sample16;
1436
    int32_t *sample24;
1437
    int i, ch, ret;
1438
    int blockstodecode;
1439
    uint64_t decoded_buffer_size;
1440
1441
    /* this should never be negative, but bad things will happen if it is, so
1442
       check it just to make sure. */
1443
213
    av_assert0(s->samples >= 0);
1444
1445
213
    if(!s->samples){
1446
        uint32_t nblocks, offset;
1447
        int buf_size;
1448
1449
64
        if (!avpkt->size) {
1450
13
            *got_frame_ptr = 0;
1451
13
            return 0;
1452
        }
1453
51
        if (avpkt->size < 8) {
1454
            av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1455
            return AVERROR_INVALIDDATA;
1456
        }
1457
51
        buf_size = avpkt->size & ~3;
1458
51
        if (buf_size != avpkt->size) {
1459
            av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
1460
                   "extra bytes at the end will be skipped.\n");
1461
        }
1462
51
        if (s->fileversion < 3950) // previous versions overread two bytes
1463
45
            buf_size += 2;
1464
51
        av_fast_padded_malloc(&s->data, &s->data_size, buf_size);
1465
51
        if (!s->data)
1466
            return AVERROR(ENOMEM);
1467
51
        s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,
1468
                          buf_size >> 2);
1469
51
        memset(s->data + (buf_size & ~3), 0, buf_size & 3);
1470
51
        s->ptr = s->data;
1471
51
        s->data_end = s->data + buf_size;
1472
1473
51
        nblocks = bytestream_get_be32(&s->ptr);
1474
51
        offset  = bytestream_get_be32(&s->ptr);
1475
51
        if (s->fileversion >= 3900) {
1476
18
            if (offset > 3) {
1477
                av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
1478
                av_freep(&s->data);
1479
                s->data_size = 0;
1480
                return AVERROR_INVALIDDATA;
1481
            }
1482
18
            if (s->data_end - s->ptr < offset) {
1483
                av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
1484
                return AVERROR_INVALIDDATA;
1485
            }
1486
18
            s->ptr += offset;
1487
        } else {
1488
33
            if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0)
1489
                return ret;
1490
33
            if (s->fileversion > 3800)
1491
22
                skip_bits_long(&s->gb, offset * 8);
1492
            else
1493
11
                skip_bits_long(&s->gb, offset);
1494
        }
1495
1496

51
        if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) {
1497
            av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n",
1498
                   nblocks);
1499
            return AVERROR_INVALIDDATA;
1500
        }
1501
1502
        /* Initialize the frame decoder */
1503
51
        if (init_frame_decoder(s) < 0) {
1504
            av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
1505
            return AVERROR_INVALIDDATA;
1506
        }
1507
51
        s->samples = nblocks;
1508
    }
1509
1510
200
    if (!s->data) {
1511
        *got_frame_ptr = 0;
1512
        return avpkt->size;
1513
    }
1514
1515
200
    blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
1516
    // for old files coefficients were not interleaved,
1517
    // so we need to decode all of them at once
1518
200
    if (s->fileversion < 3930)
1519
41
        blockstodecode = s->samples;
1520
1521
    /* reallocate decoded sample buffer if needed */
1522
200
    decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer);
1523
200
    av_assert0(decoded_buffer_size <= INT_MAX);
1524
1525
    /* get output buffer */
1526
200
    frame->nb_samples = blockstodecode;
1527
200
    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
1528
        s->samples=0;
1529
        return ret;
1530
    }
1531
1532
200
    av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size);
1533
200
    if (!s->decoded_buffer)
1534
        return AVERROR(ENOMEM);
1535
200
    memset(s->decoded_buffer, 0, decoded_buffer_size);
1536
200
    s->decoded[0] = s->decoded_buffer;
1537
200
    s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
1538
1539
200
    s->error=0;
1540
1541

200
    if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
1542
        ape_unpack_mono(s, blockstodecode);
1543
    else
1544
200
        ape_unpack_stereo(s, blockstodecode);
1545
200
    emms_c();
1546
1547
200
    if (s->error) {
1548
1
        s->samples=0;
1549
1
        av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
1550
1
        return AVERROR_INVALIDDATA;
1551
    }
1552
1553

199
    switch (s->bps) {
1554
    case 8:
1555
        for (ch = 0; ch < s->channels; ch++) {
1556
            sample8 = (uint8_t *)frame->data[ch];
1557
            for (i = 0; i < blockstodecode; i++)
1558
                *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
1559
        }
1560
        break;
1561
199
    case 16:
1562
597
        for (ch = 0; ch < s->channels; ch++) {
1563
398
            sample16 = (int16_t *)frame->data[ch];
1564
4018574
            for (i = 0; i < blockstodecode; i++)
1565
4018176
                *sample16++ = s->decoded[ch][i];
1566
        }
1567
199
        break;
1568
    case 24:
1569
        for (ch = 0; ch < s->channels; ch++) {
1570
            sample24 = (int32_t *)frame->data[ch];
1571
            for (i = 0; i < blockstodecode; i++)
1572
                *sample24++ = s->decoded[ch][i] * 256U;
1573
        }
1574
        break;
1575
    }
1576
1577
199
    s->samples -= blockstodecode;
1578
1579
199
    if (avctx->err_recognition & AV_EF_CRCCHECK &&
1580
        s->fileversion >= 3900 && s->bps < 24) {
1581
        uint32_t crc = s->CRC_state;
1582
        const AVCRC *crc_tab = av_crc_get_table(AV_CRC_32_IEEE_LE);
1583
        for (i = 0; i < blockstodecode; i++) {
1584
            for (ch = 0; ch < s->channels; ch++) {
1585
                uint8_t *smp = frame->data[ch] + (i*(s->bps >> 3));
1586
                crc = av_crc(crc_tab, crc, smp, s->bps >> 3);
1587
            }
1588
        }
1589
1590
        if (!s->samples && (~crc >> 1) ^ s->CRC) {
1591
            av_log(avctx, AV_LOG_ERROR, "CRC mismatch! Previously decoded "
1592
                   "frames may have been affected as well.\n");
1593
            if (avctx->err_recognition & AV_EF_EXPLODE)
1594
                return AVERROR_INVALIDDATA;
1595
        }
1596
1597
        s->CRC_state = crc;
1598
    }
1599
1600
199
    *got_frame_ptr = 1;
1601
1602
199
    return !s->samples ? avpkt->size : 0;
1603
}
1604
1605
static void ape_flush(AVCodecContext *avctx)
1606
{
1607
    APEContext *s = avctx->priv_data;
1608
    s->samples= 0;
1609
}
1610
1611
#define OFFSET(x) offsetof(APEContext, x)
1612
#define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
1613
static const AVOption options[] = {
1614
    { "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" },
1615
    { "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" },
1616
    { NULL},
1617
};
1618
1619
static const AVClass ape_decoder_class = {
1620
    .class_name = "APE decoder",
1621
    .item_name  = av_default_item_name,
1622
    .option     = options,
1623
    .version    = LIBAVUTIL_VERSION_INT,
1624
};
1625
1626
AVCodec ff_ape_decoder = {
1627
    .name           = "ape",
1628
    .long_name      = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
1629
    .type           = AVMEDIA_TYPE_AUDIO,
1630
    .id             = AV_CODEC_ID_APE,
1631
    .priv_data_size = sizeof(APEContext),
1632
    .init           = ape_decode_init,
1633
    .close          = ape_decode_close,
1634
    .decode         = ape_decode_frame,
1635
    .capabilities   = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DELAY |
1636
                      AV_CODEC_CAP_DR1,
1637
    .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP,
1638
    .flush          = ape_flush,
1639
    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
1640
                                                      AV_SAMPLE_FMT_S16P,
1641
                                                      AV_SAMPLE_FMT_S32P,
1642
                                                      AV_SAMPLE_FMT_NONE },
1643
    .priv_class     = &ape_decoder_class,
1644
};