2 * WavPack lossless audio decoder
3 * Copyright (c) 2006,2011 Konstantin Shishkov
4 * Copyright (c) 2020 David Bryant
6 * This file is part of FFmpeg.
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.
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.
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
23 #include "libavutil/buffer.h"
24 #include "libavutil/channel_layout.h"
26 #define BITSTREAM_READER_LE
28 #include "bytestream.h"
38 * WavPack lossless audio decoder
41 #define DSD_BYTE_READY(low,high) (!(((low) ^ (high)) & 0xff000000))
44 #define PTABLE_BINS (1<<PTABLE_BITS)
45 #define PTABLE_MASK (PTABLE_BINS-1)
48 #define DOWN 0x00010000
52 #define VALUE_ONE (1 << PRECISION)
53 #define PRECISION_USE 12
57 #define MAX_HISTORY_BITS 5
58 #define MAX_HISTORY_BINS (1 << MAX_HISTORY_BITS)
59 #define MAX_BIN_BYTES 1280 // for value_lookup, per bin (2k - 512 - 256)
62 MODULATION_PCM, // pulse code modulation
63 MODULATION_DSD // pulse density modulation (aka DSD)
66 typedef struct WavpackFrameContext {
67 AVCodecContext *avctx;
69 int stereo, stereo_in;
74 uint32_t crc_extra_bits;
75 GetBitContext gb_extra_bits;
78 Decorr decorr[MAX_TERMS];
79 int zero, one, zeroes;
83 int hybrid, hybrid_bitrate;
84 int hybrid_maxclip, hybrid_minclip;
91 int ptable [PTABLE_BINS];
92 uint8_t value_lookup_buffer[MAX_HISTORY_BINS*MAX_BIN_BYTES];
93 uint16_t summed_probabilities[MAX_HISTORY_BINS][256];
94 uint8_t probabilities[MAX_HISTORY_BINS][256];
95 uint8_t *value_lookup[MAX_HISTORY_BINS];
96 } WavpackFrameContext;
98 #define WV_MAX_FRAME_DECODERS 14
100 typedef struct WavpackContext {
101 AVCodecContext *avctx;
103 WavpackFrameContext *fdec[WV_MAX_FRAME_DECODERS];
111 ThreadFrame curr_frame, prev_frame;
112 Modulation modulation;
114 AVBufferRef *dsd_ref;
119 #define LEVEL_DECAY(a) (((a) + 0x80) >> 8)
121 static av_always_inline unsigned get_tail(GetBitContext *gb, int k)
128 e = (1 << (p + 1)) - k - 1;
129 res = get_bitsz(gb, p);
131 res = (res << 1) - e + get_bits1(gb);
135 static int update_error_limit(WavpackFrameContext *ctx)
139 for (i = 0; i <= ctx->stereo_in; i++) {
140 if (ctx->ch[i].bitrate_acc > UINT_MAX - ctx->ch[i].bitrate_delta)
141 return AVERROR_INVALIDDATA;
142 ctx->ch[i].bitrate_acc += ctx->ch[i].bitrate_delta;
143 br[i] = ctx->ch[i].bitrate_acc >> 16;
144 sl[i] = LEVEL_DECAY(ctx->ch[i].slow_level);
146 if (ctx->stereo_in && ctx->hybrid_bitrate) {
147 int balance = (sl[1] - sl[0] + br[1] + 1) >> 1;
148 if (balance > br[0]) {
151 } else if (-balance > br[0]) {
155 br[1] = br[0] + balance;
156 br[0] = br[0] - balance;
159 for (i = 0; i <= ctx->stereo_in; i++) {
160 if (ctx->hybrid_bitrate) {
161 if (sl[i] - br[i] > -0x100)
162 ctx->ch[i].error_limit = wp_exp2(sl[i] - br[i] + 0x100);
164 ctx->ch[i].error_limit = 0;
166 ctx->ch[i].error_limit = wp_exp2(br[i]);
173 static int wv_get_value(WavpackFrameContext *ctx, GetBitContext *gb,
174 int channel, int *last)
177 int sign, base, add, ret;
178 WvChannel *c = &ctx->ch[channel];
182 if ((ctx->ch[0].median[0] < 2U) && (ctx->ch[1].median[0] < 2U) &&
183 !ctx->zero && !ctx->one) {
187 c->slow_level -= LEVEL_DECAY(c->slow_level);
191 t = get_unary_0_33(gb);
193 if (t >= 32 || get_bits_left(gb) < t - 1)
195 t = get_bits_long(gb, t - 1) | (1 << (t - 1));
197 if (get_bits_left(gb) < 0)
202 memset(ctx->ch[0].median, 0, sizeof(ctx->ch[0].median));
203 memset(ctx->ch[1].median, 0, sizeof(ctx->ch[1].median));
204 c->slow_level -= LEVEL_DECAY(c->slow_level);
214 t = get_unary_0_33(gb);
215 if (get_bits_left(gb) < 0)
218 t2 = get_unary_0_33(gb);
220 if (get_bits_left(gb) < 0)
224 if (t2 >= 32 || get_bits_left(gb) < t2 - 1)
226 t += get_bits_long(gb, t2 - 1) | (1 << (t2 - 1));
237 ctx->zero = !ctx->one;
240 if (ctx->hybrid && !channel) {
241 if (update_error_limit(ctx) < 0)
247 add = GET_MED(0) - 1;
251 add = GET_MED(1) - 1;
255 base = GET_MED(0) + GET_MED(1);
256 add = GET_MED(2) - 1;
261 base = GET_MED(0) + GET_MED(1) + GET_MED(2) * (t - 2U);
262 add = GET_MED(2) - 1;
267 if (!c->error_limit) {
268 if (add >= 0x2000000U) {
269 av_log(ctx->avctx, AV_LOG_ERROR, "k %d is too large\n", add);
272 ret = base + get_tail(gb, add);
273 if (get_bits_left(gb) <= 0)
276 int mid = (base * 2U + add + 1) >> 1;
277 while (add > c->error_limit) {
278 if (get_bits_left(gb) <= 0)
281 add -= (mid - (unsigned)base);
284 add = mid - (unsigned)base - 1;
285 mid = (base * 2U + add + 1) >> 1;
289 sign = get_bits1(gb);
290 if (ctx->hybrid_bitrate)
291 c->slow_level += wp_log2(ret) - LEVEL_DECAY(c->slow_level);
292 return sign ? ~ret : ret;
295 ret = get_bits_left(gb);
297 av_log(ctx->avctx, AV_LOG_ERROR, "Too few bits (%d) left\n", ret);
303 static inline int wv_get_value_integer(WavpackFrameContext *s, uint32_t *crc,
309 S *= 1 << s->extra_bits;
311 if (s->got_extra_bits &&
312 get_bits_left(&s->gb_extra_bits) >= s->extra_bits) {
313 S |= get_bits_long(&s->gb_extra_bits, s->extra_bits);
314 *crc = *crc * 9 + (S & 0xffff) * 3 + ((unsigned)S >> 16);
318 bit = (S & s->and) | s->or;
319 bit = ((S + bit) << s->shift) - bit;
322 bit = av_clip(bit, s->hybrid_minclip, s->hybrid_maxclip);
324 return bit << s->post_shift;
327 static float wv_get_value_float(WavpackFrameContext *s, uint32_t *crc, int S)
335 int exp = s->float_max_exp;
337 if (s->got_extra_bits) {
338 const int max_bits = 1 + 23 + 8 + 1;
339 const int left_bits = get_bits_left(&s->gb_extra_bits);
341 if (left_bits + 8 * AV_INPUT_BUFFER_PADDING_SIZE < max_bits)
346 S *= 1U << s->float_shift;
350 if (S >= 0x1000000U) {
351 if (s->got_extra_bits && get_bits1(&s->gb_extra_bits))
352 S = get_bits(&s->gb_extra_bits, 23);
357 int shift = 23 - av_log2(S);
358 exp = s->float_max_exp;
365 if ((s->float_flag & WV_FLT_SHIFT_ONES) ||
366 (s->got_extra_bits &&
367 (s->float_flag & WV_FLT_SHIFT_SAME) &&
368 get_bits1(&s->gb_extra_bits))) {
369 S |= (1 << shift) - 1;
370 } else if (s->got_extra_bits &&
371 (s->float_flag & WV_FLT_SHIFT_SENT)) {
372 S |= get_bits(&s->gb_extra_bits, shift);
376 exp = s->float_max_exp;
382 if (s->got_extra_bits && (s->float_flag & WV_FLT_ZERO_SENT)) {
383 if (get_bits1(&s->gb_extra_bits)) {
384 S = get_bits(&s->gb_extra_bits, 23);
385 if (s->float_max_exp >= 25)
386 exp = get_bits(&s->gb_extra_bits, 8);
387 sign = get_bits1(&s->gb_extra_bits);
389 if (s->float_flag & WV_FLT_ZERO_SIGN)
390 sign = get_bits1(&s->gb_extra_bits);
395 *crc = *crc * 27 + S * 9 + exp * 3 + sign;
397 value.u = (sign << 31) | (exp << 23) | S;
401 static inline int wv_check_crc(WavpackFrameContext *s, uint32_t crc,
402 uint32_t crc_extra_bits)
405 av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
406 return AVERROR_INVALIDDATA;
408 if (s->got_extra_bits && crc_extra_bits != s->crc_extra_bits) {
409 av_log(s->avctx, AV_LOG_ERROR, "Extra bits CRC error\n");
410 return AVERROR_INVALIDDATA;
416 static void init_ptable(int *table, int rate_i, int rate_s)
418 int value = 0x808000, rate = rate_i << 8;
420 for (int c = (rate + 128) >> 8; c--;)
421 value += (DOWN - value) >> DECAY;
423 for (int i = 0; i < PTABLE_BINS/2; i++) {
425 table[PTABLE_BINS-1-i] = 0x100ffff - value;
427 if (value > 0x010000) {
428 rate += (rate * rate_s + 128) >> 8;
430 for (int c = (rate + 64) >> 7; c--;)
431 value += (DOWN - value) >> DECAY;
437 int32_t value, fltr0, fltr1, fltr2, fltr3, fltr4, fltr5, fltr6, factor;
441 static int wv_unpack_dsd_high(WavpackFrameContext *s, uint8_t *dst_left, uint8_t *dst_right)
443 uint32_t checksum = 0xFFFFFFFF;
444 uint8_t *dst_l = dst_left, *dst_r = dst_right;
445 int total_samples = s->samples, stereo = dst_r ? 1 : 0;
446 DSDfilters filters[2], *sp = filters;
448 uint32_t low, high, value;
450 if (bytestream2_get_bytes_left(&s->gbyte) < (stereo ? 20 : 13))
451 return AVERROR_INVALIDDATA;
453 rate_i = bytestream2_get_byte(&s->gbyte);
454 rate_s = bytestream2_get_byte(&s->gbyte);
456 if (rate_s != RATE_S)
457 return AVERROR_INVALIDDATA;
459 init_ptable(s->ptable, rate_i, rate_s);
461 for (int channel = 0; channel < stereo + 1; channel++) {
462 DSDfilters *sp = filters + channel;
464 sp->fltr1 = bytestream2_get_byte(&s->gbyte) << (PRECISION - 8);
465 sp->fltr2 = bytestream2_get_byte(&s->gbyte) << (PRECISION - 8);
466 sp->fltr3 = bytestream2_get_byte(&s->gbyte) << (PRECISION - 8);
467 sp->fltr4 = bytestream2_get_byte(&s->gbyte) << (PRECISION - 8);
468 sp->fltr5 = bytestream2_get_byte(&s->gbyte) << (PRECISION - 8);
470 sp->factor = bytestream2_get_byte(&s->gbyte) & 0xff;
471 sp->factor |= (bytestream2_get_byte(&s->gbyte) << 8) & 0xff00;
472 sp->factor = (int32_t)((uint32_t)sp->factor << 16) >> 16;
475 value = bytestream2_get_be32(&s->gbyte);
479 while (total_samples--) {
482 sp[0].value = sp[0].fltr1 - sp[0].fltr5 + ((sp[0].fltr6 * sp[0].factor) >> 2);
485 sp[1].value = sp[1].fltr1 - sp[1].fltr5 + ((sp[1].fltr6 * sp[1].factor) >> 2);
488 int32_t *pp = s->ptable + ((sp[0].value >> (PRECISION - PRECISION_USE)) & PTABLE_MASK);
489 uint32_t split = low + ((high - low) >> 8) * (*pp >> 16);
491 if (value <= split) {
493 *pp += (UP - *pp) >> DECAY;
497 *pp += (DOWN - *pp) >> DECAY;
501 while (DSD_BYTE_READY(high, low) && bytestream2_get_bytes_left(&s->gbyte)) {
502 value = (value << 8) | bytestream2_get_byte(&s->gbyte);
503 high = (high << 8) | 0xff;
507 sp[0].value += sp[0].fltr6 * 8;
508 sp[0].byte = (sp[0].byte << 1) | (sp[0].fltr0 & 1);
509 sp[0].factor += (((sp[0].value ^ sp[0].fltr0) >> 31) | 1) &
510 ((sp[0].value ^ (sp[0].value - (sp[0].fltr6 * 16))) >> 31);
511 sp[0].fltr1 += ((sp[0].fltr0 & VALUE_ONE) - sp[0].fltr1) >> 6;
512 sp[0].fltr2 += ((sp[0].fltr0 & VALUE_ONE) - sp[0].fltr2) >> 4;
513 sp[0].fltr3 += (sp[0].fltr2 - sp[0].fltr3) >> 4;
514 sp[0].fltr4 += (sp[0].fltr3 - sp[0].fltr4) >> 4;
515 sp[0].value = (sp[0].fltr4 - sp[0].fltr5) >> 4;
516 sp[0].fltr5 += sp[0].value;
517 sp[0].fltr6 += (sp[0].value - sp[0].fltr6) >> 3;
518 sp[0].value = sp[0].fltr1 - sp[0].fltr5 + ((sp[0].fltr6 * sp[0].factor) >> 2);
523 pp = s->ptable + ((sp[1].value >> (PRECISION - PRECISION_USE)) & PTABLE_MASK);
524 split = low + ((high - low) >> 8) * (*pp >> 16);
526 if (value <= split) {
528 *pp += (UP - *pp) >> DECAY;
532 *pp += (DOWN - *pp) >> DECAY;
536 while (DSD_BYTE_READY(high, low) && bytestream2_get_bytes_left(&s->gbyte)) {
537 value = (value << 8) | bytestream2_get_byte(&s->gbyte);
538 high = (high << 8) | 0xff;
542 sp[1].value += sp[1].fltr6 * 8;
543 sp[1].byte = (sp[1].byte << 1) | (sp[1].fltr0 & 1);
544 sp[1].factor += (((sp[1].value ^ sp[1].fltr0) >> 31) | 1) &
545 ((sp[1].value ^ (sp[1].value - (sp[1].fltr6 * 16))) >> 31);
546 sp[1].fltr1 += ((sp[1].fltr0 & VALUE_ONE) - sp[1].fltr1) >> 6;
547 sp[1].fltr2 += ((sp[1].fltr0 & VALUE_ONE) - sp[1].fltr2) >> 4;
548 sp[1].fltr3 += (sp[1].fltr2 - sp[1].fltr3) >> 4;
549 sp[1].fltr4 += (sp[1].fltr3 - sp[1].fltr4) >> 4;
550 sp[1].value = (sp[1].fltr4 - sp[1].fltr5) >> 4;
551 sp[1].fltr5 += sp[1].value;
552 sp[1].fltr6 += (sp[1].value - sp[1].fltr6) >> 3;
553 sp[1].value = sp[1].fltr1 - sp[1].fltr5 + ((sp[1].fltr6 * sp[1].factor) >> 2);
556 checksum += (checksum << 1) + (*dst_l = sp[0].byte & 0xff);
557 sp[0].factor -= (sp[0].factor + 512) >> 10;
561 checksum += (checksum << 1) + (*dst_r = filters[1].byte & 0xff);
562 filters[1].factor -= (filters[1].factor + 512) >> 10;
567 if (wv_check_crc(s, checksum, 0)) {
568 if (s->avctx->err_recognition & AV_EF_CRCCHECK)
569 return AVERROR_INVALIDDATA;
571 memset(dst_left, 0x69, s->samples * 4);
574 memset(dst_right, 0x69, s->samples * 4);
580 static int wv_unpack_dsd_fast(WavpackFrameContext *s, uint8_t *dst_left, uint8_t *dst_right)
582 uint8_t *dst_l = dst_left, *dst_r = dst_right;
583 uint8_t history_bits, max_probability;
584 int total_summed_probabilities = 0;
585 int total_samples = s->samples;
586 uint8_t *vlb = s->value_lookup_buffer;
587 int history_bins, p0, p1, chan;
588 uint32_t checksum = 0xFFFFFFFF;
589 uint32_t low, high, value;
591 if (!bytestream2_get_bytes_left(&s->gbyte))
592 return AVERROR_INVALIDDATA;
594 history_bits = bytestream2_get_byte(&s->gbyte);
596 if (!bytestream2_get_bytes_left(&s->gbyte) || history_bits > MAX_HISTORY_BITS)
597 return AVERROR_INVALIDDATA;
599 history_bins = 1 << history_bits;
600 max_probability = bytestream2_get_byte(&s->gbyte);
602 if (max_probability < 0xff) {
603 uint8_t *outptr = (uint8_t *)s->probabilities;
604 uint8_t *outend = outptr + sizeof(*s->probabilities) * history_bins;
606 while (outptr < outend && bytestream2_get_bytes_left(&s->gbyte)) {
607 int code = bytestream2_get_byte(&s->gbyte);
609 if (code > max_probability) {
610 int zcount = code - max_probability;
612 while (outptr < outend && zcount--)
622 if (outptr < outend ||
623 (bytestream2_get_bytes_left(&s->gbyte) && bytestream2_get_byte(&s->gbyte)))
624 return AVERROR_INVALIDDATA;
625 } else if (bytestream2_get_bytes_left(&s->gbyte) > (int)sizeof(*s->probabilities) * history_bins) {
626 bytestream2_get_buffer(&s->gbyte, (uint8_t *)s->probabilities,
627 sizeof(*s->probabilities) * history_bins);
629 return AVERROR_INVALIDDATA;
632 for (p0 = 0; p0 < history_bins; p0++) {
633 int32_t sum_values = 0;
635 for (int i = 0; i < 256; i++)
636 s->summed_probabilities[p0][i] = sum_values += s->probabilities[p0][i];
639 total_summed_probabilities += sum_values;
641 if (total_summed_probabilities > history_bins * MAX_BIN_BYTES)
642 return AVERROR_INVALIDDATA;
644 s->value_lookup[p0] = vlb;
646 for (int i = 0; i < 256; i++) {
647 int c = s->probabilities[p0][i];
655 if (bytestream2_get_bytes_left(&s->gbyte) < 4)
656 return AVERROR_INVALIDDATA;
659 low = 0; high = 0xffffffff;
660 value = bytestream2_get_be32(&s->gbyte);
665 while (total_samples--) {
666 unsigned int mult, index, code;
668 if (!s->summed_probabilities[p0][255])
669 return AVERROR_INVALIDDATA;
671 mult = (high - low) / s->summed_probabilities[p0][255];
674 if (bytestream2_get_bytes_left(&s->gbyte) >= 4)
675 value = bytestream2_get_be32(&s->gbyte);
679 mult = high / s->summed_probabilities[p0][255];
682 return AVERROR_INVALIDDATA;
685 index = (value - low) / mult;
687 if (index >= s->summed_probabilities[p0][255])
688 return AVERROR_INVALIDDATA;
691 if ((*dst_l = code = s->value_lookup[p0][index]))
692 low += s->summed_probabilities[p0][code-1] * mult;
696 if ((code = s->value_lookup[p0][index]))
697 low += s->summed_probabilities[p0][code-1] * mult;
711 high = low + s->probabilities[p0][code] * mult - 1;
712 checksum += (checksum << 1) + code;
715 p0 = code & (history_bins-1);
718 p1 = code & (history_bins-1);
721 while (DSD_BYTE_READY(high, low) && bytestream2_get_bytes_left(&s->gbyte)) {
722 value = (value << 8) | bytestream2_get_byte(&s->gbyte);
723 high = (high << 8) | 0xff;
728 if (wv_check_crc(s, checksum, 0)) {
729 if (s->avctx->err_recognition & AV_EF_CRCCHECK)
730 return AVERROR_INVALIDDATA;
732 memset(dst_left, 0x69, s->samples * 4);
735 memset(dst_right, 0x69, s->samples * 4);
741 static int wv_unpack_dsd_copy(WavpackFrameContext *s, uint8_t *dst_left, uint8_t *dst_right)
743 uint8_t *dst_l = dst_left, *dst_r = dst_right;
744 int total_samples = s->samples;
745 uint32_t checksum = 0xFFFFFFFF;
747 if (bytestream2_get_bytes_left(&s->gbyte) != total_samples * (dst_r ? 2 : 1))
748 return AVERROR_INVALIDDATA;
750 while (total_samples--) {
751 checksum += (checksum << 1) + (*dst_l = bytestream2_get_byte(&s->gbyte));
755 checksum += (checksum << 1) + (*dst_r = bytestream2_get_byte(&s->gbyte));
760 if (wv_check_crc(s, checksum, 0)) {
761 if (s->avctx->err_recognition & AV_EF_CRCCHECK)
762 return AVERROR_INVALIDDATA;
764 memset(dst_left, 0x69, s->samples * 4);
767 memset(dst_right, 0x69, s->samples * 4);
773 static inline int wv_unpack_stereo(WavpackFrameContext *s, GetBitContext *gb,
774 void *dst_l, void *dst_r, const int type)
778 int A, B, L, L2, R, R2;
780 uint32_t crc = 0xFFFFFFFF;
781 uint32_t crc_extra_bits = 0xFFFFFFFF;
782 int16_t *dst16_l = dst_l;
783 int16_t *dst16_r = dst_r;
784 int32_t *dst32_l = dst_l;
785 int32_t *dst32_r = dst_r;
786 float *dstfl_l = dst_l;
787 float *dstfl_r = dst_r;
789 s->one = s->zero = s->zeroes = 0;
791 L = wv_get_value(s, gb, 0, &last);
794 R = wv_get_value(s, gb, 1, &last);
797 for (i = 0; i < s->terms; i++) {
798 t = s->decorr[i].value;
802 A = 2U * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
803 B = 2U * s->decorr[i].samplesB[0] - s->decorr[i].samplesB[1];
805 A = (int)(3U * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1]) >> 1;
806 B = (int)(3U * s->decorr[i].samplesB[0] - s->decorr[i].samplesB[1]) >> 1;
808 s->decorr[i].samplesA[1] = s->decorr[i].samplesA[0];
809 s->decorr[i].samplesB[1] = s->decorr[i].samplesB[0];
812 A = s->decorr[i].samplesA[pos];
813 B = s->decorr[i].samplesB[pos];
816 if (type != AV_SAMPLE_FMT_S16P) {
817 L2 = L + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
818 R2 = R + ((s->decorr[i].weightB * (int64_t)B + 512) >> 10);
820 L2 = L + (unsigned)((int)(s->decorr[i].weightA * (unsigned)A + 512) >> 10);
821 R2 = R + (unsigned)((int)(s->decorr[i].weightB * (unsigned)B + 512) >> 10);
824 s->decorr[i].weightA -= ((((L ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
826 s->decorr[i].weightB -= ((((R ^ B) >> 30) & 2) - 1) * s->decorr[i].delta;
827 s->decorr[i].samplesA[j] = L = L2;
828 s->decorr[i].samplesB[j] = R = R2;
829 } else if (t == -1) {
830 if (type != AV_SAMPLE_FMT_S16P)
831 L2 = L + ((s->decorr[i].weightA * (int64_t)s->decorr[i].samplesA[0] + 512) >> 10);
833 L2 = L + (unsigned)((int)(s->decorr[i].weightA * (unsigned)s->decorr[i].samplesA[0] + 512) >> 10);
834 UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, s->decorr[i].samplesA[0], L);
836 if (type != AV_SAMPLE_FMT_S16P)
837 R2 = R + ((s->decorr[i].weightB * (int64_t)L2 + 512) >> 10);
839 R2 = R + (unsigned)((int)(s->decorr[i].weightB * (unsigned)L2 + 512) >> 10);
840 UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, L2, R);
842 s->decorr[i].samplesA[0] = R;
844 if (type != AV_SAMPLE_FMT_S16P)
845 R2 = R + ((s->decorr[i].weightB * (int64_t)s->decorr[i].samplesB[0] + 512) >> 10);
847 R2 = R + (unsigned)((int)(s->decorr[i].weightB * (unsigned)s->decorr[i].samplesB[0] + 512) >> 10);
848 UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, s->decorr[i].samplesB[0], R);
852 R2 = s->decorr[i].samplesA[0];
853 s->decorr[i].samplesA[0] = R;
856 if (type != AV_SAMPLE_FMT_S16P)
857 L2 = L + ((s->decorr[i].weightA * (int64_t)R2 + 512) >> 10);
859 L2 = L + (unsigned)((int)(s->decorr[i].weightA * (unsigned)R2 + 512) >> 10);
860 UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, R2, L);
862 s->decorr[i].samplesB[0] = L;
866 if (type == AV_SAMPLE_FMT_S16P) {
867 if (FFABS((int64_t)L) + FFABS((int64_t)R) > (1<<19)) {
868 av_log(s->avctx, AV_LOG_ERROR, "sample %d %d too large\n", L, R);
869 return AVERROR_INVALIDDATA;
875 L += (unsigned)(R -= (unsigned)(L >> 1));
876 crc = (crc * 3 + L) * 3 + R;
878 if (type == AV_SAMPLE_FMT_FLTP) {
879 *dstfl_l++ = wv_get_value_float(s, &crc_extra_bits, L);
880 *dstfl_r++ = wv_get_value_float(s, &crc_extra_bits, R);
881 } else if (type == AV_SAMPLE_FMT_S32P) {
882 *dst32_l++ = wv_get_value_integer(s, &crc_extra_bits, L);
883 *dst32_r++ = wv_get_value_integer(s, &crc_extra_bits, R);
885 *dst16_l++ = wv_get_value_integer(s, &crc_extra_bits, L);
886 *dst16_r++ = wv_get_value_integer(s, &crc_extra_bits, R);
889 } while (!last && count < s->samples);
891 if (last && count < s->samples) {
892 int size = av_get_bytes_per_sample(type);
893 memset((uint8_t*)dst_l + count*size, 0, (s->samples-count)*size);
894 memset((uint8_t*)dst_r + count*size, 0, (s->samples-count)*size);
897 if ((s->avctx->err_recognition & AV_EF_CRCCHECK) &&
898 wv_check_crc(s, crc, crc_extra_bits))
899 return AVERROR_INVALIDDATA;
904 static inline int wv_unpack_mono(WavpackFrameContext *s, GetBitContext *gb,
905 void *dst, const int type)
911 uint32_t crc = 0xFFFFFFFF;
912 uint32_t crc_extra_bits = 0xFFFFFFFF;
913 int16_t *dst16 = dst;
914 int32_t *dst32 = dst;
917 s->one = s->zero = s->zeroes = 0;
919 T = wv_get_value(s, gb, 0, &last);
923 for (i = 0; i < s->terms; i++) {
924 t = s->decorr[i].value;
927 A = 2U * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
929 A = (int)(3U * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1]) >> 1;
930 s->decorr[i].samplesA[1] = s->decorr[i].samplesA[0];
933 A = s->decorr[i].samplesA[pos];
936 if (type != AV_SAMPLE_FMT_S16P)
937 S = T + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
939 S = T + (unsigned)((int)(s->decorr[i].weightA * (unsigned)A + 512) >> 10);
941 s->decorr[i].weightA -= ((((T ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
942 s->decorr[i].samplesA[j] = T = S;
947 if (type == AV_SAMPLE_FMT_FLTP) {
948 *dstfl++ = wv_get_value_float(s, &crc_extra_bits, S);
949 } else if (type == AV_SAMPLE_FMT_S32P) {
950 *dst32++ = wv_get_value_integer(s, &crc_extra_bits, S);
952 *dst16++ = wv_get_value_integer(s, &crc_extra_bits, S);
955 } while (!last && count < s->samples);
957 if (last && count < s->samples) {
958 int size = av_get_bytes_per_sample(type);
959 memset((uint8_t*)dst + count*size, 0, (s->samples-count)*size);
962 if (s->avctx->err_recognition & AV_EF_CRCCHECK) {
963 int ret = wv_check_crc(s, crc, crc_extra_bits);
964 if (ret < 0 && s->avctx->err_recognition & AV_EF_EXPLODE)
971 static av_cold int wv_alloc_frame_context(WavpackContext *c)
973 if (c->fdec_num == WV_MAX_FRAME_DECODERS)
976 c->fdec[c->fdec_num] = av_mallocz(sizeof(**c->fdec));
977 if (!c->fdec[c->fdec_num])
980 c->fdec[c->fdec_num - 1]->avctx = c->avctx;
985 static int wv_dsd_reset(WavpackContext *s, int channels)
991 av_buffer_unref(&s->dsd_ref);
996 if (channels > INT_MAX / sizeof(*s->dsdctx))
997 return AVERROR(EINVAL);
999 s->dsd_ref = av_buffer_allocz(channels * sizeof(*s->dsdctx));
1001 return AVERROR(ENOMEM);
1002 s->dsdctx = (DSDContext*)s->dsd_ref->data;
1003 s->dsd_channels = channels;
1005 for (i = 0; i < channels; i++)
1006 memset(s->dsdctx[i].buf, 0x69, sizeof(s->dsdctx[i].buf));
1012 static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
1014 WavpackContext *fsrc = src->priv_data;
1015 WavpackContext *fdst = dst->priv_data;
1021 ff_thread_release_buffer(dst, &fdst->curr_frame);
1022 if (fsrc->curr_frame.f->data[0]) {
1023 if ((ret = ff_thread_ref_frame(&fdst->curr_frame, &fsrc->curr_frame)) < 0)
1027 av_buffer_unref(&fdst->dsd_ref);
1028 fdst->dsdctx = NULL;
1029 fdst->dsd_channels = 0;
1030 if (fsrc->dsd_ref) {
1031 fdst->dsd_ref = av_buffer_ref(fsrc->dsd_ref);
1033 return AVERROR(ENOMEM);
1034 fdst->dsdctx = (DSDContext*)fdst->dsd_ref->data;
1035 fdst->dsd_channels = fsrc->dsd_channels;
1042 static av_cold int wavpack_decode_init(AVCodecContext *avctx)
1044 WavpackContext *s = avctx->priv_data;
1050 s->curr_frame.f = av_frame_alloc();
1051 s->prev_frame.f = av_frame_alloc();
1053 if (!s->curr_frame.f || !s->prev_frame.f)
1054 return AVERROR(ENOMEM);
1061 static av_cold int wavpack_decode_end(AVCodecContext *avctx)
1063 WavpackContext *s = avctx->priv_data;
1065 for (int i = 0; i < s->fdec_num; i++)
1066 av_freep(&s->fdec[i]);
1069 ff_thread_release_buffer(avctx, &s->curr_frame);
1070 av_frame_free(&s->curr_frame.f);
1072 ff_thread_release_buffer(avctx, &s->prev_frame);
1073 av_frame_free(&s->prev_frame.f);
1075 av_buffer_unref(&s->dsd_ref);
1080 static int wavpack_decode_block(AVCodecContext *avctx, int block_no,
1081 const uint8_t *buf, int buf_size)
1083 WavpackContext *wc = avctx->priv_data;
1084 WavpackFrameContext *s;
1086 enum AVSampleFormat sample_fmt;
1087 void *samples_l = NULL, *samples_r = NULL;
1089 int got_terms = 0, got_weights = 0, got_samples = 0,
1090 got_entropy = 0, got_pcm = 0, got_float = 0, got_hybrid = 0;
1092 int i, j, id, size, ssize, weights, t;
1093 int bpp, chan = 0, orig_bpp, sample_rate = 0, rate_x = 1, dsd_mode = 0;
1095 uint64_t chmask = 0;
1097 if (block_no >= wc->fdec_num && wv_alloc_frame_context(wc) < 0) {
1098 av_log(avctx, AV_LOG_ERROR, "Error creating frame decode context\n");
1099 return AVERROR_INVALIDDATA;
1102 s = wc->fdec[block_no];
1104 av_log(avctx, AV_LOG_ERROR, "Context for block %d is not present\n",
1106 return AVERROR_INVALIDDATA;
1109 memset(s->decorr, 0, MAX_TERMS * sizeof(Decorr));
1110 memset(s->ch, 0, sizeof(s->ch));
1112 s->and = s->or = s->shift = 0;
1113 s->got_extra_bits = 0;
1115 bytestream2_init(&gb, buf, buf_size);
1117 s->samples = bytestream2_get_le32(&gb);
1118 if (s->samples != wc->samples) {
1119 av_log(avctx, AV_LOG_ERROR, "Mismatching number of samples in "
1120 "a sequence: %d and %d\n", wc->samples, s->samples);
1121 return AVERROR_INVALIDDATA;
1123 s->frame_flags = bytestream2_get_le32(&gb);
1125 if (s->frame_flags & (WV_FLOAT_DATA | WV_DSD_DATA))
1126 sample_fmt = AV_SAMPLE_FMT_FLTP;
1127 else if ((s->frame_flags & 0x03) <= 1)
1128 sample_fmt = AV_SAMPLE_FMT_S16P;
1130 sample_fmt = AV_SAMPLE_FMT_S32P;
1132 if (wc->ch_offset && avctx->sample_fmt != sample_fmt)
1133 return AVERROR_INVALIDDATA;
1135 bpp = av_get_bytes_per_sample(sample_fmt);
1136 orig_bpp = ((s->frame_flags & 0x03) + 1) << 3;
1137 multiblock = (s->frame_flags & WV_SINGLE_BLOCK) != WV_SINGLE_BLOCK;
1139 s->stereo = !(s->frame_flags & WV_MONO);
1140 s->stereo_in = (s->frame_flags & WV_FALSE_STEREO) ? 0 : s->stereo;
1141 s->joint = s->frame_flags & WV_JOINT_STEREO;
1142 s->hybrid = s->frame_flags & WV_HYBRID_MODE;
1143 s->hybrid_bitrate = s->frame_flags & WV_HYBRID_BITRATE;
1144 s->post_shift = bpp * 8 - orig_bpp + ((s->frame_flags >> 13) & 0x1f);
1145 if (s->post_shift < 0 || s->post_shift > 31) {
1146 return AVERROR_INVALIDDATA;
1148 s->hybrid_maxclip = ((1LL << (orig_bpp - 1)) - 1);
1149 s->hybrid_minclip = ((-1UL << (orig_bpp - 1)));
1150 s->CRC = bytestream2_get_le32(&gb);
1152 // parse metadata blocks
1153 while (bytestream2_get_bytes_left(&gb)) {
1154 id = bytestream2_get_byte(&gb);
1155 size = bytestream2_get_byte(&gb);
1156 if (id & WP_IDF_LONG)
1157 size |= (bytestream2_get_le16u(&gb)) << 8;
1158 size <<= 1; // size is specified in words
1160 if (id & WP_IDF_ODD)
1163 av_log(avctx, AV_LOG_ERROR,
1164 "Got incorrect block %02X with size %i\n", id, size);
1167 if (bytestream2_get_bytes_left(&gb) < ssize) {
1168 av_log(avctx, AV_LOG_ERROR,
1169 "Block size %i is out of bounds\n", size);
1172 switch (id & WP_IDF_MASK) {
1173 case WP_ID_DECTERMS:
1174 if (size > MAX_TERMS) {
1175 av_log(avctx, AV_LOG_ERROR, "Too many decorrelation terms\n");
1177 bytestream2_skip(&gb, ssize);
1181 for (i = 0; i < s->terms; i++) {
1182 uint8_t val = bytestream2_get_byte(&gb);
1183 s->decorr[s->terms - i - 1].value = (val & 0x1F) - 5;
1184 s->decorr[s->terms - i - 1].delta = val >> 5;
1188 case WP_ID_DECWEIGHTS:
1190 av_log(avctx, AV_LOG_ERROR, "No decorrelation terms met\n");
1193 weights = size >> s->stereo_in;
1194 if (weights > MAX_TERMS || weights > s->terms) {
1195 av_log(avctx, AV_LOG_ERROR, "Too many decorrelation weights\n");
1196 bytestream2_skip(&gb, ssize);
1199 for (i = 0; i < weights; i++) {
1200 t = (int8_t)bytestream2_get_byte(&gb);
1201 s->decorr[s->terms - i - 1].weightA = t * (1 << 3);
1202 if (s->decorr[s->terms - i - 1].weightA > 0)
1203 s->decorr[s->terms - i - 1].weightA +=
1204 (s->decorr[s->terms - i - 1].weightA + 64) >> 7;
1206 t = (int8_t)bytestream2_get_byte(&gb);
1207 s->decorr[s->terms - i - 1].weightB = t * (1 << 3);
1208 if (s->decorr[s->terms - i - 1].weightB > 0)
1209 s->decorr[s->terms - i - 1].weightB +=
1210 (s->decorr[s->terms - i - 1].weightB + 64) >> 7;
1215 case WP_ID_DECSAMPLES:
1217 av_log(avctx, AV_LOG_ERROR, "No decorrelation terms met\n");
1221 for (i = s->terms - 1; (i >= 0) && (t < size); i--) {
1222 if (s->decorr[i].value > 8) {
1223 s->decorr[i].samplesA[0] =
1224 wp_exp2(bytestream2_get_le16(&gb));
1225 s->decorr[i].samplesA[1] =
1226 wp_exp2(bytestream2_get_le16(&gb));
1229 s->decorr[i].samplesB[0] =
1230 wp_exp2(bytestream2_get_le16(&gb));
1231 s->decorr[i].samplesB[1] =
1232 wp_exp2(bytestream2_get_le16(&gb));
1236 } else if (s->decorr[i].value < 0) {
1237 s->decorr[i].samplesA[0] =
1238 wp_exp2(bytestream2_get_le16(&gb));
1239 s->decorr[i].samplesB[0] =
1240 wp_exp2(bytestream2_get_le16(&gb));
1243 for (j = 0; j < s->decorr[i].value; j++) {
1244 s->decorr[i].samplesA[j] =
1245 wp_exp2(bytestream2_get_le16(&gb));
1247 s->decorr[i].samplesB[j] =
1248 wp_exp2(bytestream2_get_le16(&gb));
1251 t += s->decorr[i].value * 2 * (s->stereo_in + 1);
1257 if (size != 6 * (s->stereo_in + 1)) {
1258 av_log(avctx, AV_LOG_ERROR,
1259 "Entropy vars size should be %i, got %i.\n",
1260 6 * (s->stereo_in + 1), size);
1261 bytestream2_skip(&gb, ssize);
1264 for (j = 0; j <= s->stereo_in; j++)
1265 for (i = 0; i < 3; i++) {
1266 s->ch[j].median[i] = wp_exp2(bytestream2_get_le16(&gb));
1271 if (s->hybrid_bitrate) {
1272 for (i = 0; i <= s->stereo_in; i++) {
1273 s->ch[i].slow_level = wp_exp2(bytestream2_get_le16(&gb));
1277 for (i = 0; i < (s->stereo_in + 1); i++) {
1278 s->ch[i].bitrate_acc = bytestream2_get_le16(&gb) << 16;
1282 for (i = 0; i < (s->stereo_in + 1); i++) {
1283 s->ch[i].bitrate_delta =
1284 wp_exp2((int16_t)bytestream2_get_le16(&gb));
1287 for (i = 0; i < (s->stereo_in + 1); i++)
1288 s->ch[i].bitrate_delta = 0;
1292 case WP_ID_INT32INFO: {
1295 av_log(avctx, AV_LOG_ERROR,
1296 "Invalid INT32INFO, size = %i\n",
1298 bytestream2_skip(&gb, ssize - 4);
1301 bytestream2_get_buffer(&gb, val, 4);
1303 av_log(avctx, AV_LOG_ERROR,
1304 "Invalid INT32INFO, extra_bits = %d (> 30)\n", val[0]);
1306 } else if (val[0]) {
1307 s->extra_bits = val[0];
1308 } else if (val[1]) {
1310 } else if (val[2]) {
1313 } else if (val[3]) {
1317 if (s->shift > 31) {
1318 av_log(avctx, AV_LOG_ERROR,
1319 "Invalid INT32INFO, shift = %d (> 31)\n", s->shift);
1320 s->and = s->or = s->shift = 0;
1323 /* original WavPack decoder forces 32-bit lossy sound to be treated
1324 * as 24-bit one in order to have proper clipping */
1325 if (s->hybrid && bpp == 4 && s->post_shift < 8 && s->shift > 8) {
1328 s->hybrid_maxclip >>= 8;
1329 s->hybrid_minclip >>= 8;
1333 case WP_ID_FLOATINFO:
1335 av_log(avctx, AV_LOG_ERROR,
1336 "Invalid FLOATINFO, size = %i\n", size);
1337 bytestream2_skip(&gb, ssize);
1340 s->float_flag = bytestream2_get_byte(&gb);
1341 s->float_shift = bytestream2_get_byte(&gb);
1342 s->float_max_exp = bytestream2_get_byte(&gb);
1343 if (s->float_shift > 31) {
1344 av_log(avctx, AV_LOG_ERROR,
1345 "Invalid FLOATINFO, shift = %d (> 31)\n", s->float_shift);
1350 bytestream2_skip(&gb, 1);
1353 if ((ret = init_get_bits8(&s->gb, gb.buffer, size)) < 0)
1355 bytestream2_skip(&gb, size);
1358 case WP_ID_DSD_DATA:
1360 av_log(avctx, AV_LOG_ERROR, "Invalid DSD_DATA, size = %i\n",
1362 bytestream2_skip(&gb, ssize);
1365 rate_x = bytestream2_get_byte(&gb);
1367 return AVERROR_INVALIDDATA;
1368 rate_x = 1 << rate_x;
1369 dsd_mode = bytestream2_get_byte(&gb);
1370 if (dsd_mode && dsd_mode != 1 && dsd_mode != 3) {
1371 av_log(avctx, AV_LOG_ERROR, "Invalid DSD encoding mode: %d\n",
1373 return AVERROR_INVALIDDATA;
1375 bytestream2_init(&s->gbyte, gb.buffer, size-2);
1376 bytestream2_skip(&gb, size-2);
1379 case WP_ID_EXTRABITS:
1381 av_log(avctx, AV_LOG_ERROR, "Invalid EXTRABITS, size = %i\n",
1383 bytestream2_skip(&gb, size);
1386 if ((ret = init_get_bits8(&s->gb_extra_bits, gb.buffer, size)) < 0)
1388 s->crc_extra_bits = get_bits_long(&s->gb_extra_bits, 32);
1389 bytestream2_skip(&gb, size);
1390 s->got_extra_bits = 1;
1392 case WP_ID_CHANINFO:
1394 av_log(avctx, AV_LOG_ERROR,
1395 "Insufficient channel information\n");
1396 return AVERROR_INVALIDDATA;
1398 chan = bytestream2_get_byte(&gb);
1401 chmask = bytestream2_get_byte(&gb);
1404 chmask = bytestream2_get_le16(&gb);
1407 chmask = bytestream2_get_le24(&gb);
1410 chmask = bytestream2_get_le32(&gb);
1413 size = bytestream2_get_byte(&gb);
1414 chan |= (bytestream2_get_byte(&gb) & 0xF) << 8;
1416 if (avctx->channels != chan)
1417 av_log(avctx, AV_LOG_WARNING, "%i channels signalled"
1418 " instead of %i.\n", chan, avctx->channels);
1419 chmask = bytestream2_get_le24(&gb);
1422 size = bytestream2_get_byte(&gb);
1423 chan |= (bytestream2_get_byte(&gb) & 0xF) << 8;
1425 if (avctx->channels != chan)
1426 av_log(avctx, AV_LOG_WARNING, "%i channels signalled"
1427 " instead of %i.\n", chan, avctx->channels);
1428 chmask = bytestream2_get_le32(&gb);
1431 av_log(avctx, AV_LOG_ERROR, "Invalid channel info size %d\n",
1433 chan = avctx->channels;
1434 chmask = avctx->channel_layout;
1437 case WP_ID_SAMPLE_RATE:
1439 av_log(avctx, AV_LOG_ERROR, "Invalid custom sample rate.\n");
1440 return AVERROR_INVALIDDATA;
1442 sample_rate = bytestream2_get_le24(&gb);
1445 bytestream2_skip(&gb, size);
1447 if (id & WP_IDF_ODD)
1448 bytestream2_skip(&gb, 1);
1453 av_log(avctx, AV_LOG_ERROR, "No block with decorrelation terms\n");
1454 return AVERROR_INVALIDDATA;
1457 av_log(avctx, AV_LOG_ERROR, "No block with decorrelation weights\n");
1458 return AVERROR_INVALIDDATA;
1461 av_log(avctx, AV_LOG_ERROR, "No block with decorrelation samples\n");
1462 return AVERROR_INVALIDDATA;
1465 av_log(avctx, AV_LOG_ERROR, "No block with entropy info\n");
1466 return AVERROR_INVALIDDATA;
1468 if (s->hybrid && !got_hybrid) {
1469 av_log(avctx, AV_LOG_ERROR, "Hybrid config not found\n");
1470 return AVERROR_INVALIDDATA;
1472 if (!got_float && sample_fmt == AV_SAMPLE_FMT_FLTP) {
1473 av_log(avctx, AV_LOG_ERROR, "Float information not found\n");
1474 return AVERROR_INVALIDDATA;
1476 if (s->got_extra_bits && sample_fmt != AV_SAMPLE_FMT_FLTP) {
1477 const int size = get_bits_left(&s->gb_extra_bits);
1478 const int wanted = s->samples * s->extra_bits << s->stereo_in;
1479 if (size < wanted) {
1480 av_log(avctx, AV_LOG_ERROR, "Too small EXTRABITS\n");
1481 s->got_extra_bits = 0;
1486 if (!got_pcm && !got_dsd) {
1487 av_log(avctx, AV_LOG_ERROR, "Packed samples not found\n");
1488 return AVERROR_INVALIDDATA;
1491 if ((got_pcm && wc->modulation != MODULATION_PCM) ||
1492 (got_dsd && wc->modulation != MODULATION_DSD)) {
1493 av_log(avctx, AV_LOG_ERROR, "Invalid PCM/DSD mix encountered\n");
1494 return AVERROR_INVALIDDATA;
1497 if (!wc->ch_offset) {
1498 int new_channels = avctx->channels;
1499 uint64_t new_chmask = avctx->channel_layout;
1501 int sr = (s->frame_flags >> 23) & 0xf;
1504 av_log(avctx, AV_LOG_ERROR, "Custom sample rate missing.\n");
1505 return AVERROR_INVALIDDATA;
1507 new_samplerate = sample_rate;
1509 new_samplerate = wv_rates[sr];
1511 if (new_samplerate * (uint64_t)rate_x > INT_MAX)
1512 return AVERROR_INVALIDDATA;
1513 new_samplerate *= rate_x;
1517 new_channels = chan;
1519 new_chmask = chmask;
1521 new_channels = s->stereo ? 2 : 1;
1522 new_chmask = s->stereo ? AV_CH_LAYOUT_STEREO :
1527 av_get_channel_layout_nb_channels(new_chmask) != new_channels) {
1528 av_log(avctx, AV_LOG_ERROR, "Channel mask does not match the channel count\n");
1529 return AVERROR_INVALIDDATA;
1532 /* clear DSD state if stream properties change */
1533 if (new_channels != wc->dsd_channels ||
1534 new_chmask != avctx->channel_layout ||
1535 new_samplerate != avctx->sample_rate ||
1536 !!got_dsd != !!wc->dsdctx) {
1537 ret = wv_dsd_reset(wc, got_dsd ? new_channels : 0);
1539 av_log(avctx, AV_LOG_ERROR, "Error reinitializing the DSD context\n");
1542 ff_thread_release_buffer(avctx, &wc->curr_frame);
1544 avctx->channels = new_channels;
1545 avctx->channel_layout = new_chmask;
1546 avctx->sample_rate = new_samplerate;
1547 avctx->sample_fmt = sample_fmt;
1548 avctx->bits_per_raw_sample = orig_bpp;
1550 ff_thread_release_buffer(avctx, &wc->prev_frame);
1551 FFSWAP(ThreadFrame, wc->curr_frame, wc->prev_frame);
1553 /* get output buffer */
1554 wc->curr_frame.f->nb_samples = s->samples;
1555 if ((ret = ff_thread_get_buffer(avctx, &wc->curr_frame, AV_GET_BUFFER_FLAG_REF)) < 0)
1558 wc->frame = wc->curr_frame.f;
1559 ff_thread_finish_setup(avctx);
1562 if (wc->ch_offset + s->stereo >= avctx->channels) {
1563 av_log(avctx, AV_LOG_WARNING, "Too many channels coded in a packet.\n");
1564 return ((avctx->err_recognition & AV_EF_EXPLODE) || !wc->ch_offset) ? AVERROR_INVALIDDATA : 0;
1567 samples_l = wc->frame->extended_data[wc->ch_offset];
1569 samples_r = wc->frame->extended_data[wc->ch_offset + 1];
1571 wc->ch_offset += 1 + s->stereo;
1575 if (dsd_mode == 3) {
1576 ret = wv_unpack_dsd_high(s, samples_l, samples_r);
1577 } else if (dsd_mode == 1) {
1578 ret = wv_unpack_dsd_fast(s, samples_l, samples_r);
1580 ret = wv_unpack_dsd_copy(s, samples_l, samples_r);
1583 ret = wv_unpack_stereo(s, &s->gb, samples_l, samples_r, avctx->sample_fmt);
1589 if (dsd_mode == 3) {
1590 ret = wv_unpack_dsd_high(s, samples_l, NULL);
1591 } else if (dsd_mode == 1) {
1592 ret = wv_unpack_dsd_fast(s, samples_l, NULL);
1594 ret = wv_unpack_dsd_copy(s, samples_l, NULL);
1597 ret = wv_unpack_mono(s, &s->gb, samples_l, avctx->sample_fmt);
1603 memcpy(samples_r, samples_l, bpp * s->samples);
1609 static void wavpack_decode_flush(AVCodecContext *avctx)
1611 WavpackContext *s = avctx->priv_data;
1616 static int dsd_channel(AVCodecContext *avctx, void *frmptr, int jobnr, int threadnr)
1618 WavpackContext *s = avctx->priv_data;
1619 AVFrame *frame = frmptr;
1621 ff_dsd2pcm_translate (&s->dsdctx [jobnr], s->samples, 0,
1622 (uint8_t *)frame->extended_data[jobnr], 4,
1623 (float *)frame->extended_data[jobnr], 1);
1628 static int wavpack_decode_frame(AVCodecContext *avctx, void *data,
1629 int *got_frame_ptr, AVPacket *avpkt)
1631 WavpackContext *s = avctx->priv_data;
1632 const uint8_t *buf = avpkt->data;
1633 int buf_size = avpkt->size;
1634 int frame_size, ret, frame_flags;
1636 if (avpkt->size <= WV_HEADER_SIZE)
1637 return AVERROR_INVALIDDATA;
1643 /* determine number of samples */
1644 s->samples = AV_RL32(buf + 20);
1645 frame_flags = AV_RL32(buf + 24);
1646 if (s->samples <= 0 || s->samples > WV_MAX_SAMPLES) {
1647 av_log(avctx, AV_LOG_ERROR, "Invalid number of samples: %d\n",
1649 return AVERROR_INVALIDDATA;
1652 s->modulation = (frame_flags & WV_DSD_DATA) ? MODULATION_DSD : MODULATION_PCM;
1654 while (buf_size > WV_HEADER_SIZE) {
1655 frame_size = AV_RL32(buf + 4) - 12;
1658 if (frame_size <= 0 || frame_size > buf_size) {
1659 av_log(avctx, AV_LOG_ERROR,
1660 "Block %d has invalid size (size %d vs. %d bytes left)\n",
1661 s->block, frame_size, buf_size);
1662 ret = AVERROR_INVALIDDATA;
1665 if ((ret = wavpack_decode_block(avctx, s->block, buf, frame_size)) < 0)
1669 buf_size -= frame_size;
1672 if (s->ch_offset != avctx->channels) {
1673 av_log(avctx, AV_LOG_ERROR, "Not enough channels coded in a packet.\n");
1674 ret = AVERROR_INVALIDDATA;
1678 ff_thread_await_progress(&s->prev_frame, INT_MAX, 0);
1679 ff_thread_release_buffer(avctx, &s->prev_frame);
1681 if (s->modulation == MODULATION_DSD)
1682 avctx->execute2(avctx, dsd_channel, s->frame, NULL, avctx->channels);
1684 ff_thread_report_progress(&s->curr_frame, INT_MAX, 0);
1686 if ((ret = av_frame_ref(data, s->frame)) < 0)
1695 ff_thread_await_progress(&s->prev_frame, INT_MAX, 0);
1696 ff_thread_release_buffer(avctx, &s->prev_frame);
1697 ff_thread_report_progress(&s->curr_frame, INT_MAX, 0);
1703 AVCodec ff_wavpack_decoder = {
1705 .long_name = NULL_IF_CONFIG_SMALL("WavPack"),
1706 .type = AVMEDIA_TYPE_AUDIO,
1707 .id = AV_CODEC_ID_WAVPACK,
1708 .priv_data_size = sizeof(WavpackContext),
1709 .init = wavpack_decode_init,
1710 .close = wavpack_decode_end,
1711 .decode = wavpack_decode_frame,
1712 .flush = wavpack_decode_flush,
1713 .update_thread_context = ONLY_IF_THREADS_ENABLED(update_thread_context),
1714 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS |
1715 AV_CODEC_CAP_SLICE_THREADS,
1716 .caps_internal = FF_CODEC_CAP_ALLOCATE_PROGRESS,