wavpack.c 36.4 KB
Newer Older
1 2
/*
 * WavPack lossless audio decoder
3
 * Copyright (c) 2006,2011 Konstantin Shishkov
4
 *
5 6 7
 * This file is part of FFmpeg.
 *
 * FFmpeg 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
 * FFmpeg 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 FFmpeg; 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/channel_layout.h"
25
#include "avcodec.h"
26
#include "get_bits.h"
27
#include "internal.h"
28
#include "thread.h"
29
#include "unary.h"
30
#include "bytestream.h"
Paul B Mahol's avatar
Paul B Mahol committed
31
#include "wavpack.h"
32 33

/**
34
 * @file
35 36 37
 * WavPack lossless audio decoder
 */

38 39 40 41 42 43 44
typedef struct SavedContext {
    int offset;
    int size;
    int bits_used;
    uint32_t crc;
} SavedContext;

45
typedef struct WavpackFrameContext {
46
    AVCodecContext *avctx;
47
    int frame_flags;
48
    int stereo, stereo_in;
49 50 51
    int joint;
    uint32_t CRC;
    GetBitContext gb;
52 53 54
    int got_extra_bits;
    uint32_t crc_extra_bits;
    GetBitContext gb_extra_bits;
55 56 57 58 59
    int data_size; // in bits
    int samples;
    int terms;
    Decorr decorr[MAX_TERMS];
    int zero, one, zeroes;
60
    int extra_bits;
61
    int and, or, shift;
62
    int post_shift;
63 64
    int hybrid, hybrid_bitrate;
    int hybrid_maxclip, hybrid_minclip;
65 66 67
    int float_flag;
    int float_shift;
    int float_max_exp;
68
    WvChannel ch[2];
69 70
    int pos;
    SavedContext sc, extra_sc;
71 72 73 74 75 76 77 78 79 80 81 82 83
} WavpackFrameContext;

#define WV_MAX_FRAME_DECODERS 14

typedef struct WavpackContext {
    AVCodecContext *avctx;

    WavpackFrameContext *fdec[WV_MAX_FRAME_DECODERS];
    int fdec_num;

    int block;
    int samples;
    int ch_offset;
84 85
} WavpackContext;

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

88
static av_always_inline int get_tail(GetBitContext *gb, int k)
89 90 91
{
    int p, e, res;

92 93
    if (k < 1)
        return 0;
94 95
    p   = av_log2(k);
    e   = (1 << (p + 1)) - k - 1;
96
    res = p ? get_bits(gb, p) : 0;
97 98
    if (res >= e)
        res = (res << 1) - e + get_bits1(gb);
99 100 101
    return res;
}

102
static void update_error_limit(WavpackFrameContext *ctx)
103 104 105
{
    int i, br[2], sl[2];

106
    for (i = 0; i <= ctx->stereo_in; i++) {
107
        ctx->ch[i].bitrate_acc += ctx->ch[i].bitrate_delta;
108 109
        br[i]                   = ctx->ch[i].bitrate_acc >> 16;
        sl[i]                   = LEVEL_DECAY(ctx->ch[i].slow_level);
110
    }
111
    if (ctx->stereo_in && ctx->hybrid_bitrate) {
112
        int balance = (sl[1] - sl[0] + br[1] + 1) >> 1;
113
        if (balance > br[0]) {
114 115
            br[1] = br[0] << 1;
            br[0] = 0;
116
        } else if (-balance > br[0]) {
117
            br[0] <<= 1;
118
            br[1]   = 0;
119
        } else {
120 121 122 123
            br[1] = br[0] + balance;
            br[0] = br[0] - balance;
        }
    }
124 125 126
    for (i = 0; i <= ctx->stereo_in; i++) {
        if (ctx->hybrid_bitrate) {
            if (sl[i] - br[i] > -0x100)
127 128 129
                ctx->ch[i].error_limit = wp_exp2(sl[i] - br[i] + 0x100);
            else
                ctx->ch[i].error_limit = 0;
130
        } else {
131 132 133 134 135
            ctx->ch[i].error_limit = wp_exp2(br[i]);
        }
    }
}

136 137
static int wv_get_value(WavpackFrameContext *ctx, GetBitContext *gb,
                        int channel, int *last)
138 139 140
{
    int t, t2;
    int sign, base, add, ret;
141
    WvChannel *c = &ctx->ch[channel];
142 143 144

    *last = 0;

145 146 147
    if ((ctx->ch[0].median[0] < 2U) && (ctx->ch[1].median[0] < 2U) &&
        !ctx->zero && !ctx->one) {
        if (ctx->zeroes) {
148
            ctx->zeroes--;
149
            if (ctx->zeroes) {
150
                c->slow_level -= LEVEL_DECAY(c->slow_level);
151
                return 0;
152
            }
153
        } else {
154
            t = get_unary_0_33(gb);
155 156
            if (t >= 2) {
                if (get_bits_left(gb) < t - 1)
157
                    goto error;
158
                t = get_bits(gb, t - 1) | (1 << (t - 1));
159 160
            } else {
                if (get_bits_left(gb) < 0)
161 162
                    goto error;
            }
163
            ctx->zeroes = t;
164
            if (ctx->zeroes) {
165 166 167
                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);
168 169 170 171 172
                return 0;
            }
        }
    }

173
    if (ctx->zero) {
174
        t         = 0;
175
        ctx->zero = 0;
176
    } else {
177
        t = get_unary_0_33(gb);
178
        if (get_bits_left(gb) < 0)
179
            goto error;
180
        if (t == 16) {
181
            t2 = get_unary_0_33(gb);
182 183
            if (t2 < 2) {
                if (get_bits_left(gb) < 0)
184 185
                    goto error;
                t += t2;
186 187
            } else {
                if (get_bits_left(gb) < t2 - 1)
188 189 190
                    goto error;
                t += get_bits(gb, t2 - 1) | (1 << (t2 - 1));
            }
191 192
        }

193 194
        if (ctx->one) {
            ctx->one = t & 1;
195
            t        = (t >> 1) + 1;
196 197
        } else {
            ctx->one = t & 1;
198
            t      >>= 1;
199 200 201 202
        }
        ctx->zero = !ctx->one;
    }

203
    if (ctx->hybrid && !channel)
204 205
        update_error_limit(ctx);

206
    if (!t) {
207
        base = 0;
208
        add  = GET_MED(0) - 1;
209
        DEC_MED(0);
210
    } else if (t == 1) {
211
        base = GET_MED(0);
212
        add  = GET_MED(1) - 1;
213 214
        INC_MED(0);
        DEC_MED(1);
215
    } else if (t == 2) {
216
        base = GET_MED(0) + GET_MED(1);
217
        add  = GET_MED(2) - 1;
218 219 220
        INC_MED(0);
        INC_MED(1);
        DEC_MED(2);
221
    } else {
222
        base = GET_MED(0) + GET_MED(1) + GET_MED(2) * (t - 2);
223
        add  = GET_MED(2) - 1;
224 225 226 227
        INC_MED(0);
        INC_MED(1);
        INC_MED(2);
    }
228
    if (!c->error_limit) {
229 230 231 232
        if (add >= 0x2000000U) {
            av_log(ctx->avctx, AV_LOG_ERROR, "k %d is too large\n", add);
            goto error;
        }
233
        ret = base + get_tail(gb, add);
234 235
        if (get_bits_left(gb) <= 0)
            goto error;
236 237 238 239
    } else {
        int mid = (base * 2 + add + 1) >> 1;
        while (add > c->error_limit) {
            if (get_bits_left(gb) <= 0)
240
                goto error;
241
            if (get_bits1(gb)) {
242 243
                add -= (mid - base);
                base = mid;
244
            } else
245
                add = mid - base - 1;
246
            mid = (base * 2 + add + 1) >> 1;
247 248 249
        }
        ret = mid;
    }
250
    sign = get_bits1(gb);
251
    if (ctx->hybrid_bitrate)
252
        c->slow_level += wp_log2(ret) - LEVEL_DECAY(c->slow_level);
253
    return sign ? ~ret : ret;
254 255 256 257

error:
    *last = 1;
    return 0;
258 259
}

260 261
static inline int wv_get_value_integer(WavpackFrameContext *s, uint32_t *crc,
                                       int S)
262 263 264
{
    int bit;

265
    if (s->extra_bits) {
266 267
        S <<= s->extra_bits;

268 269 270
        if (s->got_extra_bits &&
            get_bits_left(&s->gb_extra_bits) >= s->extra_bits) {
            S   |= get_bits(&s->gb_extra_bits, s->extra_bits);
271
            *crc = *crc * 9 + (S & 0xffff) * 3 + ((unsigned)S >> 16);
272 273
        }
    }
274

275
    bit = (S & s->and) | s->or;
276
    bit = ((S + bit) << s->shift) - bit;
277

278
    if (s->hybrid)
279
        bit = av_clip(bit, s->hybrid_minclip, s->hybrid_maxclip);
280

281
    return bit << s->post_shift;
282 283
}

284
static float wv_get_value_float(WavpackFrameContext *s, uint32_t *crc, int S)
285 286 287 288 289 290
{
    union {
        float    f;
        uint32_t u;
    } value;

291
    unsigned int sign;
292 293
    int exp = s->float_max_exp;

294 295
    if (s->got_extra_bits) {
        const int max_bits  = 1 + 23 + 8 + 1;
296
        const int left_bits = get_bits_left(&s->gb_extra_bits);
297

298
        if (left_bits + 8 * FF_INPUT_BUFFER_PADDING_SIZE < max_bits)
299 300 301
            return 0.0;
    }

302
    if (S) {
303
        S  <<= s->float_shift;
304
        sign = S < 0;
305
        if (sign)
306
            S = -S;
307 308
        if (S >= 0x1000000) {
            if (s->got_extra_bits && get_bits1(&s->gb_extra_bits))
309
                S = get_bits(&s->gb_extra_bits, 23);
310
            else
311 312
                S = 0;
            exp = 255;
313
        } else if (exp) {
314 315
            int shift = 23 - av_log2(S);
            exp = s->float_max_exp;
316
            if (exp <= shift)
317 318 319
                shift = --exp;
            exp -= shift;

320
            if (shift) {
321
                S <<= shift;
322
                if ((s->float_flag & WV_FLT_SHIFT_ONES) ||
323 324
                    (s->got_extra_bits &&
                     (s->float_flag & WV_FLT_SHIFT_SAME) &&
325
                     get_bits1(&s->gb_extra_bits))) {
326
                    S |= (1 << shift) - 1;
327 328
                } else if (s->got_extra_bits &&
                           (s->float_flag & WV_FLT_SHIFT_SENT)) {
329 330 331
                    S |= get_bits(&s->gb_extra_bits, shift);
                }
            }
332
        } else {
333 334 335
            exp = s->float_max_exp;
        }
        S &= 0x7fffff;
336
    } else {
337
        sign = 0;
338
        exp  = 0;
339 340
        if (s->got_extra_bits && (s->float_flag & WV_FLT_ZERO_SENT)) {
            if (get_bits1(&s->gb_extra_bits)) {
341
                S = get_bits(&s->gb_extra_bits, 23);
342
                if (s->float_max_exp >= 25)
343 344
                    exp = get_bits(&s->gb_extra_bits, 8);
                sign = get_bits1(&s->gb_extra_bits);
345 346
            } else {
                if (s->float_flag & WV_FLT_ZERO_SIGN)
347 348 349 350 351 352 353 354 355 356 357
                    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;
}

358
static void wv_reset_saved_context(WavpackFrameContext *s)
359
{
360
    s->pos    = 0;
361 362 363
    s->sc.crc = s->extra_sc.crc = 0xFFFFFFFF;
}

364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
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;
}

379
static inline int wv_unpack_stereo(WavpackFrameContext *s, GetBitContext *gb,
380
                                   void *dst_l, void *dst_r, const int type)
381 382 383
{
    int i, j, count = 0;
    int last, t;
384
    int A, B, L, L2, R, R2;
385 386
    int pos                 = s->pos;
    uint32_t crc            = s->sc.crc;
387
    uint32_t crc_extra_bits = s->extra_sc.crc;
388 389 390 391 392 393
    int16_t *dst16_l        = dst_l;
    int16_t *dst16_r        = dst_r;
    int32_t *dst32_l        = dst_l;
    int32_t *dst32_r        = dst_r;
    float *dstfl_l          = dst_l;
    float *dstfl_r          = dst_r;
394

395
    s->one = s->zero = s->zeroes = 0;
396
    do {
397
        L = wv_get_value(s, gb, 0, &last);
398 399
        if (last)
            break;
400
        R = wv_get_value(s, gb, 1, &last);
401 402 403
        if (last)
            break;
        for (i = 0; i < s->terms; i++) {
404
            t = s->decorr[i].value;
405 406 407
            if (t > 0) {
                if (t > 8) {
                    if (t & 1) {
408 409
                        A = 2 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
                        B = 2 * s->decorr[i].samplesB[0] - s->decorr[i].samplesB[1];
410
                    } else {
411 412 413 414 415
                        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];
416
                    j                        = 0;
417
                } else {
418 419 420 421
                    A = s->decorr[i].samplesA[pos];
                    B = s->decorr[i].samplesB[pos];
                    j = (pos + t) & 7;
                }
422
                if (type != AV_SAMPLE_FMT_S16P) {
423 424
                    L2 = L + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
                    R2 = R + ((s->decorr[i].weightB * (int64_t)B + 512) >> 10);
425
                } else {
426 427
                    L2 = L + ((s->decorr[i].weightA * A + 512) >> 10);
                    R2 = R + ((s->decorr[i].weightB * B + 512) >> 10);
428
                }
429 430 431 432
                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;
433 434
                s->decorr[i].samplesA[j] = L = L2;
                s->decorr[i].samplesB[j] = R = R2;
435
            } else if (t == -1) {
436
                if (type != AV_SAMPLE_FMT_S16P)
437 438 439
                    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);
440 441
                UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, s->decorr[i].samplesA[0], L);
                L = L2;
442
                if (type != AV_SAMPLE_FMT_S16P)
443 444 445
                    R2 = R + ((s->decorr[i].weightB * (int64_t)L2 + 512) >> 10);
                else
                    R2 = R + ((s->decorr[i].weightB * L2 + 512) >> 10);
446
                UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, L2, R);
447
                R                        = R2;
448
                s->decorr[i].samplesA[0] = R;
449
            } else {
450
                if (type != AV_SAMPLE_FMT_S16P)
451 452 453
                    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);
454 455 456
                UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, s->decorr[i].samplesB[0], R);
                R = R2;

457
                if (t == -3) {
458
                    R2                       = s->decorr[i].samplesA[0];
459 460 461
                    s->decorr[i].samplesA[0] = R;
                }

462
                if (type != AV_SAMPLE_FMT_S16P)
463 464 465
                    L2 = L + ((s->decorr[i].weightA * (int64_t)R2 + 512) >> 10);
                else
                    L2 = L + ((s->decorr[i].weightA * R2 + 512) >> 10);
466
                UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, R2, L);
467
                L                        = L2;
468 469 470 471
                s->decorr[i].samplesB[0] = L;
            }
        }
        pos = (pos + 1) & 7;
472
        if (s->joint)
473 474
            L += (R -= (L >> 1));
        crc = (crc * 3 + L) * 3 + R;
475

476 477 478 479 480 481
        if (type == AV_SAMPLE_FMT_FLTP) {
            *dstfl_l++ = wv_get_value_float(s, &crc_extra_bits, L);
            *dstfl_r++ = wv_get_value_float(s, &crc_extra_bits, R);
        } else if (type == AV_SAMPLE_FMT_S32P) {
            *dst32_l++ = wv_get_value_integer(s, &crc_extra_bits, L);
            *dst32_r++ = wv_get_value_integer(s, &crc_extra_bits, R);
482
        } else {
483 484
            *dst16_l++ = wv_get_value_integer(s, &crc_extra_bits, L);
            *dst16_r++ = wv_get_value_integer(s, &crc_extra_bits, R);
485
        }
486
        count++;
487
    } while (!last && count < s->samples);
488

489
    wv_reset_saved_context(s);
490 491 492

    if (last && count < s->samples) {
        int size = av_get_bytes_per_sample(type);
493 494
        memset((uint8_t*)dst_l + count*size, 0, (s->samples-count)*size);
        memset((uint8_t*)dst_r + count*size, 0, (s->samples-count)*size);
495 496
    }

497 498 499
    if ((s->avctx->err_recognition & AV_EF_CRCCHECK) &&
        wv_check_crc(s, crc, crc_extra_bits))
        return AVERROR_INVALIDDATA;
500

501
    return 0;
502 503
}

504 505
static inline int wv_unpack_mono(WavpackFrameContext *s, GetBitContext *gb,
                                 void *dst, const int type)
506 507 508
{
    int i, j, count = 0;
    int last, t;
509
    int A, S, T;
510 511 512 513 514 515
    int pos                  = s->pos;
    uint32_t crc             = s->sc.crc;
    uint32_t crc_extra_bits  = s->extra_sc.crc;
    int16_t *dst16           = dst;
    int32_t *dst32           = dst;
    float *dstfl             = dst;
516

517
    s->one = s->zero = s->zeroes = 0;
518
    do {
519 520
        T = wv_get_value(s, gb, 0, &last);
        S = 0;
521 522 523
        if (last)
            break;
        for (i = 0; i < s->terms; i++) {
524
            t = s->decorr[i].value;
525 526 527
            if (t > 8) {
                if (t & 1)
                    A =  2 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
528 529 530
                else
                    A = (3 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1]) >> 1;
                s->decorr[i].samplesA[1] = s->decorr[i].samplesA[0];
531
                j                        = 0;
532
            } else {
533 534 535
                A = s->decorr[i].samplesA[pos];
                j = (pos + t) & 7;
            }
536
            if (type != AV_SAMPLE_FMT_S16P)
537 538 539
                S = T + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
            else
                S = T + ((s->decorr[i].weightA * A + 512) >> 10);
540 541
            if (A && T)
                s->decorr[i].weightA -= ((((T ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
542 543 544 545
            s->decorr[i].samplesA[j] = T = S;
        }
        pos = (pos + 1) & 7;
        crc = crc * 3 + S;
546

547 548 549 550
        if (type == AV_SAMPLE_FMT_FLTP) {
            *dstfl++ = wv_get_value_float(s, &crc_extra_bits, S);
        } else if (type == AV_SAMPLE_FMT_S32P) {
            *dst32++ = wv_get_value_integer(s, &crc_extra_bits, S);
551
        } else {
552
            *dst16++ = wv_get_value_integer(s, &crc_extra_bits, S);
553
        }
554
        count++;
555
    } while (!last && count < s->samples);
556

557
    wv_reset_saved_context(s);
558 559 560

    if (last && count < s->samples) {
        int size = av_get_bytes_per_sample(type);
561
        memset((uint8_t*)dst + count*size, 0, (s->samples-count)*size);
562 563
    }

564 565 566 567 568
    if (s->avctx->err_recognition & AV_EF_CRCCHECK) {
        int ret = wv_check_crc(s, crc, crc_extra_bits);
        if (ret < 0 && s->avctx->err_recognition & AV_EF_EXPLODE)
            return ret;
    }
569

570
    return 0;
571 572
}

573 574
static av_cold int wv_alloc_frame_context(WavpackContext *c)
{
575
    if (c->fdec_num == WV_MAX_FRAME_DECODERS)
576 577 578
        return -1;

    c->fdec[c->fdec_num] = av_mallocz(sizeof(**c->fdec));
579
    if (!c->fdec[c->fdec_num])
580 581 582 583 584 585 586 587
        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;
}

588 589 590 591 592 593 594
static int init_thread_copy(AVCodecContext *avctx)
{
    WavpackContext *s = avctx->priv_data;
    s->avctx = avctx;
    return 0;
}

595
static av_cold int wavpack_decode_init(AVCodecContext *avctx)
596 597 598 599
{
    WavpackContext *s = avctx->priv_data;

    s->avctx = avctx;
600

601
    s->fdec_num = 0;
602

603 604 605
    return 0;
}

606
static av_cold int wavpack_decode_end(AVCodecContext *avctx)
607 608
{
    WavpackContext *s = avctx->priv_data;
609 610
    int i;

611
    for (i = 0; i < s->fdec_num; i++)
612 613 614 615 616 617 618
        av_freep(&s->fdec[i]);
    s->fdec_num = 0;

    return 0;
}

static int wavpack_decode_block(AVCodecContext *avctx, int block_no,
619
                                AVFrame *frame, const uint8_t *buf, int buf_size)
620 621
{
    WavpackContext *wc = avctx->priv_data;
622
    ThreadFrame tframe = { .f = frame };
623
    WavpackFrameContext *s;
624
    GetByteContext gb;
625
    void *samples_l, *samples_r;
626
    int ret;
627
    int got_terms   = 0, got_weights = 0, got_samples = 0,
628
        got_entropy = 0, got_bs      = 0, got_float   = 0, got_hybrid = 0;
629
    int i, j, id, size, ssize, weights, t;
630 631
    int bpp, chan = 0, chmask = 0, orig_bpp, sample_rate = 0;
    int multiblock;
632

633
    if (block_no >= wc->fdec_num && wv_alloc_frame_context(wc) < 0) {
634
        av_log(avctx, AV_LOG_ERROR, "Error creating frame decode context\n");
635
        return AVERROR_INVALIDDATA;
636 637 638
    }

    s = wc->fdec[block_no];
639
    if (!s) {
640 641
        av_log(avctx, AV_LOG_ERROR, "Context for block %d is not present\n",
               block_no);
642
        return AVERROR_INVALIDDATA;
643 644
    }

645 646
    memset(s->decorr, 0, MAX_TERMS * sizeof(Decorr));
    memset(s->ch, 0, sizeof(s->ch));
647 648
    s->extra_bits     = 0;
    s->and            = s->or = s->shift = 0;
649
    s->got_extra_bits = 0;
650

651 652
    bytestream2_init(&gb, buf, buf_size);

653 654 655 656 657
    s->samples = bytestream2_get_le32(&gb);
    if (s->samples != wc->samples) {
        av_log(avctx, AV_LOG_ERROR, "Mismatching number of samples in "
               "a sequence: %d and %d\n", wc->samples, s->samples);
        return AVERROR_INVALIDDATA;
658
    }
659
    s->frame_flags = bytestream2_get_le32(&gb);
660 661
    bpp            = av_get_bytes_per_sample(avctx->sample_fmt);
    orig_bpp       = ((s->frame_flags & 0x03) + 1) << 3;
662
    multiblock     = (s->frame_flags & WV_SINGLE_BLOCK) != WV_SINGLE_BLOCK;
663

664 665 666 667 668
    s->stereo         = !(s->frame_flags & WV_MONO);
    s->stereo_in      =  (s->frame_flags & WV_FALSE_STEREO) ? 0 : s->stereo;
    s->joint          =   s->frame_flags & WV_JOINT_STEREO;
    s->hybrid         =   s->frame_flags & WV_HYBRID_MODE;
    s->hybrid_bitrate =   s->frame_flags & WV_HYBRID_BITRATE;
669
    s->post_shift     = bpp * 8 - orig_bpp + ((s->frame_flags >> 13) & 0x1f);
670
    s->hybrid_maxclip =  ((1LL << (orig_bpp - 1)) - 1);
671
    s->hybrid_minclip = ((-1LL << (orig_bpp - 1)));
672 673
    s->CRC            = bytestream2_get_le32(&gb);

674
    // parse metadata blocks
675 676 677
    while (bytestream2_get_bytes_left(&gb)) {
        id   = bytestream2_get_byte(&gb);
        size = bytestream2_get_byte(&gb);
678
        if (id & WP_IDF_LONG) {
679 680
            size |= (bytestream2_get_byte(&gb)) << 8;
            size |= (bytestream2_get_byte(&gb)) << 16;
681 682
        }
        size <<= 1; // size is specified in words
683
        ssize  = size;
684 685 686
        if (id & WP_IDF_ODD)
            size--;
        if (size < 0) {
687 688
            av_log(avctx, AV_LOG_ERROR,
                   "Got incorrect block %02X with size %i\n", id, size);
689 690
            break;
        }
691
        if (bytestream2_get_bytes_left(&gb) < ssize) {
692 693
            av_log(avctx, AV_LOG_ERROR,
                   "Block size %i is out of bounds\n", size);
694 695
            break;
        }
696
        switch (id & WP_IDF_MASK) {
697
        case WP_ID_DECTERMS:
698
            if (size > MAX_TERMS) {
699
                av_log(avctx, AV_LOG_ERROR, "Too many decorrelation terms\n");
700
                s->terms = 0;
701
                bytestream2_skip(&gb, ssize);
702 703
                continue;
            }
704
            s->terms = size;
705
            for (i = 0; i < s->terms; i++) {
706 707 708
                uint8_t val = bytestream2_get_byte(&gb);
                s->decorr[s->terms - i - 1].value = (val & 0x1F) - 5;
                s->decorr[s->terms - i - 1].delta =  val >> 5;
709 710 711 712
            }
            got_terms = 1;
            break;
        case WP_ID_DECWEIGHTS:
713
            if (!got_terms) {
714 715 716
                av_log(avctx, AV_LOG_ERROR, "No decorrelation terms met\n");
                continue;
            }
717
            weights = size >> s->stereo_in;
718
            if (weights > MAX_TERMS || weights > s->terms) {
719
                av_log(avctx, AV_LOG_ERROR, "Too many decorrelation weights\n");
720
                bytestream2_skip(&gb, ssize);
721 722
                continue;
            }
723
            for (i = 0; i < weights; i++) {
724
                t = (int8_t)bytestream2_get_byte(&gb);
725
                s->decorr[s->terms - i - 1].weightA = t << 3;
726 727
                if (s->decorr[s->terms - i - 1].weightA > 0)
                    s->decorr[s->terms - i - 1].weightA +=
728
                        (s->decorr[s->terms - i - 1].weightA + 64) >> 7;
729
                if (s->stereo_in) {
730
                    t = (int8_t)bytestream2_get_byte(&gb);
731
                    s->decorr[s->terms - i - 1].weightB = t << 3;
732 733
                    if (s->decorr[s->terms - i - 1].weightB > 0)
                        s->decorr[s->terms - i - 1].weightB +=
734
                            (s->decorr[s->terms - i - 1].weightB + 64) >> 7;
735 736 737 738 739
                }
            }
            got_weights = 1;
            break;
        case WP_ID_DECSAMPLES:
740
            if (!got_terms) {
741 742 743 744
                av_log(avctx, AV_LOG_ERROR, "No decorrelation terms met\n");
                continue;
            }
            t = 0;
745
            for (i = s->terms - 1; (i >= 0) && (t < size); i--) {
746
                if (s->decorr[i].value > 8) {
747 748 749 750 751
                    s->decorr[i].samplesA[0] =
                        wp_exp2(bytestream2_get_le16(&gb));
                    s->decorr[i].samplesA[1] =
                        wp_exp2(bytestream2_get_le16(&gb));

752
                    if (s->stereo_in) {
753 754 755 756
                        s->decorr[i].samplesB[0] =
                            wp_exp2(bytestream2_get_le16(&gb));
                        s->decorr[i].samplesB[1] =
                            wp_exp2(bytestream2_get_le16(&gb));
757
                        t                       += 4;
758 759
                    }
                    t += 4;
760
                } else if (s->decorr[i].value < 0) {
761 762 763 764
                    s->decorr[i].samplesA[0] =
                        wp_exp2(bytestream2_get_le16(&gb));
                    s->decorr[i].samplesB[0] =
                        wp_exp2(bytestream2_get_le16(&gb));
765
                    t                       += 4;
766 767
                } else {
                    for (j = 0; j < s->decorr[i].value; j++) {
768 769
                        s->decorr[i].samplesA[j] =
                            wp_exp2(bytestream2_get_le16(&gb));
770
                        if (s->stereo_in) {
771 772
                            s->decorr[i].samplesB[j] =
                                wp_exp2(bytestream2_get_le16(&gb));
773
                        }
774
                    }
775
                    t += s->decorr[i].value * 2 * (s->stereo_in + 1);
776 777 778 779 780
                }
            }
            got_samples = 1;
            break;
        case WP_ID_ENTROPY:
781
            if (size != 6 * (s->stereo_in + 1)) {
782
                av_log(avctx, AV_LOG_ERROR,
783
                       "Entropy vars size should be %i, got %i.\n",
784
                       6 * (s->stereo_in + 1), size);
785
                bytestream2_skip(&gb, ssize);
786 787
                continue;
            }
788
            for (j = 0; j <= s->stereo_in; j++)
789
                for (i = 0; i < 3; i++) {
790
                    s->ch[j].median[i] = wp_exp2(bytestream2_get_le16(&gb));
791
                }
792 793
            got_entropy = 1;
            break;
794
        case WP_ID_HYBRID:
795 796
            if (s->hybrid_bitrate) {
                for (i = 0; i <= s->stereo_in; i++) {
797
                    s->ch[i].slow_level = wp_exp2(bytestream2_get_le16(&gb));
798
                    size               -= 2;
799 800
                }
            }
801
            for (i = 0; i < (s->stereo_in + 1); i++) {
802
                s->ch[i].bitrate_acc = bytestream2_get_le16(&gb) << 16;
803
                size                -= 2;
804
            }
805 806
            if (size > 0) {
                for (i = 0; i < (s->stereo_in + 1); i++) {
807 808
                    s->ch[i].bitrate_delta =
                        wp_exp2((int16_t)bytestream2_get_le16(&gb));
809
                }
810 811
            } else {
                for (i = 0; i < (s->stereo_in + 1); i++)
812 813 814 815
                    s->ch[i].bitrate_delta = 0;
            }
            got_hybrid = 1;
            break;
816 817
        case WP_ID_INT32INFO: {
            uint8_t val[4];
818
            if (size != 4) {
819
                av_log(avctx, AV_LOG_ERROR,
820 821 822
                       "Invalid INT32INFO, size = %i\n",
                       size);
                bytestream2_skip(&gb, ssize - 4);
823 824
                continue;
            }
825 826 827 828 829 830
            bytestream2_get_buffer(&gb, val, 4);
            if (val[0]) {
                s->extra_bits = val[0];
            } else if (val[1]) {
                s->shift = val[1];
            } else if (val[2]) {
831
                s->and   = s->or = 1;
832 833
                s->shift = val[2];
            } else if (val[3]) {
834
                s->and   = 1;
835
                s->shift = val[3];
836
            }
837
            /* original WavPack decoder forces 32-bit lossy sound to be treated
838
             * as 24-bit one in order to have proper clipping */
839
            if (s->hybrid && bpp == 4 && s->post_shift < 8 && s->shift > 8) {
840 841
                s->post_shift      += 8;
                s->shift           -= 8;
842 843 844
                s->hybrid_maxclip >>= 8;
                s->hybrid_minclip >>= 8;
            }
845
            break;
846
        }
847
        case WP_ID_FLOATINFO:
848
            if (size != 4) {
849 850
                av_log(avctx, AV_LOG_ERROR,
                       "Invalid FLOATINFO, size = %i\n", size);
851
                bytestream2_skip(&gb, ssize);
852 853
                continue;
            }
854 855 856
            s->float_flag    = bytestream2_get_byte(&gb);
            s->float_shift   = bytestream2_get_byte(&gb);
            s->float_max_exp = bytestream2_get_byte(&gb);
857
            got_float        = 1;
858
            bytestream2_skip(&gb, 1);
859
            break;
860
        case WP_ID_DATA:
861
            s->sc.offset = bytestream2_tell(&gb);
862
            s->sc.size   = size * 8;
863 864
            if ((ret = init_get_bits8(&s->gb, gb.buffer, size)) < 0)
                return ret;
865
            s->data_size = size * 8;
866
            bytestream2_skip(&gb, size);
867
            got_bs       = 1;
868
            break;
869
        case WP_ID_EXTRABITS:
870 871 872
            if (size <= 4) {
                av_log(avctx, AV_LOG_ERROR, "Invalid EXTRABITS, size = %i\n",
                       size);
873
                bytestream2_skip(&gb, size);
874 875
                continue;
            }
876
            s->extra_sc.offset = bytestream2_tell(&gb);
877
            s->extra_sc.size   = size * 8;
878 879
            if ((ret = init_get_bits8(&s->gb_extra_bits, gb.buffer, size)) < 0)
                return ret;
880
            s->crc_extra_bits  = get_bits_long(&s->gb_extra_bits, 32);
881
            bytestream2_skip(&gb, size);
882
            s->got_extra_bits  = 1;
883
            break;
884
        case WP_ID_CHANINFO:
885
            if (size <= 1) {
886 887
                av_log(avctx, AV_LOG_ERROR,
                       "Insufficient channel information\n");
888
                return AVERROR_INVALIDDATA;
889
            }
890
            chan = bytestream2_get_byte(&gb);
891
            switch (size - 2) {
892
            case 0:
893
                chmask = bytestream2_get_byte(&gb);
894 895
                break;
            case 1:
896
                chmask = bytestream2_get_le16(&gb);
897 898
                break;
            case 2:
899
                chmask = bytestream2_get_le24(&gb);
900 901
                break;
            case 3:
902
                chmask = bytestream2_get_le32(&gb);
903
                break;
904
            case 5:
905 906 907
                bytestream2_skip(&gb, 1);
                chan  |= (bytestream2_get_byte(&gb) & 0xF) << 8;
                chmask = bytestream2_get_le16(&gb);
908 909
                break;
            default:
910 911 912
                av_log(avctx, AV_LOG_ERROR, "Invalid channel info size %d\n",
                       size);
                chan   = avctx->channels;
913 914 915
                chmask = avctx->channel_layout;
            }
            break;
916 917 918 919 920 921 922
        case WP_ID_SAMPLE_RATE:
            if (size != 3) {
                av_log(avctx, AV_LOG_ERROR, "Invalid custom sample rate.\n");
                return AVERROR_INVALIDDATA;
            }
            sample_rate = bytestream2_get_le24(&gb);
            break;
923
        default:
924
            bytestream2_skip(&gb, size);
925
        }
926
        if (id & WP_IDF_ODD)
927
            bytestream2_skip(&gb, 1);
928
    }
929

930 931
    if (!got_terms) {
        av_log(avctx, AV_LOG_ERROR, "No block with decorrelation terms\n");
932
        return AVERROR_INVALIDDATA;
933 934 935
    }
    if (!got_weights) {
        av_log(avctx, AV_LOG_ERROR, "No block with decorrelation weights\n");
936
        return AVERROR_INVALIDDATA;
937 938 939
    }
    if (!got_samples) {
        av_log(avctx, AV_LOG_ERROR, "No block with decorrelation samples\n");
940
        return AVERROR_INVALIDDATA;
941 942 943
    }
    if (!got_entropy) {
        av_log(avctx, AV_LOG_ERROR, "No block with entropy info\n");
944
        return AVERROR_INVALIDDATA;
945 946 947
    }
    if (s->hybrid && !got_hybrid) {
        av_log(avctx, AV_LOG_ERROR, "Hybrid config not found\n");
948
        return AVERROR_INVALIDDATA;
949 950 951
    }
    if (!got_bs) {
        av_log(avctx, AV_LOG_ERROR, "Packed samples not found\n");
952
        return AVERROR_INVALIDDATA;
953
    }
954
    if (!got_float && avctx->sample_fmt == AV_SAMPLE_FMT_FLTP) {
955
        av_log(avctx, AV_LOG_ERROR, "Float information not found\n");
956
        return AVERROR_INVALIDDATA;
957
    }
958
    if (s->got_extra_bits && avctx->sample_fmt != AV_SAMPLE_FMT_FLTP) {
959 960 961 962 963
        const int size   = get_bits_left(&s->gb_extra_bits);
        const int wanted = s->samples * s->extra_bits << s->stereo_in;
        if (size < wanted) {
            av_log(avctx, AV_LOG_ERROR, "Too small EXTRABITS\n");
            s->got_extra_bits = 0;
964
        }
965
    }
966

967 968 969 970 971 972 973 974 975 976 977
    if (!wc->ch_offset) {
        int sr = (s->frame_flags >> 23) & 0xf;
        if (sr == 0xf) {
            if (!sample_rate) {
                av_log(avctx, AV_LOG_ERROR, "Custom sample rate missing.\n");
                return AVERROR_INVALIDDATA;
            }
            avctx->sample_rate = sample_rate;
        } else
            avctx->sample_rate = wv_rates[sr];

978 979 980 981 982 983 984 985 986 987 988
        if (multiblock) {
            if (chan)
                avctx->channels = chan;
            if (chmask)
                avctx->channel_layout = chmask;
        } else {
            avctx->channels       = s->stereo ? 2 : 1;
            avctx->channel_layout = s->stereo ? AV_CH_LAYOUT_STEREO :
                                                AV_CH_LAYOUT_MONO;
        }

989
        /* get output buffer */
990
        frame->nb_samples = s->samples + 1;
991
        if ((ret = ff_thread_get_buffer(avctx, &tframe, 0)) < 0)
992
            return ret;
993
        frame->nb_samples = s->samples;
994 995
    }

996 997 998 999 1000
    if (wc->ch_offset + s->stereo >= avctx->channels) {
        av_log(avctx, AV_LOG_WARNING, "Too many channels coded in a packet.\n");
        return (avctx->err_recognition & AV_EF_EXPLODE) ? AVERROR_INVALIDDATA : 0;
    }

1001 1002 1003 1004 1005 1006
    samples_l = frame->extended_data[wc->ch_offset];
    if (s->stereo)
        samples_r = frame->extended_data[wc->ch_offset + 1];

    wc->ch_offset += 1 + s->stereo;

1007
    if (s->stereo_in) {
1008 1009 1010
        ret = wv_unpack_stereo(s, &s->gb, samples_l, samples_r, avctx->sample_fmt);
        if (ret < 0)
            return ret;
1011
    } else {
1012 1013 1014
        ret = wv_unpack_mono(s, &s->gb, samples_l, avctx->sample_fmt);
        if (ret < 0)
            return ret;
1015

1016 1017
        if (s->stereo)
            memcpy(samples_r, samples_l, bpp * s->samples);
1018 1019
    }

1020
    return 0;
1021 1022
}

1023 1024 1025 1026 1027 1028 1029 1030 1031
static void wavpack_decode_flush(AVCodecContext *avctx)
{
    WavpackContext *s = avctx->priv_data;
    int i;

    for (i = 0; i < s->fdec_num; i++)
        wv_reset_saved_context(s->fdec[i]);
}

1032 1033
static int wavpack_decode_frame(AVCodecContext *avctx, void *data,
                                int *got_frame_ptr, AVPacket *avpkt)
1034
{
1035
    WavpackContext *s  = avctx->priv_data;
1036
    const uint8_t *buf = avpkt->data;
1037
    int buf_size       = avpkt->size;
1038
    AVFrame *frame     = data;
1039
    int frame_size, ret, frame_flags;
1040

1041
    if (avpkt->size <= WV_HEADER_SIZE)
1042 1043
        return AVERROR_INVALIDDATA;

1044
    s->block     = 0;
1045 1046
    s->ch_offset = 0;

1047
    /* determine number of samples */
1048 1049
    s->samples  = AV_RL32(buf + 20);
    frame_flags = AV_RL32(buf + 24);
1050
    if (s->samples <= 0 || s->samples > WV_MAX_SAMPLES) {
1051 1052
        av_log(avctx, AV_LOG_ERROR, "Invalid number of samples: %d\n",
               s->samples);
1053
        return AVERROR_INVALIDDATA;
1054 1055
    }

1056
    if (frame_flags & 0x80) {
1057
        avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1058
    } else if ((frame_flags & 0x03) <= 1) {
1059
        avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
1060
    } else {
1061
        avctx->sample_fmt          = AV_SAMPLE_FMT_S32P;
1062
        avctx->bits_per_raw_sample = ((frame_flags & 0x03) + 1) << 3;
1063 1064
    }

1065
    while (buf_size > 0) {
1066 1067 1068 1069 1070
        if (buf_size <= WV_HEADER_SIZE)
            break;
        frame_size = AV_RL32(buf + 4) - 12;
        buf       += 20;
        buf_size  -= 20;
1071
        if (frame_size <= 0 || frame_size > buf_size) {
1072 1073 1074
            av_log(avctx, AV_LOG_ERROR,
                   "Block %d has invalid size (size %d vs. %d bytes left)\n",
                   s->block, frame_size, buf_size);
1075
            wavpack_decode_flush(avctx);
1076
            return AVERROR_INVALIDDATA;
1077
        }
1078
        if ((ret = wavpack_decode_block(avctx, s->block,
1079
                                        frame, buf, frame_size)) < 0) {
1080
            wavpack_decode_flush(avctx);
1081
            return ret;
1082
        }
1083
        s->block++;
1084 1085
        buf      += frame_size;
        buf_size -= frame_size;
1086
    }
1087

1088 1089 1090 1091 1092
    if (s->ch_offset != avctx->channels) {
        av_log(avctx, AV_LOG_ERROR, "Not enough channels coded in a packet.\n");
        return AVERROR_INVALIDDATA;
    }

1093 1094
    *got_frame_ptr = 1;

1095
    return avpkt->size;
1096 1097
}

1098
AVCodec ff_wavpack_decoder = {
1099
    .name           = "wavpack",
1100
    .long_name      = NULL_IF_CONFIG_SMALL("WavPack"),
1101
    .type           = AVMEDIA_TYPE_AUDIO,
1102
    .id             = AV_CODEC_ID_WAVPACK,
1103 1104 1105 1106
    .priv_data_size = sizeof(WavpackContext),
    .init           = wavpack_decode_init,
    .close          = wavpack_decode_end,
    .decode         = wavpack_decode_frame,
1107
    .flush          = wavpack_decode_flush,
1108
    .init_thread_copy = ONLY_IF_THREADS_ENABLED(init_thread_copy),
1109
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS,
1110
};