]> git.sesse.net Git - ffmpeg/blob - libavcodec/wavpack.c
avcodec/vp8: Cosmetics, maintain alphabetical order in threading headers
[ffmpeg] / libavcodec / wavpack.c
1 /*
2  * WavPack lossless audio decoder
3  * Copyright (c) 2006,2011 Konstantin Shishkov
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * 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  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * 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  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
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 "unary.h"
29 #include "bytestream.h"
30
31 /**
32  * @file
33  * WavPack lossless audio decoder
34  */
35
36 #define WV_HEADER_SIZE    32
37
38 #define WV_MONO           0x00000004
39 #define WV_JOINT_STEREO   0x00000010
40 #define WV_FALSE_STEREO   0x40000000
41
42 #define WV_HYBRID_MODE    0x00000008
43 #define WV_HYBRID_SHAPE   0x00000008
44 #define WV_HYBRID_BITRATE 0x00000200
45 #define WV_HYBRID_BALANCE 0x00000400
46
47 #define WV_FLT_SHIFT_ONES 0x01
48 #define WV_FLT_SHIFT_SAME 0x02
49 #define WV_FLT_SHIFT_SENT 0x04
50 #define WV_FLT_ZERO_SENT  0x08
51 #define WV_FLT_ZERO_SIGN  0x10
52
53 #define WV_MAX_SAMPLES    131072
54
55 enum WP_ID_Flags {
56     WP_IDF_MASK   = 0x1F,
57     WP_IDF_IGNORE = 0x20,
58     WP_IDF_ODD    = 0x40,
59     WP_IDF_LONG   = 0x80
60 };
61
62 enum WP_ID {
63     WP_ID_DUMMY = 0,
64     WP_ID_ENCINFO,
65     WP_ID_DECTERMS,
66     WP_ID_DECWEIGHTS,
67     WP_ID_DECSAMPLES,
68     WP_ID_ENTROPY,
69     WP_ID_HYBRID,
70     WP_ID_SHAPING,
71     WP_ID_FLOATINFO,
72     WP_ID_INT32INFO,
73     WP_ID_DATA,
74     WP_ID_CORR,
75     WP_ID_EXTRABITS,
76     WP_ID_CHANINFO
77 };
78
79 typedef struct SavedContext {
80     int offset;
81     int size;
82     int bits_used;
83     uint32_t crc;
84 } SavedContext;
85
86 #define MAX_TERMS 16
87
88 typedef struct Decorr {
89     int delta;
90     int value;
91     int weightA;
92     int weightB;
93     int samplesA[8];
94     int samplesB[8];
95 } Decorr;
96
97 typedef struct WvChannel {
98     int median[3];
99     int slow_level, error_limit;
100     int bitrate_acc, bitrate_delta;
101 } WvChannel;
102
103 typedef struct WavpackFrameContext {
104     AVCodecContext *avctx;
105     int frame_flags;
106     int stereo, stereo_in;
107     int joint;
108     uint32_t CRC;
109     GetBitContext gb;
110     int got_extra_bits;
111     uint32_t crc_extra_bits;
112     GetBitContext gb_extra_bits;
113     int data_size; // in bits
114     int samples;
115     int terms;
116     Decorr decorr[MAX_TERMS];
117     int zero, one, zeroes;
118     int extra_bits;
119     int and, or, shift;
120     int post_shift;
121     int hybrid, hybrid_bitrate;
122     int hybrid_maxclip, hybrid_minclip;
123     int float_flag;
124     int float_shift;
125     int float_max_exp;
126     WvChannel ch[2];
127     int pos;
128     SavedContext sc, extra_sc;
129 } WavpackFrameContext;
130
131 #define WV_MAX_FRAME_DECODERS 14
132
133 typedef struct WavpackContext {
134     AVCodecContext *avctx;
135
136     WavpackFrameContext *fdec[WV_MAX_FRAME_DECODERS];
137     int fdec_num;
138
139     int multichannel;
140     int block;
141     int samples;
142     int ch_offset;
143 } WavpackContext;
144
145 // exponent table copied from WavPack source
146 static const uint8_t wp_exp2_table[256] = {
147     0x00, 0x01, 0x01, 0x02, 0x03, 0x03, 0x04, 0x05, 0x06, 0x06, 0x07, 0x08, 0x08, 0x09, 0x0a, 0x0b,
148     0x0b, 0x0c, 0x0d, 0x0e, 0x0e, 0x0f, 0x10, 0x10, 0x11, 0x12, 0x13, 0x13, 0x14, 0x15, 0x16, 0x16,
149     0x17, 0x18, 0x19, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1d, 0x1e, 0x1f, 0x20, 0x20, 0x21, 0x22, 0x23,
150     0x24, 0x24, 0x25, 0x26, 0x27, 0x28, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
151     0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3a, 0x3b, 0x3c, 0x3d,
152     0x3e, 0x3f, 0x40, 0x41, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x48, 0x49, 0x4a, 0x4b,
153     0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a,
154     0x5b, 0x5c, 0x5d, 0x5e, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
155     0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
156     0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x87, 0x88, 0x89, 0x8a,
157     0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b,
158     0x9c, 0x9d, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad,
159     0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0,
160     0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc8, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf, 0xd0, 0xd2, 0xd3, 0xd4,
161     0xd6, 0xd7, 0xd8, 0xd9, 0xdb, 0xdc, 0xdd, 0xde, 0xe0, 0xe1, 0xe2, 0xe4, 0xe5, 0xe6, 0xe8, 0xe9,
162     0xea, 0xec, 0xed, 0xee, 0xf0, 0xf1, 0xf2, 0xf4, 0xf5, 0xf6, 0xf8, 0xf9, 0xfa, 0xfc, 0xfd, 0xff
163 };
164
165 static const uint8_t wp_log2_table [] = {
166     0x00, 0x01, 0x03, 0x04, 0x06, 0x07, 0x09, 0x0a, 0x0b, 0x0d, 0x0e, 0x10, 0x11, 0x12, 0x14, 0x15,
167     0x16, 0x18, 0x19, 0x1a, 0x1c, 0x1d, 0x1e, 0x20, 0x21, 0x22, 0x24, 0x25, 0x26, 0x28, 0x29, 0x2a,
168     0x2c, 0x2d, 0x2e, 0x2f, 0x31, 0x32, 0x33, 0x34, 0x36, 0x37, 0x38, 0x39, 0x3b, 0x3c, 0x3d, 0x3e,
169     0x3f, 0x41, 0x42, 0x43, 0x44, 0x45, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4d, 0x4e, 0x4f, 0x50, 0x51,
170     0x52, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63,
171     0x64, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x74, 0x75,
172     0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85,
173     0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95,
174     0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4,
175     0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb2,
176     0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc0,
177     0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcb, 0xcc, 0xcd, 0xce,
178     0xcf, 0xd0, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd8, 0xd9, 0xda, 0xdb,
179     0xdc, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe4, 0xe5, 0xe6, 0xe7, 0xe7,
180     0xe8, 0xe9, 0xea, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xee, 0xef, 0xf0, 0xf1, 0xf1, 0xf2, 0xf3, 0xf4,
181     0xf4, 0xf5, 0xf6, 0xf7, 0xf7, 0xf8, 0xf9, 0xf9, 0xfa, 0xfb, 0xfc, 0xfc, 0xfd, 0xfe, 0xff, 0xff
182 };
183
184 static av_always_inline int wp_exp2(int16_t val)
185 {
186     int res, neg = 0;
187
188     if (val < 0) {
189         val = -val;
190         neg = 1;
191     }
192
193     res   = wp_exp2_table[val & 0xFF] | 0x100;
194     val >>= 8;
195     res   = (val > 9) ? (res << (val - 9)) : (res >> (9 - val));
196     return neg ? -res : res;
197 }
198
199 static av_always_inline int wp_log2(int32_t val)
200 {
201     int bits;
202
203     if (!val)
204         return 0;
205     if (val == 1)
206         return 256;
207     val += val >> 9;
208     bits = av_log2(val) + 1;
209     if (bits < 9)
210         return (bits << 8) + wp_log2_table[(val << (9 - bits)) & 0xFF];
211     else
212         return (bits << 8) + wp_log2_table[(val >> (bits - 9)) & 0xFF];
213 }
214
215 #define LEVEL_DECAY(a)  ((a + 0x80) >> 8)
216
217 // macros for manipulating median values
218 #define GET_MED(n) ((c->median[n] >> 4) + 1)
219 #define DEC_MED(n) c->median[n] -= ((c->median[n] + (128 >> n) - 2) / (128 >> n)) * 2
220 #define INC_MED(n) c->median[n] += ((c->median[n] + (128 >> n)    ) / (128 >> n)) * 5
221
222 // macros for applying weight
223 #define UPDATE_WEIGHT_CLIP(weight, delta, samples, in) \
224     if (samples && in) { \
225         if ((samples ^ in) < 0) { \
226             weight -= delta; \
227             if (weight < -1024) \
228                 weight = -1024; \
229         } else { \
230             weight += delta; \
231             if (weight > 1024) \
232                 weight = 1024; \
233         } \
234     }
235
236 static av_always_inline int get_tail(GetBitContext *gb, int k)
237 {
238     int p, e, res;
239
240     if (k < 1)
241         return 0;
242     p   = av_log2(k);
243     e   = (1 << (p + 1)) - k - 1;
244     res = p ? get_bits(gb, p) : 0;
245     if (res >= e)
246         res = (res << 1) - e + get_bits1(gb);
247     return res;
248 }
249
250 static void update_error_limit(WavpackFrameContext *ctx)
251 {
252     int i, br[2], sl[2];
253
254     for (i = 0; i <= ctx->stereo_in; i++) {
255         ctx->ch[i].bitrate_acc += ctx->ch[i].bitrate_delta;
256         br[i]                   = ctx->ch[i].bitrate_acc >> 16;
257         sl[i]                   = LEVEL_DECAY(ctx->ch[i].slow_level);
258     }
259     if (ctx->stereo_in && ctx->hybrid_bitrate) {
260         int balance = (sl[1] - sl[0] + br[1] + 1) >> 1;
261         if (balance > br[0]) {
262             br[1] = br[0] << 1;
263             br[0] = 0;
264         } else if (-balance > br[0]) {
265             br[0] <<= 1;
266             br[1]   = 0;
267         } else {
268             br[1] = br[0] + balance;
269             br[0] = br[0] - balance;
270         }
271     }
272     for (i = 0; i <= ctx->stereo_in; i++) {
273         if (ctx->hybrid_bitrate) {
274             if (sl[i] - br[i] > -0x100)
275                 ctx->ch[i].error_limit = wp_exp2(sl[i] - br[i] + 0x100);
276             else
277                 ctx->ch[i].error_limit = 0;
278         } else {
279             ctx->ch[i].error_limit = wp_exp2(br[i]);
280         }
281     }
282 }
283
284 static int wv_get_value(WavpackFrameContext *ctx, GetBitContext *gb,
285                         int channel, int *last)
286 {
287     int t, t2;
288     int sign, base, add, ret;
289     WvChannel *c = &ctx->ch[channel];
290
291     *last = 0;
292
293     if ((ctx->ch[0].median[0] < 2U) && (ctx->ch[1].median[0] < 2U) &&
294         !ctx->zero && !ctx->one) {
295         if (ctx->zeroes) {
296             ctx->zeroes--;
297             if (ctx->zeroes) {
298                 c->slow_level -= LEVEL_DECAY(c->slow_level);
299                 return 0;
300             }
301         } else {
302             t = get_unary_0_33(gb);
303             if (t >= 2) {
304                 if (get_bits_left(gb) < t - 1)
305                     goto error;
306                 t = get_bits(gb, t - 1) | (1 << (t - 1));
307             } else {
308                 if (get_bits_left(gb) < 0)
309                     goto error;
310             }
311             ctx->zeroes = t;
312             if (ctx->zeroes) {
313                 memset(ctx->ch[0].median, 0, sizeof(ctx->ch[0].median));
314                 memset(ctx->ch[1].median, 0, sizeof(ctx->ch[1].median));
315                 c->slow_level -= LEVEL_DECAY(c->slow_level);
316                 return 0;
317             }
318         }
319     }
320
321     if (ctx->zero) {
322         t         = 0;
323         ctx->zero = 0;
324     } else {
325         t = get_unary_0_33(gb);
326         if (get_bits_left(gb) < 0)
327             goto error;
328         if (t == 16) {
329             t2 = get_unary_0_33(gb);
330             if (t2 < 2) {
331                 if (get_bits_left(gb) < 0)
332                     goto error;
333                 t += t2;
334             } else {
335                 if (get_bits_left(gb) < t2 - 1)
336                     goto error;
337                 t += get_bits(gb, t2 - 1) | (1 << (t2 - 1));
338             }
339         }
340
341         if (ctx->one) {
342             ctx->one = t & 1;
343             t        = (t >> 1) + 1;
344         } else {
345             ctx->one = t & 1;
346             t      >>= 1;
347         }
348         ctx->zero = !ctx->one;
349     }
350
351     if (ctx->hybrid && !channel)
352         update_error_limit(ctx);
353
354     if (!t) {
355         base = 0;
356         add  = GET_MED(0) - 1;
357         DEC_MED(0);
358     } else if (t == 1) {
359         base = GET_MED(0);
360         add  = GET_MED(1) - 1;
361         INC_MED(0);
362         DEC_MED(1);
363     } else if (t == 2) {
364         base = GET_MED(0) + GET_MED(1);
365         add  = GET_MED(2) - 1;
366         INC_MED(0);
367         INC_MED(1);
368         DEC_MED(2);
369     } else {
370         base = GET_MED(0) + GET_MED(1) + GET_MED(2) * (t - 2);
371         add  = GET_MED(2) - 1;
372         INC_MED(0);
373         INC_MED(1);
374         INC_MED(2);
375     }
376     if (!c->error_limit) {
377         if (add >= 0x2000000U) {
378             av_log(ctx->avctx, AV_LOG_ERROR, "k %d is too large\n", add);
379             goto error;
380         }
381         ret = base + get_tail(gb, add);
382         if (get_bits_left(gb) <= 0)
383             goto error;
384     } else {
385         int mid = (base * 2 + add + 1) >> 1;
386         while (add > c->error_limit) {
387             if (get_bits_left(gb) <= 0)
388                 goto error;
389             if (get_bits1(gb)) {
390                 add -= (mid - base);
391                 base = mid;
392             } else
393                 add = mid - base - 1;
394             mid = (base * 2 + add + 1) >> 1;
395         }
396         ret = mid;
397     }
398     sign = get_bits1(gb);
399     if (ctx->hybrid_bitrate)
400         c->slow_level += wp_log2(ret) - LEVEL_DECAY(c->slow_level);
401     return sign ? ~ret : ret;
402
403 error:
404     *last = 1;
405     return 0;
406 }
407
408 static inline int wv_get_value_integer(WavpackFrameContext *s, uint32_t *crc,
409                                        int S)
410 {
411     int bit;
412
413     if (s->extra_bits) {
414         S <<= s->extra_bits;
415
416         if (s->got_extra_bits &&
417             get_bits_left(&s->gb_extra_bits) >= s->extra_bits) {
418             S   |= get_bits(&s->gb_extra_bits, s->extra_bits);
419             *crc = *crc * 9 + (S & 0xffff) * 3 + ((unsigned)S >> 16);
420         }
421     }
422
423     bit = (S & s->and) | s->or;
424     bit = ((S + bit) << s->shift) - bit;
425
426     if (s->hybrid)
427         bit = av_clip(bit, s->hybrid_minclip, s->hybrid_maxclip);
428
429     return bit << s->post_shift;
430 }
431
432 static float wv_get_value_float(WavpackFrameContext *s, uint32_t *crc, int S)
433 {
434     union {
435         float    f;
436         uint32_t u;
437     } value;
438
439     unsigned int sign;
440     int exp = s->float_max_exp;
441
442     if (s->got_extra_bits) {
443         const int max_bits  = 1 + 23 + 8 + 1;
444         const int left_bits = get_bits_left(&s->gb_extra_bits);
445
446         if (left_bits + 8 * FF_INPUT_BUFFER_PADDING_SIZE < max_bits)
447             return 0.0;
448     }
449
450     if (S) {
451         S  <<= s->float_shift;
452         sign = S < 0;
453         if (sign)
454             S = -S;
455         if (S >= 0x1000000) {
456             if (s->got_extra_bits && get_bits1(&s->gb_extra_bits))
457                 S = get_bits(&s->gb_extra_bits, 23);
458             else
459                 S = 0;
460             exp = 255;
461         } else if (exp) {
462             int shift = 23 - av_log2(S);
463             exp = s->float_max_exp;
464             if (exp <= shift)
465                 shift = --exp;
466             exp -= shift;
467
468             if (shift) {
469                 S <<= shift;
470                 if ((s->float_flag & WV_FLT_SHIFT_ONES) ||
471                     (s->got_extra_bits &&
472                      (s->float_flag & WV_FLT_SHIFT_SAME) &&
473                      get_bits1(&s->gb_extra_bits))) {
474                     S |= (1 << shift) - 1;
475                 } else if (s->got_extra_bits &&
476                            (s->float_flag & WV_FLT_SHIFT_SENT)) {
477                     S |= get_bits(&s->gb_extra_bits, shift);
478                 }
479             }
480         } else {
481             exp = s->float_max_exp;
482         }
483         S &= 0x7fffff;
484     } else {
485         sign = 0;
486         exp  = 0;
487         if (s->got_extra_bits && (s->float_flag & WV_FLT_ZERO_SENT)) {
488             if (get_bits1(&s->gb_extra_bits)) {
489                 S = get_bits(&s->gb_extra_bits, 23);
490                 if (s->float_max_exp >= 25)
491                     exp = get_bits(&s->gb_extra_bits, 8);
492                 sign = get_bits1(&s->gb_extra_bits);
493             } else {
494                 if (s->float_flag & WV_FLT_ZERO_SIGN)
495                     sign = get_bits1(&s->gb_extra_bits);
496             }
497         }
498     }
499
500     *crc = *crc * 27 + S * 9 + exp * 3 + sign;
501
502     value.u = (sign << 31) | (exp << 23) | S;
503     return value.f;
504 }
505
506 static void wv_reset_saved_context(WavpackFrameContext *s)
507 {
508     s->pos    = 0;
509     s->sc.crc = s->extra_sc.crc = 0xFFFFFFFF;
510 }
511
512 static inline int wv_check_crc(WavpackFrameContext *s, uint32_t crc,
513                                uint32_t crc_extra_bits)
514 {
515     if (crc != s->CRC) {
516         av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
517         return AVERROR_INVALIDDATA;
518     }
519     if (s->got_extra_bits && crc_extra_bits != s->crc_extra_bits) {
520         av_log(s->avctx, AV_LOG_ERROR, "Extra bits CRC error\n");
521         return AVERROR_INVALIDDATA;
522     }
523
524     return 0;
525 }
526
527 static inline int wv_unpack_stereo(WavpackFrameContext *s, GetBitContext *gb,
528                                    void *dst_l, void *dst_r, const int type)
529 {
530     int i, j, count = 0;
531     int last, t;
532     int A, B, L, L2, R, R2;
533     int pos                 = s->pos;
534     uint32_t crc            = s->sc.crc;
535     uint32_t crc_extra_bits = s->extra_sc.crc;
536     int16_t *dst16_l        = dst_l;
537     int16_t *dst16_r        = dst_r;
538     int32_t *dst32_l        = dst_l;
539     int32_t *dst32_r        = dst_r;
540     float *dstfl_l          = dst_l;
541     float *dstfl_r          = dst_r;
542
543     s->one = s->zero = s->zeroes = 0;
544     do {
545         L = wv_get_value(s, gb, 0, &last);
546         if (last)
547             break;
548         R = wv_get_value(s, gb, 1, &last);
549         if (last)
550             break;
551         for (i = 0; i < s->terms; i++) {
552             t = s->decorr[i].value;
553             if (t > 0) {
554                 if (t > 8) {
555                     if (t & 1) {
556                         A = 2 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
557                         B = 2 * s->decorr[i].samplesB[0] - s->decorr[i].samplesB[1];
558                     } else {
559                         A = (3 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1]) >> 1;
560                         B = (3 * s->decorr[i].samplesB[0] - s->decorr[i].samplesB[1]) >> 1;
561                     }
562                     s->decorr[i].samplesA[1] = s->decorr[i].samplesA[0];
563                     s->decorr[i].samplesB[1] = s->decorr[i].samplesB[0];
564                     j                        = 0;
565                 } else {
566                     A = s->decorr[i].samplesA[pos];
567                     B = s->decorr[i].samplesB[pos];
568                     j = (pos + t) & 7;
569                 }
570                 if (type != AV_SAMPLE_FMT_S16P) {
571                     L2 = L + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
572                     R2 = R + ((s->decorr[i].weightB * (int64_t)B + 512) >> 10);
573                 } else {
574                     L2 = L + ((s->decorr[i].weightA * A + 512) >> 10);
575                     R2 = R + ((s->decorr[i].weightB * B + 512) >> 10);
576                 }
577                 if (A && L)
578                     s->decorr[i].weightA -= ((((L ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
579                 if (B && R)
580                     s->decorr[i].weightB -= ((((R ^ B) >> 30) & 2) - 1) * s->decorr[i].delta;
581                 s->decorr[i].samplesA[j] = L = L2;
582                 s->decorr[i].samplesB[j] = R = R2;
583             } else if (t == -1) {
584                 if (type != AV_SAMPLE_FMT_S16P)
585                     L2 = L + ((s->decorr[i].weightA * (int64_t)s->decorr[i].samplesA[0] + 512) >> 10);
586                 else
587                     L2 = L + ((s->decorr[i].weightA * s->decorr[i].samplesA[0] + 512) >> 10);
588                 UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, s->decorr[i].samplesA[0], L);
589                 L = L2;
590                 if (type != AV_SAMPLE_FMT_S16P)
591                     R2 = R + ((s->decorr[i].weightB * (int64_t)L2 + 512) >> 10);
592                 else
593                     R2 = R + ((s->decorr[i].weightB * L2 + 512) >> 10);
594                 UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, L2, R);
595                 R                        = R2;
596                 s->decorr[i].samplesA[0] = R;
597             } else {
598                 if (type != AV_SAMPLE_FMT_S16P)
599                     R2 = R + ((s->decorr[i].weightB * (int64_t)s->decorr[i].samplesB[0] + 512) >> 10);
600                 else
601                     R2 = R + ((s->decorr[i].weightB * s->decorr[i].samplesB[0] + 512) >> 10);
602                 UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, s->decorr[i].samplesB[0], R);
603                 R = R2;
604
605                 if (t == -3) {
606                     R2                       = s->decorr[i].samplesA[0];
607                     s->decorr[i].samplesA[0] = R;
608                 }
609
610                 if (type != AV_SAMPLE_FMT_S16P)
611                     L2 = L + ((s->decorr[i].weightA * (int64_t)R2 + 512) >> 10);
612                 else
613                     L2 = L + ((s->decorr[i].weightA * R2 + 512) >> 10);
614                 UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, R2, L);
615                 L                        = L2;
616                 s->decorr[i].samplesB[0] = L;
617             }
618         }
619         pos = (pos + 1) & 7;
620         if (s->joint)
621             L += (R -= (L >> 1));
622         crc = (crc * 3 + L) * 3 + R;
623
624         if (type == AV_SAMPLE_FMT_FLTP) {
625             *dstfl_l++ = wv_get_value_float(s, &crc_extra_bits, L);
626             *dstfl_r++ = wv_get_value_float(s, &crc_extra_bits, R);
627         } else if (type == AV_SAMPLE_FMT_S32P) {
628             *dst32_l++ = wv_get_value_integer(s, &crc_extra_bits, L);
629             *dst32_r++ = wv_get_value_integer(s, &crc_extra_bits, R);
630         } else {
631             *dst16_l++ = wv_get_value_integer(s, &crc_extra_bits, L);
632             *dst16_r++ = wv_get_value_integer(s, &crc_extra_bits, R);
633         }
634         count++;
635     } while (!last && count < s->samples);
636
637     wv_reset_saved_context(s);
638     if ((s->avctx->err_recognition & AV_EF_CRCCHECK) &&
639         wv_check_crc(s, crc, crc_extra_bits))
640         return AVERROR_INVALIDDATA;
641
642     return 0;
643 }
644
645 static inline int wv_unpack_mono(WavpackFrameContext *s, GetBitContext *gb,
646                                  void *dst, const int type)
647 {
648     int i, j, count = 0;
649     int last, t;
650     int A, S, T;
651     int pos                  = s->pos;
652     uint32_t crc             = s->sc.crc;
653     uint32_t crc_extra_bits  = s->extra_sc.crc;
654     int16_t *dst16           = dst;
655     int32_t *dst32           = dst;
656     float *dstfl             = dst;
657
658     s->one = s->zero = s->zeroes = 0;
659     do {
660         T = wv_get_value(s, gb, 0, &last);
661         S = 0;
662         if (last)
663             break;
664         for (i = 0; i < s->terms; i++) {
665             t = s->decorr[i].value;
666             if (t > 8) {
667                 if (t & 1)
668                     A =  2 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
669                 else
670                     A = (3 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1]) >> 1;
671                 s->decorr[i].samplesA[1] = s->decorr[i].samplesA[0];
672                 j                        = 0;
673             } else {
674                 A = s->decorr[i].samplesA[pos];
675                 j = (pos + t) & 7;
676             }
677             if (type != AV_SAMPLE_FMT_S16P)
678                 S = T + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
679             else
680                 S = T + ((s->decorr[i].weightA * A + 512) >> 10);
681             if (A && T)
682                 s->decorr[i].weightA -= ((((T ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
683             s->decorr[i].samplesA[j] = T = S;
684         }
685         pos = (pos + 1) & 7;
686         crc = crc * 3 + S;
687
688         if (type == AV_SAMPLE_FMT_FLTP) {
689             *dstfl++ = wv_get_value_float(s, &crc_extra_bits, S);
690         } else if (type == AV_SAMPLE_FMT_S32P) {
691             *dst32++ = wv_get_value_integer(s, &crc_extra_bits, S);
692         } else {
693             *dst16++ = wv_get_value_integer(s, &crc_extra_bits, S);
694         }
695         count++;
696     } while (!last && count < s->samples);
697
698     wv_reset_saved_context(s);
699     if ((s->avctx->err_recognition & AV_EF_CRCCHECK) &&
700         wv_check_crc(s, crc, crc_extra_bits))
701         return AVERROR_INVALIDDATA;
702
703     return 0;
704 }
705
706 static av_cold int wv_alloc_frame_context(WavpackContext *c)
707 {
708     if (c->fdec_num == WV_MAX_FRAME_DECODERS)
709         return -1;
710
711     c->fdec[c->fdec_num] = av_mallocz(sizeof(**c->fdec));
712     if (!c->fdec[c->fdec_num])
713         return -1;
714     c->fdec_num++;
715     c->fdec[c->fdec_num - 1]->avctx = c->avctx;
716     wv_reset_saved_context(c->fdec[c->fdec_num - 1]);
717
718     return 0;
719 }
720
721 static av_cold int wavpack_decode_init(AVCodecContext *avctx)
722 {
723     WavpackContext *s = avctx->priv_data;
724
725     s->avctx = avctx;
726
727     if (avctx->channels <= 2 && !avctx->channel_layout)
728         avctx->channel_layout = (avctx->channels == 2) ? AV_CH_LAYOUT_STEREO
729                                                        : AV_CH_LAYOUT_MONO;
730
731     s->multichannel = avctx->channels > 2;
732
733     s->fdec_num = 0;
734
735     return 0;
736 }
737
738 static av_cold int wavpack_decode_end(AVCodecContext *avctx)
739 {
740     WavpackContext *s = avctx->priv_data;
741     int i;
742
743     for (i = 0; i < s->fdec_num; i++)
744         av_freep(&s->fdec[i]);
745     s->fdec_num = 0;
746
747     return 0;
748 }
749
750 static int wavpack_decode_block(AVCodecContext *avctx, int block_no,
751                                 uint8_t **data, const uint8_t *buf, int buf_size)
752 {
753     WavpackContext *wc = avctx->priv_data;
754     WavpackFrameContext *s;
755     GetByteContext gb;
756     void *samples_l, *samples_r;
757     int ret;
758     int got_terms   = 0, got_weights = 0, got_samples = 0,
759         got_entropy = 0, got_bs      = 0, got_float   = 0, got_hybrid = 0;
760     int i, j, id, size, ssize, weights, t;
761     int bpp, chan, chmask, orig_bpp;
762
763     if (block_no >= wc->fdec_num && wv_alloc_frame_context(wc) < 0) {
764         av_log(avctx, AV_LOG_ERROR, "Error creating frame decode context\n");
765         return AVERROR_INVALIDDATA;
766     }
767
768     s = wc->fdec[block_no];
769     if (!s) {
770         av_log(avctx, AV_LOG_ERROR, "Context for block %d is not present\n",
771                block_no);
772         return AVERROR_INVALIDDATA;
773     }
774
775     memset(s->decorr, 0, MAX_TERMS * sizeof(Decorr));
776     memset(s->ch, 0, sizeof(s->ch));
777     s->extra_bits     = 0;
778     s->and            = s->or = s->shift = 0;
779     s->got_extra_bits = 0;
780
781     bytestream2_init(&gb, buf, buf_size);
782
783     s->samples = bytestream2_get_le32(&gb);
784     if (s->samples != wc->samples) {
785         av_log(avctx, AV_LOG_ERROR, "Mismatching number of samples in "
786                "a sequence: %d and %d\n", wc->samples, s->samples);
787         return AVERROR_INVALIDDATA;
788     }
789     s->frame_flags = bytestream2_get_le32(&gb);
790     bpp            = av_get_bytes_per_sample(avctx->sample_fmt);
791     orig_bpp       = ((s->frame_flags & 0x03) + 1) << 3;
792
793     s->stereo         = !(s->frame_flags & WV_MONO);
794     s->stereo_in      =  (s->frame_flags & WV_FALSE_STEREO) ? 0 : s->stereo;
795     s->joint          =   s->frame_flags & WV_JOINT_STEREO;
796     s->hybrid         =   s->frame_flags & WV_HYBRID_MODE;
797     s->hybrid_bitrate =   s->frame_flags & WV_HYBRID_BITRATE;
798     s->post_shift     = bpp * 8 - orig_bpp + ((s->frame_flags >> 13) & 0x1f);
799     s->hybrid_maxclip =  ((1LL << (orig_bpp - 1)) - 1);
800     s->hybrid_minclip = ((-1LL << (orig_bpp - 1)));
801     s->CRC            = bytestream2_get_le32(&gb);
802
803     if (wc->ch_offset + s->stereo >= avctx->channels) {
804         av_log(avctx, AV_LOG_ERROR, "too many channels\n");
805         return -1;
806     }
807
808     samples_l = data[wc->ch_offset];
809     if (s->stereo)
810         samples_r = data[wc->ch_offset + 1];
811
812     wc->ch_offset += 1 + s->stereo;
813
814     // parse metadata blocks
815     while (bytestream2_get_bytes_left(&gb)) {
816         id   = bytestream2_get_byte(&gb);
817         size = bytestream2_get_byte(&gb);
818         if (id & WP_IDF_LONG) {
819             size |= (bytestream2_get_byte(&gb)) << 8;
820             size |= (bytestream2_get_byte(&gb)) << 16;
821         }
822         size <<= 1; // size is specified in words
823         ssize  = size;
824         if (id & WP_IDF_ODD)
825             size--;
826         if (size < 0) {
827             av_log(avctx, AV_LOG_ERROR,
828                    "Got incorrect block %02X with size %i\n", id, size);
829             break;
830         }
831         if (bytestream2_get_bytes_left(&gb) < ssize) {
832             av_log(avctx, AV_LOG_ERROR,
833                    "Block size %i is out of bounds\n", size);
834             break;
835         }
836         if (id & WP_IDF_IGNORE) {
837             bytestream2_skip(&gb, ssize);
838             continue;
839         }
840         switch (id & WP_IDF_MASK) {
841         case WP_ID_DECTERMS:
842             if (size > MAX_TERMS) {
843                 av_log(avctx, AV_LOG_ERROR, "Too many decorrelation terms\n");
844                 s->terms = 0;
845                 bytestream2_skip(&gb, ssize);
846                 continue;
847             }
848             s->terms = size;
849             for (i = 0; i < s->terms; i++) {
850                 uint8_t val = bytestream2_get_byte(&gb);
851                 s->decorr[s->terms - i - 1].value = (val & 0x1F) - 5;
852                 s->decorr[s->terms - i - 1].delta =  val >> 5;
853             }
854             got_terms = 1;
855             break;
856         case WP_ID_DECWEIGHTS:
857             if (!got_terms) {
858                 av_log(avctx, AV_LOG_ERROR, "No decorrelation terms met\n");
859                 continue;
860             }
861             weights = size >> s->stereo_in;
862             if (weights > MAX_TERMS || weights > s->terms) {
863                 av_log(avctx, AV_LOG_ERROR, "Too many decorrelation weights\n");
864                 bytestream2_skip(&gb, ssize);
865                 continue;
866             }
867             for (i = 0; i < weights; i++) {
868                 t = (int8_t)bytestream2_get_byte(&gb);
869                 s->decorr[s->terms - i - 1].weightA = t << 3;
870                 if (s->decorr[s->terms - i - 1].weightA > 0)
871                     s->decorr[s->terms - i - 1].weightA +=
872                         (s->decorr[s->terms - i - 1].weightA + 64) >> 7;
873                 if (s->stereo_in) {
874                     t = (int8_t)bytestream2_get_byte(&gb);
875                     s->decorr[s->terms - i - 1].weightB = t << 3;
876                     if (s->decorr[s->terms - i - 1].weightB > 0)
877                         s->decorr[s->terms - i - 1].weightB +=
878                             (s->decorr[s->terms - i - 1].weightB + 64) >> 7;
879                 }
880             }
881             got_weights = 1;
882             break;
883         case WP_ID_DECSAMPLES:
884             if (!got_terms) {
885                 av_log(avctx, AV_LOG_ERROR, "No decorrelation terms met\n");
886                 continue;
887             }
888             t = 0;
889             for (i = s->terms - 1; (i >= 0) && (t < size); i--) {
890                 if (s->decorr[i].value > 8) {
891                     s->decorr[i].samplesA[0] =
892                         wp_exp2(bytestream2_get_le16(&gb));
893                     s->decorr[i].samplesA[1] =
894                         wp_exp2(bytestream2_get_le16(&gb));
895
896                     if (s->stereo_in) {
897                         s->decorr[i].samplesB[0] =
898                             wp_exp2(bytestream2_get_le16(&gb));
899                         s->decorr[i].samplesB[1] =
900                             wp_exp2(bytestream2_get_le16(&gb));
901                         t                       += 4;
902                     }
903                     t += 4;
904                 } else if (s->decorr[i].value < 0) {
905                     s->decorr[i].samplesA[0] =
906                         wp_exp2(bytestream2_get_le16(&gb));
907                     s->decorr[i].samplesB[0] =
908                         wp_exp2(bytestream2_get_le16(&gb));
909                     t                       += 4;
910                 } else {
911                     for (j = 0; j < s->decorr[i].value; j++) {
912                         s->decorr[i].samplesA[j] =
913                             wp_exp2(bytestream2_get_le16(&gb));
914                         if (s->stereo_in) {
915                             s->decorr[i].samplesB[j] =
916                                 wp_exp2(bytestream2_get_le16(&gb));
917                         }
918                     }
919                     t += s->decorr[i].value * 2 * (s->stereo_in + 1);
920                 }
921             }
922             got_samples = 1;
923             break;
924         case WP_ID_ENTROPY:
925             if (size != 6 * (s->stereo_in + 1)) {
926                 av_log(avctx, AV_LOG_ERROR,
927                        "Entropy vars size should be %i, got %i",
928                        6 * (s->stereo_in + 1), size);
929                 bytestream2_skip(&gb, ssize);
930                 continue;
931             }
932             for (j = 0; j <= s->stereo_in; j++)
933                 for (i = 0; i < 3; i++) {
934                     s->ch[j].median[i] = wp_exp2(bytestream2_get_le16(&gb));
935                 }
936             got_entropy = 1;
937             break;
938         case WP_ID_HYBRID:
939             if (s->hybrid_bitrate) {
940                 for (i = 0; i <= s->stereo_in; i++) {
941                     s->ch[i].slow_level = wp_exp2(bytestream2_get_le16(&gb));
942                     size               -= 2;
943                 }
944             }
945             for (i = 0; i < (s->stereo_in + 1); i++) {
946                 s->ch[i].bitrate_acc = bytestream2_get_le16(&gb) << 16;
947                 size                -= 2;
948             }
949             if (size > 0) {
950                 for (i = 0; i < (s->stereo_in + 1); i++) {
951                     s->ch[i].bitrate_delta =
952                         wp_exp2((int16_t)bytestream2_get_le16(&gb));
953                 }
954             } else {
955                 for (i = 0; i < (s->stereo_in + 1); i++)
956                     s->ch[i].bitrate_delta = 0;
957             }
958             got_hybrid = 1;
959             break;
960         case WP_ID_INT32INFO: {
961             uint8_t val[4];
962             if (size != 4) {
963                 av_log(avctx, AV_LOG_ERROR,
964                        "Invalid INT32INFO, size = %i\n",
965                        size);
966                 bytestream2_skip(&gb, ssize - 4);
967                 continue;
968             }
969             bytestream2_get_buffer(&gb, val, 4);
970             if (val[0]) {
971                 s->extra_bits = val[0];
972             } else if (val[1]) {
973                 s->shift = val[1];
974             } else if (val[2]) {
975                 s->and   = s->or = 1;
976                 s->shift = val[2];
977             } else if (val[3]) {
978                 s->and   = 1;
979                 s->shift = val[3];
980             }
981             /* original WavPack decoder forces 32-bit lossy sound to be treated
982              * as 24-bit one in order to have proper clipping */
983             if (s->hybrid && bpp == 4 && s->post_shift < 8 && s->shift > 8) {
984                 s->post_shift      += 8;
985                 s->shift           -= 8;
986                 s->hybrid_maxclip >>= 8;
987                 s->hybrid_minclip >>= 8;
988             }
989             break;
990         }
991         case WP_ID_FLOATINFO:
992             if (size != 4) {
993                 av_log(avctx, AV_LOG_ERROR,
994                        "Invalid FLOATINFO, size = %i\n", size);
995                 bytestream2_skip(&gb, ssize);
996                 continue;
997             }
998             s->float_flag    = bytestream2_get_byte(&gb);
999             s->float_shift   = bytestream2_get_byte(&gb);
1000             s->float_max_exp = bytestream2_get_byte(&gb);
1001             got_float        = 1;
1002             bytestream2_skip(&gb, 1);
1003             break;
1004         case WP_ID_DATA:
1005             s->sc.offset = bytestream2_tell(&gb);
1006             s->sc.size   = size * 8;
1007             init_get_bits(&s->gb, gb.buffer, size * 8);
1008             s->data_size = size * 8;
1009             bytestream2_skip(&gb, size);
1010             got_bs       = 1;
1011             break;
1012         case WP_ID_EXTRABITS:
1013             if (size <= 4) {
1014                 av_log(avctx, AV_LOG_ERROR, "Invalid EXTRABITS, size = %i\n",
1015                        size);
1016                 bytestream2_skip(&gb, size);
1017                 continue;
1018             }
1019             s->extra_sc.offset = bytestream2_tell(&gb);
1020             s->extra_sc.size   = size * 8;
1021             init_get_bits(&s->gb_extra_bits, gb.buffer, size * 8);
1022             s->crc_extra_bits  = get_bits_long(&s->gb_extra_bits, 32);
1023             bytestream2_skip(&gb, size);
1024             s->got_extra_bits  = 1;
1025             break;
1026         case WP_ID_CHANINFO:
1027             if (size <= 1) {
1028                 av_log(avctx, AV_LOG_ERROR,
1029                        "Insufficient channel information\n");
1030                 return AVERROR_INVALIDDATA;
1031             }
1032             chan = bytestream2_get_byte(&gb);
1033             switch (size - 2) {
1034             case 0:
1035                 chmask = bytestream2_get_byte(&gb);
1036                 break;
1037             case 1:
1038                 chmask = bytestream2_get_le16(&gb);
1039                 break;
1040             case 2:
1041                 chmask = bytestream2_get_le24(&gb);
1042                 break;
1043             case 3:
1044                 chmask = bytestream2_get_le32(&gb);
1045                 break;
1046             case 5:
1047                 bytestream2_skip(&gb, 1);
1048                 chan  |= (bytestream2_get_byte(&gb) & 0xF) << 8;
1049                 chmask = bytestream2_get_le16(&gb);
1050                 break;
1051             default:
1052                 av_log(avctx, AV_LOG_ERROR, "Invalid channel info size %d\n",
1053                        size);
1054                 chan   = avctx->channels;
1055                 chmask = avctx->channel_layout;
1056             }
1057             if (chan != avctx->channels) {
1058                 av_log(avctx, AV_LOG_ERROR,
1059                        "Block reports total %d channels, "
1060                        "decoder believes it's %d channels\n",
1061                        chan, avctx->channels);
1062                 return AVERROR_INVALIDDATA;
1063             }
1064             if (!avctx->channel_layout)
1065                 avctx->channel_layout = chmask;
1066             break;
1067         default:
1068             bytestream2_skip(&gb, size);
1069         }
1070         if (id & WP_IDF_ODD)
1071             bytestream2_skip(&gb, 1);
1072     }
1073
1074     if (!got_terms) {
1075         av_log(avctx, AV_LOG_ERROR, "No block with decorrelation terms\n");
1076         return AVERROR_INVALIDDATA;
1077     }
1078     if (!got_weights) {
1079         av_log(avctx, AV_LOG_ERROR, "No block with decorrelation weights\n");
1080         return AVERROR_INVALIDDATA;
1081     }
1082     if (!got_samples) {
1083         av_log(avctx, AV_LOG_ERROR, "No block with decorrelation samples\n");
1084         return AVERROR_INVALIDDATA;
1085     }
1086     if (!got_entropy) {
1087         av_log(avctx, AV_LOG_ERROR, "No block with entropy info\n");
1088         return AVERROR_INVALIDDATA;
1089     }
1090     if (s->hybrid && !got_hybrid) {
1091         av_log(avctx, AV_LOG_ERROR, "Hybrid config not found\n");
1092         return AVERROR_INVALIDDATA;
1093     }
1094     if (!got_bs) {
1095         av_log(avctx, AV_LOG_ERROR, "Packed samples not found\n");
1096         return AVERROR_INVALIDDATA;
1097     }
1098     if (!got_float && avctx->sample_fmt == AV_SAMPLE_FMT_FLTP) {
1099         av_log(avctx, AV_LOG_ERROR, "Float information not found\n");
1100         return AVERROR_INVALIDDATA;
1101     }
1102     if (s->got_extra_bits && avctx->sample_fmt != AV_SAMPLE_FMT_FLTP) {
1103         const int size   = get_bits_left(&s->gb_extra_bits);
1104         const int wanted = s->samples * s->extra_bits << s->stereo_in;
1105         if (size < wanted) {
1106             av_log(avctx, AV_LOG_ERROR, "Too small EXTRABITS\n");
1107             s->got_extra_bits = 0;
1108         }
1109     }
1110
1111     if (s->stereo_in) {
1112         ret = wv_unpack_stereo(s, &s->gb, samples_l, samples_r, avctx->sample_fmt);
1113         if (ret < 0)
1114             return ret;
1115     } else {
1116         ret = wv_unpack_mono(s, &s->gb, samples_l, avctx->sample_fmt);
1117         if (ret < 0)
1118             return ret;
1119
1120         if (s->stereo)
1121             memcpy(samples_r, samples_l, bpp * s->samples);
1122     }
1123
1124     return 0;
1125 }
1126
1127 static void wavpack_decode_flush(AVCodecContext *avctx)
1128 {
1129     WavpackContext *s = avctx->priv_data;
1130     int i;
1131
1132     for (i = 0; i < s->fdec_num; i++)
1133         wv_reset_saved_context(s->fdec[i]);
1134 }
1135
1136 static int wavpack_decode_frame(AVCodecContext *avctx, void *data,
1137                                 int *got_frame_ptr, AVPacket *avpkt)
1138 {
1139     WavpackContext *s  = avctx->priv_data;
1140     const uint8_t *buf = avpkt->data;
1141     int buf_size       = avpkt->size;
1142     AVFrame *frame     = data;
1143     int frame_size, ret, frame_flags;
1144
1145     if (avpkt->size <= WV_HEADER_SIZE)
1146         return AVERROR_INVALIDDATA;
1147
1148     s->block     = 0;
1149     s->ch_offset = 0;
1150
1151     /* determine number of samples */
1152     s->samples  = AV_RL32(buf + 20);
1153     frame_flags = AV_RL32(buf + 24);
1154     if (s->samples <= 0 || s->samples > WV_MAX_SAMPLES) {
1155         av_log(avctx, AV_LOG_ERROR, "Invalid number of samples: %d\n",
1156                s->samples);
1157         return AVERROR_INVALIDDATA;
1158     }
1159
1160     if (frame_flags & 0x80) {
1161         avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1162     } else if ((frame_flags & 0x03) <= 1) {
1163         avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
1164     } else {
1165         avctx->sample_fmt          = AV_SAMPLE_FMT_S32P;
1166         avctx->bits_per_raw_sample = ((frame_flags & 0x03) + 1) << 3;
1167     }
1168
1169     /* get output buffer */
1170     frame->nb_samples = s->samples + 1;
1171     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
1172         return ret;
1173     frame->nb_samples = s->samples;
1174
1175     while (buf_size > 0) {
1176         if (buf_size <= WV_HEADER_SIZE)
1177             break;
1178         frame_size = AV_RL32(buf + 4) - 12;
1179         buf       += 20;
1180         buf_size  -= 20;
1181         if (frame_size <= 0 || frame_size > buf_size) {
1182             av_log(avctx, AV_LOG_ERROR,
1183                    "Block %d has invalid size (size %d vs. %d bytes left)\n",
1184                    s->block, frame_size, buf_size);
1185             wavpack_decode_flush(avctx);
1186             return AVERROR_INVALIDDATA;
1187         }
1188         if ((ret = wavpack_decode_block(avctx, s->block,
1189                                         frame->extended_data,
1190                                         buf, frame_size)) < 0) {
1191             wavpack_decode_flush(avctx);
1192             return ret;
1193         }
1194         s->block++;
1195         buf      += frame_size;
1196         buf_size -= frame_size;
1197     }
1198
1199     *got_frame_ptr = 1;
1200
1201     return avpkt->size;
1202 }
1203
1204 AVCodec ff_wavpack_decoder = {
1205     .name           = "wavpack",
1206     .type           = AVMEDIA_TYPE_AUDIO,
1207     .id             = AV_CODEC_ID_WAVPACK,
1208     .priv_data_size = sizeof(WavpackContext),
1209     .init           = wavpack_decode_init,
1210     .close          = wavpack_decode_end,
1211     .decode         = wavpack_decode_frame,
1212     .flush          = wavpack_decode_flush,
1213     .capabilities   = CODEC_CAP_DR1,
1214     .long_name      = NULL_IF_CONFIG_SMALL("WavPack"),
1215 };