GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/apedec.c Lines: 570 777 73.4 %
Date: 2020-04-02 05:41:20 Branches: 209 326 64.1 %

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

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

27
    if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE ||
253
27
        !s->compression_level ||
254

27
        (s->fileversion < 3930 && s->compression_level == COMPRESSION_LEVEL_INSANE)) {
255
        av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
256
               s->compression_level);
257
        return AVERROR_INVALIDDATA;
258
    }
259
27
    s->fset = s->compression_level / 1000 - 1;
260
66
    for (i = 0; i < APE_FILTER_LEVELS; i++) {
261
66
        if (!ape_filter_orders[s->fset][i])
262
27
            break;
263

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

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

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

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

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

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

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

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

199
    switch (s->bps) {
1555
    case 8:
1556
        for (ch = 0; ch < s->channels; ch++) {
1557
            sample8 = (uint8_t *)frame->data[ch];
1558
            for (i = 0; i < blockstodecode; i++)
1559
                *sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
1560
        }
1561
        break;
1562
199
    case 16:
1563
597
        for (ch = 0; ch < s->channels; ch++) {
1564
398
            sample16 = (int16_t *)frame->data[ch];
1565
4018574
            for (i = 0; i < blockstodecode; i++)
1566
4018176
                *sample16++ = s->decoded[ch][i];
1567
        }
1568
199
        break;
1569
    case 24:
1570
        for (ch = 0; ch < s->channels; ch++) {
1571
            sample24 = (int32_t *)frame->data[ch];
1572
            for (i = 0; i < blockstodecode; i++)
1573
                *sample24++ = s->decoded[ch][i] * 256;
1574
        }
1575
        break;
1576
    }
1577
1578
199
    s->samples -= blockstodecode;
1579
1580
199
    *got_frame_ptr = 1;
1581
1582
199
    return !s->samples ? avpkt->size : 0;
1583
}
1584
1585
static void ape_flush(AVCodecContext *avctx)
1586
{
1587
    APEContext *s = avctx->priv_data;
1588
    s->samples= 0;
1589
}
1590
1591
#define OFFSET(x) offsetof(APEContext, x)
1592
#define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
1593
static const AVOption options[] = {
1594
    { "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" },
1595
    { "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" },
1596
    { NULL},
1597
};
1598
1599
static const AVClass ape_decoder_class = {
1600
    .class_name = "APE decoder",
1601
    .item_name  = av_default_item_name,
1602
    .option     = options,
1603
    .version    = LIBAVUTIL_VERSION_INT,
1604
};
1605
1606
AVCodec ff_ape_decoder = {
1607
    .name           = "ape",
1608
    .long_name      = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
1609
    .type           = AVMEDIA_TYPE_AUDIO,
1610
    .id             = AV_CODEC_ID_APE,
1611
    .priv_data_size = sizeof(APEContext),
1612
    .init           = ape_decode_init,
1613
    .close          = ape_decode_close,
1614
    .decode         = ape_decode_frame,
1615
    .capabilities   = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DELAY |
1616
                      AV_CODEC_CAP_DR1,
1617
    .flush          = ape_flush,
1618
    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
1619
                                                      AV_SAMPLE_FMT_S16P,
1620
                                                      AV_SAMPLE_FMT_S32P,
1621
                                                      AV_SAMPLE_FMT_NONE },
1622
    .priv_class     = &ape_decoder_class,
1623
};