Statistics
| Branch: | Revision:

ffmpeg / libavcodec / apedec.c @ 36373cde

History | View | Annotate | Download (28.1 KB)

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
#define ALT_BITSTREAM_READER_LE
24
#include "avcodec.h"
25
#include "dsputil.h"
26
#include "get_bits.h"
27
#include "bytestream.h"
28

    
29
/**
30
 * @file libavcodec/apedec.c
31
 * Monkey's Audio lossless audio decoder
32
 */
33

    
34
#define BLOCKS_PER_LOOP     4608
35
#define MAX_CHANNELS        2
36
#define MAX_BYTESPERSAMPLE  3
37

    
38
#define APE_FRAMECODE_MONO_SILENCE    1
39
#define APE_FRAMECODE_STEREO_SILENCE  3
40
#define APE_FRAMECODE_PSEUDO_STEREO   4
41

    
42
#define HISTORY_SIZE 512
43
#define PREDICTOR_ORDER 8
44
/** Total size of all predictor histories */
45
#define PREDICTOR_SIZE 50
46

    
47
#define YDELAYA (18 + PREDICTOR_ORDER*4)
48
#define YDELAYB (18 + PREDICTOR_ORDER*3)
49
#define XDELAYA (18 + PREDICTOR_ORDER*2)
50
#define XDELAYB (18 + PREDICTOR_ORDER)
51

    
52
#define YADAPTCOEFFSA 18
53
#define XADAPTCOEFFSA 14
54
#define YADAPTCOEFFSB 10
55
#define XADAPTCOEFFSB 5
56

    
57
/**
58
 * Possible compression levels
59
 * @{
60
 */
61
enum APECompressionLevel {
62
    COMPRESSION_LEVEL_FAST       = 1000,
63
    COMPRESSION_LEVEL_NORMAL     = 2000,
64
    COMPRESSION_LEVEL_HIGH       = 3000,
65
    COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
66
    COMPRESSION_LEVEL_INSANE     = 5000
67
};
68
/** @} */
69

    
70
#define APE_FILTER_LEVELS 3
71

    
72
/** Filter orders depending on compression level */
73
static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
74
    {  0,   0,    0 },
75
    { 16,   0,    0 },
76
    { 64,   0,    0 },
77
    { 32, 256,    0 },
78
    { 16, 256, 1280 }
79
};
80

    
81
/** Filter fraction bits depending on compression level */
82
static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
83
    {  0,  0,  0 },
84
    { 11,  0,  0 },
85
    { 11,  0,  0 },
86
    { 10, 13,  0 },
87
    { 11, 13, 15 }
88
};
89

    
90

    
91
/** Filters applied to the decoded data */
92
typedef struct APEFilter {
93
    int16_t *coeffs;        ///< actual coefficients used in filtering
94
    int16_t *adaptcoeffs;   ///< adaptive filter coefficients used for correcting of actual filter coefficients
95
    int16_t *historybuffer; ///< filter memory
96
    int16_t *delay;         ///< filtered values
97

    
98
    int avg;
99
} APEFilter;
100

    
101
typedef struct APERice {
102
    uint32_t k;
103
    uint32_t ksum;
104
} APERice;
105

    
106
typedef struct APERangecoder {
107
    uint32_t low;           ///< low end of interval
108
    uint32_t range;         ///< length of interval
109
    uint32_t help;          ///< bytes_to_follow resp. intermediate value
110
    unsigned int buffer;    ///< buffer for input/output
111
} APERangecoder;
112

    
113
/** Filter histories */
114
typedef struct APEPredictor {
115
    int32_t *buf;
116

    
117
    int32_t lastA[2];
118

    
119
    int32_t filterA[2];
120
    int32_t filterB[2];
121

    
122
    int32_t coeffsA[2][4];  ///< adaption coefficients
123
    int32_t coeffsB[2][5];  ///< adaption coefficients
124
    int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
125
} APEPredictor;
126

    
127
/** Decoder context */
128
typedef struct APEContext {
129
    AVCodecContext *avctx;
130
    DSPContext dsp;
131
    int channels;
132
    int samples;                             ///< samples left to decode in current frame
133

    
134
    int fileversion;                         ///< codec version, very important in decoding process
135
    int compression_level;                   ///< compression levels
136
    int fset;                                ///< which filter set to use (calculated from compression level)
137
    int flags;                               ///< global decoder flags
138

    
139
    uint32_t CRC;                            ///< frame CRC
140
    int frameflags;                          ///< frame flags
141
    int currentframeblocks;                  ///< samples (per channel) in current frame
142
    int blocksdecoded;                       ///< count of decoded samples in current frame
143
    APEPredictor predictor;                  ///< predictor used for final reconstruction
144

    
145
    int32_t decoded0[BLOCKS_PER_LOOP];       ///< decoded data for the first channel
146
    int32_t decoded1[BLOCKS_PER_LOOP];       ///< decoded data for the second channel
147

    
148
    int16_t* filterbuf[APE_FILTER_LEVELS];   ///< filter memory
149

    
150
    APERangecoder rc;                        ///< rangecoder used to decode actual values
151
    APERice riceX;                           ///< rice code parameters for the second channel
152
    APERice riceY;                           ///< rice code parameters for the first channel
153
    APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
154

    
155
    uint8_t *data;                           ///< current frame data
156
    uint8_t *data_end;                       ///< frame data end
157
    const uint8_t *ptr;                      ///< current position in frame data
158
    const uint8_t *last_ptr;                 ///< position where last 4608-sample block ended
159

    
160
    int error;
161
} APEContext;
162

    
163
// TODO: dsputilize
164

    
165
static av_cold int ape_decode_init(AVCodecContext * avctx)
166
{
167
    APEContext *s = avctx->priv_data;
168
    int i;
169

    
170
    if (avctx->extradata_size != 6) {
171
        av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
172
        return -1;
173
    }
174
    if (avctx->bits_per_coded_sample != 16) {
175
        av_log(avctx, AV_LOG_ERROR, "Only 16-bit samples are supported\n");
176
        return -1;
177
    }
178
    if (avctx->channels > 2) {
179
        av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
180
        return -1;
181
    }
182
    s->avctx             = avctx;
183
    s->channels          = avctx->channels;
184
    s->fileversion       = AV_RL16(avctx->extradata);
185
    s->compression_level = AV_RL16(avctx->extradata + 2);
186
    s->flags             = AV_RL16(avctx->extradata + 4);
187

    
188
    av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n", s->compression_level, s->flags);
189
    if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE) {
190
        av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n", s->compression_level);
191
        return -1;
192
    }
193
    s->fset = s->compression_level / 1000 - 1;
194
    for (i = 0; i < APE_FILTER_LEVELS; i++) {
195
        if (!ape_filter_orders[s->fset][i])
196
            break;
197
        s->filterbuf[i] = av_malloc((ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4);
198
    }
199

    
200
    dsputil_init(&s->dsp, avctx);
201
    avctx->sample_fmt = SAMPLE_FMT_S16;
202
    avctx->channel_layout = (avctx->channels==2) ? CH_LAYOUT_STEREO : CH_LAYOUT_MONO;
203
    return 0;
204
}
205

    
206
static av_cold int ape_decode_close(AVCodecContext * avctx)
207
{
208
    APEContext *s = avctx->priv_data;
209
    int i;
210

    
211
    for (i = 0; i < APE_FILTER_LEVELS; i++)
212
        av_freep(&s->filterbuf[i]);
213

    
214
    return 0;
215
}
216

    
217
/**
218
 * @defgroup rangecoder APE range decoder
219
 * @{
220
 */
221

    
222
#define CODE_BITS    32
223
#define TOP_VALUE    ((unsigned int)1 << (CODE_BITS-1))
224
#define SHIFT_BITS   (CODE_BITS - 9)
225
#define EXTRA_BITS   ((CODE_BITS-2) % 8 + 1)
226
#define BOTTOM_VALUE (TOP_VALUE >> 8)
227

    
228
/** Start the decoder */
229
static inline void range_start_decoding(APEContext * ctx)
230
{
231
    ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
232
    ctx->rc.low    = ctx->rc.buffer >> (8 - EXTRA_BITS);
233
    ctx->rc.range  = (uint32_t) 1 << EXTRA_BITS;
234
}
235

    
236
/** Perform normalization */
237
static inline void range_dec_normalize(APEContext * ctx)
238
{
239
    while (ctx->rc.range <= BOTTOM_VALUE) {
240
        ctx->rc.buffer <<= 8;
241
        if(ctx->ptr < ctx->data_end)
242
            ctx->rc.buffer += *ctx->ptr;
243
        ctx->ptr++;
244
        ctx->rc.low    = (ctx->rc.low << 8)    | ((ctx->rc.buffer >> 1) & 0xFF);
245
        ctx->rc.range  <<= 8;
246
    }
247
}
248

    
249
/**
250
 * Calculate culmulative frequency for next symbol. Does NO update!
251
 * @param ctx decoder context
252
 * @param tot_f is the total frequency or (code_value)1<<shift
253
 * @return the culmulative frequency
254
 */
255
static inline int range_decode_culfreq(APEContext * ctx, int tot_f)
256
{
257
    range_dec_normalize(ctx);
258
    ctx->rc.help = ctx->rc.range / tot_f;
259
    return ctx->rc.low / ctx->rc.help;
260
}
261

    
262
/**
263
 * Decode value with given size in bits
264
 * @param ctx decoder context
265
 * @param shift number of bits to decode
266
 */
267
static inline int range_decode_culshift(APEContext * ctx, int shift)
268
{
269
    range_dec_normalize(ctx);
270
    ctx->rc.help = ctx->rc.range >> shift;
271
    return ctx->rc.low / ctx->rc.help;
272
}
273

    
274

    
275
/**
276
 * Update decoding state
277
 * @param ctx decoder context
278
 * @param sy_f the interval length (frequency of the symbol)
279
 * @param lt_f the lower end (frequency sum of < symbols)
280
 */
281
static inline void range_decode_update(APEContext * ctx, int sy_f, int lt_f)
282
{
283
    ctx->rc.low  -= ctx->rc.help * lt_f;
284
    ctx->rc.range = ctx->rc.help * sy_f;
285
}
286

    
287
/** Decode n bits (n <= 16) without modelling */
288
static inline int range_decode_bits(APEContext * ctx, int n)
289
{
290
    int sym = range_decode_culshift(ctx, n);
291
    range_decode_update(ctx, 1, sym);
292
    return sym;
293
}
294

    
295

    
296
#define MODEL_ELEMENTS 64
297

    
298
/**
299
 * Fixed probabilities for symbols in Monkey Audio version 3.97
300
 */
301
static const uint16_t counts_3970[22] = {
302
        0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
303
    62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
304
    65450, 65469, 65480, 65487, 65491, 65493,
305
};
306

    
307
/**
308
 * Probability ranges for symbols in Monkey Audio version 3.97
309
 */
310
static const uint16_t counts_diff_3970[21] = {
311
    14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
312
    1104, 677, 415, 248, 150, 89, 54, 31,
313
    19, 11, 7, 4, 2,
314
};
315

    
316
/**
317
 * Fixed probabilities for symbols in Monkey Audio version 3.98
318
 */
319
static const uint16_t counts_3980[22] = {
320
        0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
321
    64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
322
    65485, 65488, 65490, 65491, 65492, 65493,
323
};
324

    
325
/**
326
 * Probability ranges for symbols in Monkey Audio version 3.98
327
 */
328
static const uint16_t counts_diff_3980[21] = {
329
    19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
330
    261, 119, 65, 31, 19, 10, 6, 3,
331
    3, 2, 1, 1, 1,
332
};
333

    
334
/**
335
 * Decode symbol
336
 * @param ctx decoder context
337
 * @param counts probability range start position
338
 * @param counts_diff probability range widths
339
 */
340
static inline int range_get_symbol(APEContext * ctx,
341
                                   const uint16_t counts[],
342
                                   const uint16_t counts_diff[])
343
{
344
    int symbol, cf;
345

    
346
    cf = range_decode_culshift(ctx, 16);
347

    
348
    if(cf > 65492){
349
        symbol= cf - 65535 + 63;
350
        range_decode_update(ctx, 1, cf);
351
        if(cf > 65535)
352
            ctx->error=1;
353
        return symbol;
354
    }
355
    /* figure out the symbol inefficiently; a binary search would be much better */
356
    for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
357

    
358
    range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
359

    
360
    return symbol;
361
}
362
/** @} */ // group rangecoder
363

    
364
static inline void update_rice(APERice *rice, int x)
365
{
366
    int lim = rice->k ? (1 << (rice->k + 4)) : 0;
367
    rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
368

    
369
    if (rice->ksum < lim)
370
        rice->k--;
371
    else if (rice->ksum >= (1 << (rice->k + 5)))
372
        rice->k++;
373
}
374

    
375
static inline int ape_decode_value(APEContext * ctx, APERice *rice)
376
{
377
    int x, overflow;
378

    
379
    if (ctx->fileversion < 3990) {
380
        int tmpk;
381

    
382
        overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
383

    
384
        if (overflow == (MODEL_ELEMENTS - 1)) {
385
            tmpk = range_decode_bits(ctx, 5);
386
            overflow = 0;
387
        } else
388
            tmpk = (rice->k < 1) ? 0 : rice->k - 1;
389

    
390
        if (tmpk <= 16)
391
            x = range_decode_bits(ctx, tmpk);
392
        else {
393
            x = range_decode_bits(ctx, 16);
394
            x |= (range_decode_bits(ctx, tmpk - 16) << 16);
395
        }
396
        x += overflow << tmpk;
397
    } else {
398
        int base, pivot;
399

    
400
        pivot = rice->ksum >> 5;
401
        if (pivot == 0)
402
            pivot = 1;
403

    
404
        overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
405

    
406
        if (overflow == (MODEL_ELEMENTS - 1)) {
407
            overflow  = range_decode_bits(ctx, 16) << 16;
408
            overflow |= range_decode_bits(ctx, 16);
409
        }
410

    
411
        if (pivot < 0x10000) {
412
            base = range_decode_culfreq(ctx, pivot);
413
            range_decode_update(ctx, 1, base);
414
        } else {
415
            int base_hi = pivot, base_lo;
416
            int bbits = 0;
417

    
418
            while (base_hi & ~0xFFFF) {
419
                base_hi >>= 1;
420
                bbits++;
421
            }
422
            base_hi = range_decode_culfreq(ctx, base_hi + 1);
423
            range_decode_update(ctx, 1, base_hi);
424
            base_lo = range_decode_culfreq(ctx, 1 << bbits);
425
            range_decode_update(ctx, 1, base_lo);
426

    
427
            base = (base_hi << bbits) + base_lo;
428
        }
429

    
430
        x = base + overflow * pivot;
431
    }
432

    
433
    update_rice(rice, x);
434

    
435
    /* Convert to signed */
436
    if (x & 1)
437
        return (x >> 1) + 1;
438
    else
439
        return -(x >> 1);
440
}
441

    
442
static void entropy_decode(APEContext * ctx, int blockstodecode, int stereo)
443
{
444
    int32_t *decoded0 = ctx->decoded0;
445
    int32_t *decoded1 = ctx->decoded1;
446

    
447
    ctx->blocksdecoded = blockstodecode;
448

    
449
    if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
450
        /* We are pure silence, just memset the output buffer. */
451
        memset(decoded0, 0, blockstodecode * sizeof(int32_t));
452
        memset(decoded1, 0, blockstodecode * sizeof(int32_t));
453
    } else {
454
        while (blockstodecode--) {
455
            *decoded0++ = ape_decode_value(ctx, &ctx->riceY);
456
            if (stereo)
457
                *decoded1++ = ape_decode_value(ctx, &ctx->riceX);
458
        }
459
    }
460

    
461
    if (ctx->blocksdecoded == ctx->currentframeblocks)
462
        range_dec_normalize(ctx);   /* normalize to use up all bytes */
463
}
464

    
465
static void init_entropy_decoder(APEContext * ctx)
466
{
467
    /* Read the CRC */
468
    ctx->CRC = bytestream_get_be32(&ctx->ptr);
469

    
470
    /* Read the frame flags if they exist */
471
    ctx->frameflags = 0;
472
    if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
473
        ctx->CRC &= ~0x80000000;
474

    
475
        ctx->frameflags = bytestream_get_be32(&ctx->ptr);
476
    }
477

    
478
    /* Keep a count of the blocks decoded in this frame */
479
    ctx->blocksdecoded = 0;
480

    
481
    /* Initialize the rice structs */
482
    ctx->riceX.k = 10;
483
    ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
484
    ctx->riceY.k = 10;
485
    ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
486

    
487
    /* The first 8 bits of input are ignored. */
488
    ctx->ptr++;
489

    
490
    range_start_decoding(ctx);
491
}
492

    
493
static const int32_t initial_coeffs[4] = {
494
    360, 317, -109, 98
495
};
496

    
497
static void init_predictor_decoder(APEContext * ctx)
498
{
499
    APEPredictor *p = &ctx->predictor;
500

    
501
    /* Zero the history buffers */
502
    memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(int32_t));
503
    p->buf = p->historybuffer;
504

    
505
    /* Initialize and zero the coefficients */
506
    memcpy(p->coeffsA[0], initial_coeffs, sizeof(initial_coeffs));
507
    memcpy(p->coeffsA[1], initial_coeffs, sizeof(initial_coeffs));
508
    memset(p->coeffsB, 0, sizeof(p->coeffsB));
509

    
510
    p->filterA[0] = p->filterA[1] = 0;
511
    p->filterB[0] = p->filterB[1] = 0;
512
    p->lastA[0]   = p->lastA[1]   = 0;
513
}
514

    
515
/** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
516
static inline int APESIGN(int32_t x) {
517
    return (x < 0) - (x > 0);
518
}
519

    
520
static av_always_inline int predictor_update_filter(APEPredictor *p, const int decoded, const int filter, const int delayA, const int delayB, const int adaptA, const int adaptB)
521
{
522
    int32_t predictionA, predictionB;
523

    
524
    p->buf[delayA]     = p->lastA[filter];
525
    p->buf[adaptA]     = APESIGN(p->buf[delayA]);
526
    p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
527
    p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
528

    
529
    predictionA = p->buf[delayA    ] * p->coeffsA[filter][0] +
530
                  p->buf[delayA - 1] * p->coeffsA[filter][1] +
531
                  p->buf[delayA - 2] * p->coeffsA[filter][2] +
532
                  p->buf[delayA - 3] * p->coeffsA[filter][3];
533

    
534
    /*  Apply a scaled first-order filter compression */
535
    p->buf[delayB]     = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
536
    p->buf[adaptB]     = APESIGN(p->buf[delayB]);
537
    p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
538
    p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
539
    p->filterB[filter] = p->filterA[filter ^ 1];
540

    
541
    predictionB = p->buf[delayB    ] * p->coeffsB[filter][0] +
542
                  p->buf[delayB - 1] * p->coeffsB[filter][1] +
543
                  p->buf[delayB - 2] * p->coeffsB[filter][2] +
544
                  p->buf[delayB - 3] * p->coeffsB[filter][3] +
545
                  p->buf[delayB - 4] * p->coeffsB[filter][4];
546

    
547
    p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
548
    p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
549

    
550
    if (!decoded) // no need updating filter coefficients
551
        return p->filterA[filter];
552

    
553
    if (decoded > 0) {
554
        p->coeffsA[filter][0] -= p->buf[adaptA    ];
555
        p->coeffsA[filter][1] -= p->buf[adaptA - 1];
556
        p->coeffsA[filter][2] -= p->buf[adaptA - 2];
557
        p->coeffsA[filter][3] -= p->buf[adaptA - 3];
558

    
559
        p->coeffsB[filter][0] -= p->buf[adaptB    ];
560
        p->coeffsB[filter][1] -= p->buf[adaptB - 1];
561
        p->coeffsB[filter][2] -= p->buf[adaptB - 2];
562
        p->coeffsB[filter][3] -= p->buf[adaptB - 3];
563
        p->coeffsB[filter][4] -= p->buf[adaptB - 4];
564
    } else {
565
        p->coeffsA[filter][0] += p->buf[adaptA    ];
566
        p->coeffsA[filter][1] += p->buf[adaptA - 1];
567
        p->coeffsA[filter][2] += p->buf[adaptA - 2];
568
        p->coeffsA[filter][3] += p->buf[adaptA - 3];
569

    
570
        p->coeffsB[filter][0] += p->buf[adaptB    ];
571
        p->coeffsB[filter][1] += p->buf[adaptB - 1];
572
        p->coeffsB[filter][2] += p->buf[adaptB - 2];
573
        p->coeffsB[filter][3] += p->buf[adaptB - 3];
574
        p->coeffsB[filter][4] += p->buf[adaptB - 4];
575
    }
576
    return p->filterA[filter];
577
}
578

    
579
static void predictor_decode_stereo(APEContext * ctx, int count)
580
{
581
    APEPredictor *p = &ctx->predictor;
582
    int32_t *decoded0 = ctx->decoded0;
583
    int32_t *decoded1 = ctx->decoded1;
584

    
585
    while (count--) {
586
        /* Predictor Y */
587
        *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB, YADAPTCOEFFSA, YADAPTCOEFFSB);
588
        decoded0++;
589
        *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB, XADAPTCOEFFSA, XADAPTCOEFFSB);
590
        decoded1++;
591

    
592
        /* Combined */
593
        p->buf++;
594

    
595
        /* Have we filled the history buffer? */
596
        if (p->buf == p->historybuffer + HISTORY_SIZE) {
597
            memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
598
            p->buf = p->historybuffer;
599
        }
600
    }
601
}
602

    
603
static void predictor_decode_mono(APEContext * ctx, int count)
604
{
605
    APEPredictor *p = &ctx->predictor;
606
    int32_t *decoded0 = ctx->decoded0;
607
    int32_t predictionA, currentA, A;
608

    
609
    currentA = p->lastA[0];
610

    
611
    while (count--) {
612
        A = *decoded0;
613

    
614
        p->buf[YDELAYA] = currentA;
615
        p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
616

    
617
        predictionA = p->buf[YDELAYA    ] * p->coeffsA[0][0] +
618
                      p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
619
                      p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
620
                      p->buf[YDELAYA - 3] * p->coeffsA[0][3];
621

    
622
        currentA = A + (predictionA >> 10);
623

    
624
        p->buf[YADAPTCOEFFSA]     = APESIGN(p->buf[YDELAYA    ]);
625
        p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
626

    
627
        if (A > 0) {
628
            p->coeffsA[0][0] -= p->buf[YADAPTCOEFFSA    ];
629
            p->coeffsA[0][1] -= p->buf[YADAPTCOEFFSA - 1];
630
            p->coeffsA[0][2] -= p->buf[YADAPTCOEFFSA - 2];
631
            p->coeffsA[0][3] -= p->buf[YADAPTCOEFFSA - 3];
632
        } else if (A < 0) {
633
            p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA    ];
634
            p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1];
635
            p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2];
636
            p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3];
637
        }
638

    
639
        p->buf++;
640

    
641
        /* Have we filled the history buffer? */
642
        if (p->buf == p->historybuffer + HISTORY_SIZE) {
643
            memmove(p->historybuffer, p->buf, PREDICTOR_SIZE * sizeof(int32_t));
644
            p->buf = p->historybuffer;
645
        }
646

    
647
        p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
648
        *(decoded0++) = p->filterA[0];
649
    }
650

    
651
    p->lastA[0] = currentA;
652
}
653

    
654
static void do_init_filter(APEFilter *f, int16_t * buf, int order)
655
{
656
    f->coeffs = buf;
657
    f->historybuffer = buf + order;
658
    f->delay       = f->historybuffer + order * 2;
659
    f->adaptcoeffs = f->historybuffer + order;
660

    
661
    memset(f->historybuffer, 0, (order * 2) * sizeof(int16_t));
662
    memset(f->coeffs, 0, order * sizeof(int16_t));
663
    f->avg = 0;
664
}
665

    
666
static void init_filter(APEContext * ctx, APEFilter *f, int16_t * buf, int order)
667
{
668
    do_init_filter(&f[0], buf, order);
669
    do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
670
}
671

    
672
static inline void do_apply_filter(APEContext * ctx, int version, APEFilter *f, int32_t *data, int count, int order, int fracbits)
673
{
674
    int res;
675
    int absres;
676

    
677
    while (count--) {
678
        /* round fixedpoint scalar product */
679
        res = (ctx->dsp.scalarproduct_int16(f->delay - order, f->coeffs, order, 0) + (1 << (fracbits - 1))) >> fracbits;
680

    
681
        if (*data < 0)
682
            ctx->dsp.add_int16(f->coeffs, f->adaptcoeffs - order, order);
683
        else if (*data > 0)
684
            ctx->dsp.sub_int16(f->coeffs, f->adaptcoeffs - order, order);
685

    
686
        res += *data;
687

    
688
        *data++ = res;
689

    
690
        /* Update the output history */
691
        *f->delay++ = av_clip_int16(res);
692

    
693
        if (version < 3980) {
694
            /* Version ??? to < 3.98 files (untested) */
695
            f->adaptcoeffs[0]  = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
696
            f->adaptcoeffs[-4] >>= 1;
697
            f->adaptcoeffs[-8] >>= 1;
698
        } else {
699
            /* Version 3.98 and later files */
700

    
701
            /* Update the adaption coefficients */
702
            absres = (res < 0 ? -res : res);
703

    
704
            if (absres > (f->avg * 3))
705
                *f->adaptcoeffs = ((res >> 25) & 64) - 32;
706
            else if (absres > (f->avg * 4) / 3)
707
                *f->adaptcoeffs = ((res >> 26) & 32) - 16;
708
            else if (absres > 0)
709
                *f->adaptcoeffs = ((res >> 27) & 16) - 8;
710
            else
711
                *f->adaptcoeffs = 0;
712

    
713
            f->avg += (absres - f->avg) / 16;
714

    
715
            f->adaptcoeffs[-1] >>= 1;
716
            f->adaptcoeffs[-2] >>= 1;
717
            f->adaptcoeffs[-8] >>= 1;
718
        }
719

    
720
        f->adaptcoeffs++;
721

    
722
        /* Have we filled the history buffer? */
723
        if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
724
            memmove(f->historybuffer, f->delay - (order * 2),
725
                    (order * 2) * sizeof(int16_t));
726
            f->delay = f->historybuffer + order * 2;
727
            f->adaptcoeffs = f->historybuffer + order;
728
        }
729
    }
730
}
731

    
732
static void apply_filter(APEContext * ctx, APEFilter *f,
733
                         int32_t * data0, int32_t * data1,
734
                         int count, int order, int fracbits)
735
{
736
    do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
737
    if (data1)
738
        do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
739
}
740

    
741
static void ape_apply_filters(APEContext * ctx, int32_t * decoded0,
742
                              int32_t * decoded1, int count)
743
{
744
    int i;
745

    
746
    for (i = 0; i < APE_FILTER_LEVELS; i++) {
747
        if (!ape_filter_orders[ctx->fset][i])
748
            break;
749
        apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count, ape_filter_orders[ctx->fset][i], ape_filter_fracbits[ctx->fset][i]);
750
    }
751
}
752

    
753
static void init_frame_decoder(APEContext * ctx)
754
{
755
    int i;
756
    init_entropy_decoder(ctx);
757
    init_predictor_decoder(ctx);
758

    
759
    for (i = 0; i < APE_FILTER_LEVELS; i++) {
760
        if (!ape_filter_orders[ctx->fset][i])
761
            break;
762
        init_filter(ctx, ctx->filters[i], ctx->filterbuf[i], ape_filter_orders[ctx->fset][i]);
763
    }
764
}
765

    
766
static void ape_unpack_mono(APEContext * ctx, int count)
767
{
768
    int32_t left;
769
    int32_t *decoded0 = ctx->decoded0;
770
    int32_t *decoded1 = ctx->decoded1;
771

    
772
    if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
773
        entropy_decode(ctx, count, 0);
774
        /* We are pure silence, so we're done. */
775
        av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
776
        return;
777
    }
778

    
779
    entropy_decode(ctx, count, 0);
780
    ape_apply_filters(ctx, decoded0, NULL, count);
781

    
782
    /* Now apply the predictor decoding */
783
    predictor_decode_mono(ctx, count);
784

    
785
    /* Pseudo-stereo - just copy left channel to right channel */
786
    if (ctx->channels == 2) {
787
        while (count--) {
788
            left = *decoded0;
789
            *(decoded1++) = *(decoded0++) = left;
790
        }
791
    }
792
}
793

    
794
static void ape_unpack_stereo(APEContext * ctx, int count)
795
{
796
    int32_t left, right;
797
    int32_t *decoded0 = ctx->decoded0;
798
    int32_t *decoded1 = ctx->decoded1;
799

    
800
    if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
801
        /* We are pure silence, so we're done. */
802
        av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
803
        return;
804
    }
805

    
806
    entropy_decode(ctx, count, 1);
807
    ape_apply_filters(ctx, decoded0, decoded1, count);
808

    
809
    /* Now apply the predictor decoding */
810
    predictor_decode_stereo(ctx, count);
811

    
812
    /* Decorrelate and scale to output depth */
813
    while (count--) {
814
        left = *decoded1 - (*decoded0 / 2);
815
        right = left + *decoded0;
816

    
817
        *(decoded0++) = left;
818
        *(decoded1++) = right;
819
    }
820
}
821

    
822
static int ape_decode_frame(AVCodecContext * avctx,
823
                            void *data, int *data_size,
824
                            AVPacket *avpkt)
825
{
826
    const uint8_t *buf = avpkt->data;
827
    int buf_size = avpkt->size;
828
    APEContext *s = avctx->priv_data;
829
    int16_t *samples = data;
830
    int nblocks;
831
    int i, n;
832
    int blockstodecode;
833
    int bytes_used;
834

    
835
    if (buf_size == 0 && !s->samples) {
836
        *data_size = 0;
837
        return 0;
838
    }
839

    
840
    /* should not happen but who knows */
841
    if (BLOCKS_PER_LOOP * 2 * avctx->channels > *data_size) {
842
        av_log (avctx, AV_LOG_ERROR, "Packet size is too big to be handled in lavc! (max is %d where you have %d)\n", *data_size, s->samples * 2 * avctx->channels);
843
        return -1;
844
    }
845

    
846
    if(!s->samples){
847
        s->data = av_realloc(s->data, (buf_size + 3) & ~3);
848
        s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
849
        s->ptr = s->last_ptr = s->data;
850
        s->data_end = s->data + buf_size;
851

    
852
        nblocks = s->samples = bytestream_get_be32(&s->ptr);
853
        n =  bytestream_get_be32(&s->ptr);
854
        if(n < 0 || n > 3){
855
            av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
856
            s->data = NULL;
857
            return -1;
858
        }
859
        s->ptr += n;
860

    
861
        s->currentframeblocks = nblocks;
862
        buf += 4;
863
        if (s->samples <= 0) {
864
            *data_size = 0;
865
            return buf_size;
866
        }
867

    
868
        memset(s->decoded0,  0, sizeof(s->decoded0));
869
        memset(s->decoded1,  0, sizeof(s->decoded1));
870

    
871
        /* Initialize the frame decoder */
872
        init_frame_decoder(s);
873
    }
874

    
875
    if (!s->data) {
876
        *data_size = 0;
877
        return buf_size;
878
    }
879

    
880
    nblocks = s->samples;
881
    blockstodecode = FFMIN(BLOCKS_PER_LOOP, nblocks);
882

    
883
    s->error=0;
884

    
885
    if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
886
        ape_unpack_mono(s, blockstodecode);
887
    else
888
        ape_unpack_stereo(s, blockstodecode);
889

    
890
    if(s->error || s->ptr > s->data_end){
891
        s->samples=0;
892
        av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
893
        return -1;
894
    }
895

    
896
    for (i = 0; i < blockstodecode; i++) {
897
        *samples++ = s->decoded0[i];
898
        if(s->channels == 2)
899
            *samples++ = s->decoded1[i];
900
    }
901

    
902
    s->samples -= blockstodecode;
903

    
904
    *data_size = blockstodecode * 2 * s->channels;
905
    bytes_used = s->samples ? s->ptr - s->last_ptr : buf_size;
906
    s->last_ptr = s->ptr;
907
    return bytes_used;
908
}
909

    
910
AVCodec ape_decoder = {
911
    "ape",
912
    CODEC_TYPE_AUDIO,
913
    CODEC_ID_APE,
914
    sizeof(APEContext),
915
    ape_decode_init,
916
    NULL,
917
    ape_decode_close,
918
    ape_decode_frame,
919
    .capabilities = CODEC_CAP_SUBFRAMES,
920
    .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
921
};