wavpack.c 41.5 KB
Newer Older
1 2
/*
 * WavPack lossless audio decoder
3
 * Copyright (c) 2006,2011 Konstantin Shishkov
4
 *
5
 * This file is part of Libav.
6
 *
7
 * Libav is free software; you can redistribute it and/or
8 9
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * Libav is distributed in the hope that it will be useful,
13 14 15 16 17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with Libav; if not, write to the Free Software
19 20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */
21

22
#define BITSTREAM_READER_LE
23 24

#include "libavutil/audioconvert.h"
25
#include "avcodec.h"
26
#include "get_bits.h"
27
#include "unary.h"
28 29

/**
30
 * @file
31 32 33
 * WavPack lossless audio decoder
 */

34 35 36
#define WV_MONO           0x00000004
#define WV_JOINT_STEREO   0x00000010
#define WV_FALSE_STEREO   0x40000000
37

Kostya Shishkov's avatar
Kostya Shishkov committed
38 39 40 41 42
#define WV_HYBRID_MODE    0x00000008
#define WV_HYBRID_SHAPE   0x00000008
#define WV_HYBRID_BITRATE 0x00000200
#define WV_HYBRID_BALANCE 0x00000400

43 44 45 46 47 48
#define WV_FLT_SHIFT_ONES 0x01
#define WV_FLT_SHIFT_SAME 0x02
#define WV_FLT_SHIFT_SENT 0x04
#define WV_FLT_ZERO_SENT  0x08
#define WV_FLT_ZERO_SIGN  0x10

49
enum WP_ID_Flags {
50 51 52 53 54 55
    WP_IDF_MASK   = 0x1F,
    WP_IDF_IGNORE = 0x20,
    WP_IDF_ODD    = 0x40,
    WP_IDF_LONG   = 0x80
};

56
enum WP_ID {
57 58 59 60 61 62 63 64 65 66 67 68
    WP_ID_DUMMY = 0,
    WP_ID_ENCINFO,
    WP_ID_DECTERMS,
    WP_ID_DECWEIGHTS,
    WP_ID_DECSAMPLES,
    WP_ID_ENTROPY,
    WP_ID_HYBRID,
    WP_ID_SHAPING,
    WP_ID_FLOATINFO,
    WP_ID_INT32INFO,
    WP_ID_DATA,
    WP_ID_CORR,
69
    WP_ID_EXTRABITS,
70 71 72
    WP_ID_CHANINFO
};

73 74 75 76 77 78 79
typedef struct SavedContext {
    int offset;
    int size;
    int bits_used;
    uint32_t crc;
} SavedContext;

80 81 82 83 84 85 86 87 88 89 90
#define MAX_TERMS 16

typedef struct Decorr {
    int delta;
    int value;
    int weightA;
    int weightB;
    int samplesA[8];
    int samplesB[8];
} Decorr;

Kostya Shishkov's avatar
Kostya Shishkov committed
91 92 93 94 95 96
typedef struct WvChannel {
    int median[3];
    int slow_level, error_limit;
    int bitrate_acc, bitrate_delta;
} WvChannel;

97
typedef struct WavpackFrameContext {
98
    AVCodecContext *avctx;
Kostya Shishkov's avatar
Kostya Shishkov committed
99
    int frame_flags;
100
    int stereo, stereo_in;
101 102 103
    int joint;
    uint32_t CRC;
    GetBitContext gb;
104 105 106
    int got_extra_bits;
    uint32_t crc_extra_bits;
    GetBitContext gb_extra_bits;
107 108 109 110 111
    int data_size; // in bits
    int samples;
    int terms;
    Decorr decorr[MAX_TERMS];
    int zero, one, zeroes;
112
    int extra_bits;
113
    int and, or, shift;
114
    int post_shift;
115 116
    int hybrid, hybrid_bitrate;
    int hybrid_maxclip, hybrid_minclip;
117 118 119
    int float_flag;
    int float_shift;
    int float_max_exp;
Kostya Shishkov's avatar
Kostya Shishkov committed
120
    WvChannel ch[2];
121 122
    int pos;
    SavedContext sc, extra_sc;
123 124 125 126 127 128
} WavpackFrameContext;

#define WV_MAX_FRAME_DECODERS 14

typedef struct WavpackContext {
    AVCodecContext *avctx;
Justin Ruggles's avatar
Justin Ruggles committed
129
    AVFrame frame;
130 131 132 133 134 135 136 137 138

    WavpackFrameContext *fdec[WV_MAX_FRAME_DECODERS];
    int fdec_num;

    int multichannel;
    int mkv_mode;
    int block;
    int samples;
    int ch_offset;
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
} WavpackContext;

// exponent table copied from WavPack source
static const uint8_t wp_exp2_table [256] = {
    0x00, 0x01, 0x01, 0x02, 0x03, 0x03, 0x04, 0x05, 0x06, 0x06, 0x07, 0x08, 0x08, 0x09, 0x0a, 0x0b,
    0x0b, 0x0c, 0x0d, 0x0e, 0x0e, 0x0f, 0x10, 0x10, 0x11, 0x12, 0x13, 0x13, 0x14, 0x15, 0x16, 0x16,
    0x17, 0x18, 0x19, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1d, 0x1e, 0x1f, 0x20, 0x20, 0x21, 0x22, 0x23,
    0x24, 0x24, 0x25, 0x26, 0x27, 0x28, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
    0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3a, 0x3b, 0x3c, 0x3d,
    0x3e, 0x3f, 0x40, 0x41, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x48, 0x49, 0x4a, 0x4b,
    0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a,
    0x5b, 0x5c, 0x5d, 0x5e, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
    0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
    0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x87, 0x88, 0x89, 0x8a,
    0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b,
    0x9c, 0x9d, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad,
    0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0,
    0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc8, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf, 0xd0, 0xd2, 0xd3, 0xd4,
    0xd6, 0xd7, 0xd8, 0xd9, 0xdb, 0xdc, 0xdd, 0xde, 0xe0, 0xe1, 0xe2, 0xe4, 0xe5, 0xe6, 0xe8, 0xe9,
    0xea, 0xec, 0xed, 0xee, 0xf0, 0xf1, 0xf2, 0xf4, 0xf5, 0xf6, 0xf8, 0xf9, 0xfa, 0xfc, 0xfd, 0xff
};

Kostya Shishkov's avatar
Kostya Shishkov committed
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
static const uint8_t wp_log2_table [] = {
    0x00, 0x01, 0x03, 0x04, 0x06, 0x07, 0x09, 0x0a, 0x0b, 0x0d, 0x0e, 0x10, 0x11, 0x12, 0x14, 0x15,
    0x16, 0x18, 0x19, 0x1a, 0x1c, 0x1d, 0x1e, 0x20, 0x21, 0x22, 0x24, 0x25, 0x26, 0x28, 0x29, 0x2a,
    0x2c, 0x2d, 0x2e, 0x2f, 0x31, 0x32, 0x33, 0x34, 0x36, 0x37, 0x38, 0x39, 0x3b, 0x3c, 0x3d, 0x3e,
    0x3f, 0x41, 0x42, 0x43, 0x44, 0x45, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4d, 0x4e, 0x4f, 0x50, 0x51,
    0x52, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63,
    0x64, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x74, 0x75,
    0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85,
    0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95,
    0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4,
    0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb2,
    0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc0,
    0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcb, 0xcc, 0xcd, 0xce,
    0xcf, 0xd0, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd8, 0xd9, 0xda, 0xdb,
    0xdc, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe4, 0xe5, 0xe6, 0xe7, 0xe7,
    0xe8, 0xe9, 0xea, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xee, 0xef, 0xf0, 0xf1, 0xf1, 0xf2, 0xf3, 0xf4,
    0xf4, 0xf5, 0xf6, 0xf7, 0xf7, 0xf8, 0xf9, 0xf9, 0xfa, 0xfb, 0xfc, 0xfc, 0xfd, 0xfe, 0xff, 0xff
};

180
static av_always_inline int wp_exp2(int16_t val)
181 182 183
{
    int res, neg = 0;

184
    if (val < 0) {
185 186 187 188 189 190 191 192 193 194
        val = -val;
        neg = 1;
    }

    res = wp_exp2_table[val & 0xFF] | 0x100;
    val >>= 8;
    res = (val > 9) ? (res << (val - 9)) : (res >> (9 - val));
    return neg ? -res : res;
}

Kostya Shishkov's avatar
Kostya Shishkov committed
195 196 197 198
static av_always_inline int wp_log2(int32_t val)
{
    int bits;

199
    if (!val)
Kostya Shishkov's avatar
Kostya Shishkov committed
200
        return 0;
201
    if (val == 1)
Kostya Shishkov's avatar
Kostya Shishkov committed
202 203 204
        return 256;
    val += val >> 9;
    bits = av_log2(val) + 1;
205
    if (bits < 9)
Kostya Shishkov's avatar
Kostya Shishkov committed
206 207 208 209 210 211 212
        return (bits << 8) + wp_log2_table[(val << (9 - bits)) & 0xFF];
    else
        return (bits << 8) + wp_log2_table[(val >> (bits - 9)) & 0xFF];
}

#define LEVEL_DECAY(a)  ((a + 0x80) >> 8)

213
// macros for manipulating median values
Kostya Shishkov's avatar
Kostya Shishkov committed
214
#define GET_MED(n) ((c->median[n] >> 4) + 1)
215 216
#define DEC_MED(n) c->median[n] -= ((c->median[n] + (128 >> n) - 2) / (128 >> n)) * 2
#define INC_MED(n) c->median[n] += ((c->median[n] + (128 >> n)    ) / (128 >> n)) * 5
217 218 219

// macros for applying weight
#define UPDATE_WEIGHT_CLIP(weight, delta, samples, in) \
220 221 222 223 224 225 226 227 228 229 230
    if (samples && in) { \
        if ((samples ^ in) < 0) { \
            weight -= delta; \
            if (weight < -1024) \
                weight = -1024; \
        } else { \
            weight += delta; \
            if (weight > 1024) \
                weight = 1024; \
        } \
    }
231 232


233
static av_always_inline int get_tail(GetBitContext *gb, int k)
234 235 236
{
    int p, e, res;

237 238
    if (k < 1)
        return 0;
239
    p = av_log2(k);
240
    e = (1 << (p + 1)) - k - 1;
Kostya Shishkov's avatar
Kostya Shishkov committed
241
    res = p ? get_bits(gb, p) : 0;
242 243
    if (res >= e)
        res = (res << 1) - e + get_bits1(gb);
244 245 246
    return res;
}

247
static void update_error_limit(WavpackFrameContext *ctx)
Kostya Shishkov's avatar
Kostya Shishkov committed
248 249 250
{
    int i, br[2], sl[2];

251
    for (i = 0; i <= ctx->stereo_in; i++) {
Kostya Shishkov's avatar
Kostya Shishkov committed
252 253 254 255
        ctx->ch[i].bitrate_acc += ctx->ch[i].bitrate_delta;
        br[i] = ctx->ch[i].bitrate_acc >> 16;
        sl[i] = LEVEL_DECAY(ctx->ch[i].slow_level);
    }
256
    if (ctx->stereo_in && ctx->hybrid_bitrate) {
Kostya Shishkov's avatar
Kostya Shishkov committed
257
        int balance = (sl[1] - sl[0] + br[1] + 1) >> 1;
258
        if (balance > br[0]) {
Kostya Shishkov's avatar
Kostya Shishkov committed
259 260
            br[1] = br[0] << 1;
            br[0] = 0;
261
        } else if (-balance > br[0]) {
Kostya Shishkov's avatar
Kostya Shishkov committed
262 263
            br[0] <<= 1;
            br[1] = 0;
264
        } else {
Kostya Shishkov's avatar
Kostya Shishkov committed
265 266 267 268
            br[1] = br[0] + balance;
            br[0] = br[0] - balance;
        }
    }
269 270 271
    for (i = 0; i <= ctx->stereo_in; i++) {
        if (ctx->hybrid_bitrate) {
            if (sl[i] - br[i] > -0x100)
Kostya Shishkov's avatar
Kostya Shishkov committed
272 273 274
                ctx->ch[i].error_limit = wp_exp2(sl[i] - br[i] + 0x100);
            else
                ctx->ch[i].error_limit = 0;
275
        } else {
Kostya Shishkov's avatar
Kostya Shishkov committed
276 277 278 279 280
            ctx->ch[i].error_limit = wp_exp2(br[i]);
        }
    }
}

281 282
static int wv_get_value(WavpackFrameContext *ctx, GetBitContext *gb,
                        int channel, int *last)
283 284 285
{
    int t, t2;
    int sign, base, add, ret;
Kostya Shishkov's avatar
Kostya Shishkov committed
286
    WvChannel *c = &ctx->ch[channel];
287 288 289

    *last = 0;

290 291 292
    if ((ctx->ch[0].median[0] < 2U) && (ctx->ch[1].median[0] < 2U) &&
        !ctx->zero && !ctx->one) {
        if (ctx->zeroes) {
293
            ctx->zeroes--;
294
            if (ctx->zeroes) {
Kostya Shishkov's avatar
Kostya Shishkov committed
295
                c->slow_level -= LEVEL_DECAY(c->slow_level);
296
                return 0;
Kostya Shishkov's avatar
Kostya Shishkov committed
297
            }
298
        } else {
299
            t = get_unary_0_33(gb);
300 301
            if (t >= 2) {
                if (get_bits_left(gb) < t - 1)
302 303
                    goto error;
                t = get_bits(gb, t - 1) | (1 << (t-1));
304 305
            } else {
                if (get_bits_left(gb) < 0)
306 307
                    goto error;
            }
308
            ctx->zeroes = t;
309
            if (ctx->zeroes) {
Kostya Shishkov's avatar
Kostya Shishkov committed
310 311 312
                memset(ctx->ch[0].median, 0, sizeof(ctx->ch[0].median));
                memset(ctx->ch[1].median, 0, sizeof(ctx->ch[1].median));
                c->slow_level -= LEVEL_DECAY(c->slow_level);
313 314 315 316 317
                return 0;
            }
        }
    }

318
    if (ctx->zero) {
319 320
        t = 0;
        ctx->zero = 0;
321
    } else {
322
        t = get_unary_0_33(gb);
323
        if (get_bits_left(gb) < 0)
324
            goto error;
325
        if (t == 16) {
326
            t2 = get_unary_0_33(gb);
327 328
            if (t2 < 2) {
                if (get_bits_left(gb) < 0)
329 330
                    goto error;
                t += t2;
331 332
            } else {
                if (get_bits_left(gb) < t2 - 1)
333 334 335
                    goto error;
                t += get_bits(gb, t2 - 1) | (1 << (t2 - 1));
            }
336 337
        }

338 339 340 341 342
        if (ctx->one) {
            ctx->one = t & 1;
            t = (t >> 1) + 1;
        } else {
            ctx->one = t & 1;
343 344 345 346 347
            t >>= 1;
        }
        ctx->zero = !ctx->one;
    }

348
    if (ctx->hybrid && !channel)
Kostya Shishkov's avatar
Kostya Shishkov committed
349 350
        update_error_limit(ctx);

351
    if (!t) {
352
        base = 0;
353
        add  = GET_MED(0) - 1;
354
        DEC_MED(0);
355
    } else if (t == 1) {
356
        base = GET_MED(0);
357
        add  = GET_MED(1) - 1;
358 359
        INC_MED(0);
        DEC_MED(1);
360
    } else if (t == 2) {
361
        base = GET_MED(0) + GET_MED(1);
362
        add  = GET_MED(2) - 1;
363 364 365
        INC_MED(0);
        INC_MED(1);
        DEC_MED(2);
366
    } else {
367
        base = GET_MED(0) + GET_MED(1) + GET_MED(2) * (t - 2);
368
        add  = GET_MED(2) - 1;
369 370 371 372
        INC_MED(0);
        INC_MED(1);
        INC_MED(2);
    }
373
    if (!c->error_limit) {
Kostya Shishkov's avatar
Kostya Shishkov committed
374
        ret = base + get_tail(gb, add);
375 376
        if (get_bits_left(gb) <= 0)
            goto error;
377 378 379 380
    } else {
        int mid = (base * 2 + add + 1) >> 1;
        while (add > c->error_limit) {
            if (get_bits_left(gb) <= 0)
381
                goto error;
382
            if (get_bits1(gb)) {
Kostya Shishkov's avatar
Kostya Shishkov committed
383 384
                add -= (mid - base);
                base = mid;
385
            } else
Kostya Shishkov's avatar
Kostya Shishkov committed
386
                add = mid - base - 1;
387
            mid = (base * 2 + add + 1) >> 1;
Kostya Shishkov's avatar
Kostya Shishkov committed
388 389 390
        }
        ret = mid;
    }
391
    sign = get_bits1(gb);
392
    if (ctx->hybrid_bitrate)
Kostya Shishkov's avatar
Kostya Shishkov committed
393
        c->slow_level += wp_log2(ret) - LEVEL_DECAY(c->slow_level);
394
    return sign ? ~ret : ret;
395 396 397 398

error:
    *last = 1;
    return 0;
399 400
}

401 402
static inline int wv_get_value_integer(WavpackFrameContext *s, uint32_t *crc,
                                       int S)
403 404 405
{
    int bit;

406
    if (s->extra_bits){
407 408
        S <<= s->extra_bits;

409
        if (s->got_extra_bits && get_bits_left(&s->gb_extra_bits) >= s->extra_bits) {
410
            S |= get_bits(&s->gb_extra_bits, s->extra_bits);
411
            *crc = *crc * 9 + (S & 0xffff) * 3 + ((unsigned)S >> 16);
412 413
        }
    }
414

415
    bit = (S & s->and) | s->or;
416
    bit = ((S + bit) << s->shift) - bit;
417

418
    if (s->hybrid)
419
        bit = av_clip(bit, s->hybrid_minclip, s->hybrid_maxclip);
420

421
    return bit << s->post_shift;
422 423
}

424
static float wv_get_value_float(WavpackFrameContext *s, uint32_t *crc, int S)
425 426 427 428 429 430
{
    union {
        float    f;
        uint32_t u;
    } value;

431
    unsigned int sign;
432 433
    int exp = s->float_max_exp;

434 435
    if (s->got_extra_bits) {
        const int max_bits  = 1 + 23 + 8 + 1;
436
        const int left_bits = get_bits_left(&s->gb_extra_bits);
437

438
        if (left_bits + 8 * FF_INPUT_BUFFER_PADDING_SIZE < max_bits)
439 440 441
            return 0.0;
    }

442
    if (S) {
443 444
        S <<= s->float_shift;
        sign = S < 0;
445
        if (sign)
446
            S = -S;
447 448
        if (S >= 0x1000000) {
            if (s->got_extra_bits && get_bits1(&s->gb_extra_bits))
449
                S = get_bits(&s->gb_extra_bits, 23);
450
            else
451 452
                S = 0;
            exp = 255;
453
        } else if (exp) {
454 455
            int shift = 23 - av_log2(S);
            exp = s->float_max_exp;
456
            if (exp <= shift)
457 458 459
                shift = --exp;
            exp -= shift;

460
            if (shift) {
461
                S <<= shift;
462 463 464
                if ((s->float_flag & WV_FLT_SHIFT_ONES) ||
                    (s->got_extra_bits && (s->float_flag & WV_FLT_SHIFT_SAME) &&
                     get_bits1(&s->gb_extra_bits))) {
465
                    S |= (1 << shift) - 1;
466 467
                } else if (s->got_extra_bits &&
                           (s->float_flag & WV_FLT_SHIFT_SENT)) {
468 469 470
                    S |= get_bits(&s->gb_extra_bits, shift);
                }
            }
471
        } else {
472 473 474
            exp = s->float_max_exp;
        }
        S &= 0x7fffff;
475
    } else {
476 477
        sign = 0;
        exp = 0;
478 479
        if (s->got_extra_bits && (s->float_flag & WV_FLT_ZERO_SENT)) {
            if (get_bits1(&s->gb_extra_bits)) {
480
                S = get_bits(&s->gb_extra_bits, 23);
481
                if (s->float_max_exp >= 25)
482 483
                    exp = get_bits(&s->gb_extra_bits, 8);
                sign = get_bits1(&s->gb_extra_bits);
484 485
            } else {
                if (s->float_flag & WV_FLT_ZERO_SIGN)
486 487 488 489 490 491 492 493 494 495 496
                    sign = get_bits1(&s->gb_extra_bits);
            }
        }
    }

    *crc = *crc * 27 + S * 9 + exp * 3 + sign;

    value.u = (sign << 31) | (exp << 23) | S;
    return value.f;
}

497
static void wv_reset_saved_context(WavpackFrameContext *s)
498 499 500 501 502
{
    s->pos = 0;
    s->sc.crc = s->extra_sc.crc = 0xFFFFFFFF;
}

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
static inline int wv_check_crc(WavpackFrameContext *s, uint32_t crc,
                               uint32_t crc_extra_bits)
{
    if (crc != s->CRC) {
        av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
        return AVERROR_INVALIDDATA;
    }
    if (s->got_extra_bits && crc_extra_bits != s->crc_extra_bits) {
        av_log(s->avctx, AV_LOG_ERROR, "Extra bits CRC error\n");
        return AVERROR_INVALIDDATA;
    }

    return 0;
}

518 519
static inline int wv_unpack_stereo(WavpackFrameContext *s, GetBitContext *gb,
                                   void *dst, const int type)
520 521 522
{
    int i, j, count = 0;
    int last, t;
523
    int A, B, L, L2, R, R2;
524 525 526
    int pos = s->pos;
    uint32_t crc = s->sc.crc;
    uint32_t crc_extra_bits = s->extra_sc.crc;
527 528
    int16_t *dst16 = dst;
    int32_t *dst32 = dst;
529
    float   *dstfl = dst;
530
    const int channel_pad = s->avctx->channels - 2;
531

Justin Ruggles's avatar
Justin Ruggles committed
532
    s->one = s->zero = s->zeroes = 0;
533
    do {
Kostya Shishkov's avatar
Kostya Shishkov committed
534
        L = wv_get_value(s, gb, 0, &last);
535 536
        if (last)
            break;
Kostya Shishkov's avatar
Kostya Shishkov committed
537
        R = wv_get_value(s, gb, 1, &last);
538 539 540
        if (last)
            break;
        for (i = 0; i < s->terms; i++) {
541
            t = s->decorr[i].value;
542 543 544
            if (t > 0) {
                if (t > 8) {
                    if (t & 1) {
545 546
                        A = 2 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
                        B = 2 * s->decorr[i].samplesB[0] - s->decorr[i].samplesB[1];
547
                    } else {
548 549 550 551 552 553
                        A = (3 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1]) >> 1;
                        B = (3 * s->decorr[i].samplesB[0] - s->decorr[i].samplesB[1]) >> 1;
                    }
                    s->decorr[i].samplesA[1] = s->decorr[i].samplesA[0];
                    s->decorr[i].samplesB[1] = s->decorr[i].samplesB[0];
                    j = 0;
554
                } else {
555 556 557 558
                    A = s->decorr[i].samplesA[pos];
                    B = s->decorr[i].samplesB[pos];
                    j = (pos + t) & 7;
                }
559
                if (type != AV_SAMPLE_FMT_S16) {
560 561
                    L2 = L + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
                    R2 = R + ((s->decorr[i].weightB * (int64_t)B + 512) >> 10);
562
                } else {
563 564
                    L2 = L + ((s->decorr[i].weightA * A + 512) >> 10);
                    R2 = R + ((s->decorr[i].weightB * B + 512) >> 10);
565
                }
566 567
                if (A && L) s->decorr[i].weightA -= ((((L ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
                if (B && R) s->decorr[i].weightB -= ((((R ^ B) >> 30) & 2) - 1) * s->decorr[i].delta;
568 569
                s->decorr[i].samplesA[j] = L = L2;
                s->decorr[i].samplesB[j] = R = R2;
570 571
            } else if (t == -1) {
                if (type != AV_SAMPLE_FMT_S16)
572 573 574
                    L2 = L + ((s->decorr[i].weightA * (int64_t)s->decorr[i].samplesA[0] + 512) >> 10);
                else
                    L2 = L + ((s->decorr[i].weightA * s->decorr[i].samplesA[0] + 512) >> 10);
575 576
                UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, s->decorr[i].samplesA[0], L);
                L = L2;
577
                if (type != AV_SAMPLE_FMT_S16)
578 579 580
                    R2 = R + ((s->decorr[i].weightB * (int64_t)L2 + 512) >> 10);
                else
                    R2 = R + ((s->decorr[i].weightB * L2 + 512) >> 10);
581 582 583
                UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, L2, R);
                R = R2;
                s->decorr[i].samplesA[0] = R;
584 585
            } else {
                if (type != AV_SAMPLE_FMT_S16)
586 587 588
                    R2 = R + ((s->decorr[i].weightB * (int64_t)s->decorr[i].samplesB[0] + 512) >> 10);
                else
                    R2 = R + ((s->decorr[i].weightB * s->decorr[i].samplesB[0] + 512) >> 10);
589 590 591
                UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, s->decorr[i].samplesB[0], R);
                R = R2;

592
                if (t == -3) {
593 594 595 596
                    R2 = s->decorr[i].samplesA[0];
                    s->decorr[i].samplesA[0] = R;
                }

597
                if (type != AV_SAMPLE_FMT_S16)
598 599 600
                    L2 = L + ((s->decorr[i].weightA * (int64_t)R2 + 512) >> 10);
                else
                    L2 = L + ((s->decorr[i].weightA * R2 + 512) >> 10);
601 602 603 604 605 606
                UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, R2, L);
                L = L2;
                s->decorr[i].samplesB[0] = L;
            }
        }
        pos = (pos + 1) & 7;
607
        if (s->joint)
608 609
            L += (R -= (L >> 1));
        crc = (crc * 3 + L) * 3 + R;
610

611
        if (type == AV_SAMPLE_FMT_FLT) {
612 613
            *dstfl++ = wv_get_value_float(s, &crc_extra_bits, L);
            *dstfl++ = wv_get_value_float(s, &crc_extra_bits, R);
614
            dstfl += channel_pad;
615
        } else if (type == AV_SAMPLE_FMT_S32) {
616 617
            *dst32++ = wv_get_value_integer(s, &crc_extra_bits, L);
            *dst32++ = wv_get_value_integer(s, &crc_extra_bits, R);
618
            dst32 += channel_pad;
619 620 621
        } else {
            *dst16++ = wv_get_value_integer(s, &crc_extra_bits, L);
            *dst16++ = wv_get_value_integer(s, &crc_extra_bits, R);
622
            dst16 += channel_pad;
623
        }
624
        count++;
Justin Ruggles's avatar
Justin Ruggles committed
625
    } while (!last && count < s->samples);
626

627
    wv_reset_saved_context(s);
628 629 630
    if ((s->avctx->err_recognition & AV_EF_CRCCHECK) &&
        wv_check_crc(s, crc, crc_extra_bits))
        return AVERROR_INVALIDDATA;
Justin Ruggles's avatar
Justin Ruggles committed
631

632 633 634
    return count * 2;
}

635 636
static inline int wv_unpack_mono(WavpackFrameContext *s, GetBitContext *gb,
                                 void *dst, const int type)
637 638 639
{
    int i, j, count = 0;
    int last, t;
640
    int A, S, T;
641 642 643
    int pos = s->pos;
    uint32_t crc = s->sc.crc;
    uint32_t crc_extra_bits = s->extra_sc.crc;
644 645
    int16_t *dst16 = dst;
    int32_t *dst32 = dst;
646
    float   *dstfl = dst;
647
    const int channel_stride = s->avctx->channels;
648

Justin Ruggles's avatar
Justin Ruggles committed
649
    s->one = s->zero = s->zeroes = 0;
650
    do {
651 652
        T = wv_get_value(s, gb, 0, &last);
        S = 0;
653 654 655
        if (last)
            break;
        for (i = 0; i < s->terms; i++) {
656
            t = s->decorr[i].value;
657 658 659
            if (t > 8) {
                if (t & 1)
                    A =  2 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
660 661 662 663
                else
                    A = (3 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1]) >> 1;
                s->decorr[i].samplesA[1] = s->decorr[i].samplesA[0];
                j = 0;
664
            } else {
665 666 667
                A = s->decorr[i].samplesA[pos];
                j = (pos + t) & 7;
            }
668
            if (type != AV_SAMPLE_FMT_S16)
669 670 671
                S = T + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
            else
                S = T + ((s->decorr[i].weightA * A + 512) >> 10);
672 673
            if (A && T)
                s->decorr[i].weightA -= ((((T ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
674 675 676 677
            s->decorr[i].samplesA[j] = T = S;
        }
        pos = (pos + 1) & 7;
        crc = crc * 3 + S;
678

679
        if (type == AV_SAMPLE_FMT_FLT) {
680 681
            *dstfl = wv_get_value_float(s, &crc_extra_bits, S);
            dstfl += channel_stride;
682
        } else if (type == AV_SAMPLE_FMT_S32) {
683 684
            *dst32 = wv_get_value_integer(s, &crc_extra_bits, S);
            dst32 += channel_stride;
685
        } else {
686 687 688
            *dst16 = wv_get_value_integer(s, &crc_extra_bits, S);
            dst16 += channel_stride;
        }
689
        count++;
Justin Ruggles's avatar
Justin Ruggles committed
690
    } while (!last && count < s->samples);
691

692
    wv_reset_saved_context(s);
693 694 695
    if ((s->avctx->err_recognition & AV_EF_CRCCHECK) &&
        wv_check_crc(s, crc, crc_extra_bits))
        return AVERROR_INVALIDDATA;
Justin Ruggles's avatar
Justin Ruggles committed
696

697 698 699
    return count;
}

700 701 702
static av_cold int wv_alloc_frame_context(WavpackContext *c)
{

703
    if (c->fdec_num == WV_MAX_FRAME_DECODERS)
704 705 706
        return -1;

    c->fdec[c->fdec_num] = av_mallocz(sizeof(**c->fdec));
707
    if (!c->fdec[c->fdec_num])
708 709 710 711 712 713 714 715
        return -1;
    c->fdec_num++;
    c->fdec[c->fdec_num - 1]->avctx = c->avctx;
    wv_reset_saved_context(c->fdec[c->fdec_num - 1]);

    return 0;
}

716
static av_cold int wavpack_decode_init(AVCodecContext *avctx)
717 718 719 720
{
    WavpackContext *s = avctx->priv_data;

    s->avctx = avctx;
721
    if (avctx->bits_per_coded_sample <= 16)
722
        avctx->sample_fmt = AV_SAMPLE_FMT_S16;
723
    else
724
        avctx->sample_fmt = AV_SAMPLE_FMT_S32;
725 726 727
    if (avctx->channels <= 2 && !avctx->channel_layout)
        avctx->channel_layout = (avctx->channels == 2) ? AV_CH_LAYOUT_STEREO :
                                                         AV_CH_LAYOUT_MONO;
728

729 730 731 732
    s->multichannel = avctx->channels > 2;
    /* lavf demuxer does not provide extradata, Matroska stores 0x403
       there, use this to detect decoding mode for multichannel */
    s->mkv_mode = 0;
733
    if (s->multichannel && avctx->extradata && avctx->extradata_size == 2) {
734
        int ver = AV_RL16(avctx->extradata);
735
        if (ver >= 0x402 && ver <= 0x410)
736 737 738 739
            s->mkv_mode = 1;
    }

    s->fdec_num = 0;
740

Justin Ruggles's avatar
Justin Ruggles committed
741 742 743
    avcodec_get_frame_defaults(&s->frame);
    avctx->coded_frame = &s->frame;

744 745 746
    return 0;
}

747
static av_cold int wavpack_decode_end(AVCodecContext *avctx)
748 749
{
    WavpackContext *s = avctx->priv_data;
750 751
    int i;

752
    for (i = 0; i < s->fdec_num; i++)
753 754 755 756 757 758 759
        av_freep(&s->fdec[i]);
    s->fdec_num = 0;

    return 0;
}

static int wavpack_decode_block(AVCodecContext *avctx, int block_no,
Justin Ruggles's avatar
Justin Ruggles committed
760
                                void *data, int *got_frame_ptr,
761 762 763 764
                                const uint8_t *buf, int buf_size)
{
    WavpackContext *wc = avctx->priv_data;
    WavpackFrameContext *s;
765
    void *samples = data;
766
    int samplecount;
767
    int got_terms   = 0, got_weights = 0, got_samples = 0,
768
        got_entropy = 0, got_bs      = 0, got_float   = 0, got_hybrid = 0;
769 770
    const uint8_t *orig_buf = buf;
    const uint8_t *buf_end  = buf + buf_size;
771
    int i, j, id, size, ssize, weights, t;
772
    int bpp, chan, chmask, orig_bpp;
773

774
    if (buf_size == 0) {
Justin Ruggles's avatar
Justin Ruggles committed
775
        *got_frame_ptr = 0;
776 777
        return 0;
    }
778

779
    if (block_no >= wc->fdec_num && wv_alloc_frame_context(wc) < 0) {
780 781 782 783 784
        av_log(avctx, AV_LOG_ERROR, "Error creating frame decode context\n");
        return -1;
    }

    s = wc->fdec[block_no];
785
    if (!s) {
786 787 788 789
        av_log(avctx, AV_LOG_ERROR, "Context for block %d is not present\n", block_no);
        return -1;
    }

790 791 792 793 794
    memset(s->decorr, 0, MAX_TERMS * sizeof(Decorr));
    memset(s->ch, 0, sizeof(s->ch));
    s->extra_bits = 0;
    s->and = s->or = s->shift = 0;
    s->got_extra_bits = 0;
795

796
    if (!wc->mkv_mode) {
Kostya's avatar