]> git.sesse.net Git - ffmpeg/blob - libavcodec/wavpack.c
Merge commit 'e1eaaec765d2e726618633fcbd2e06fded7647a8'
[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 "thread.h"
29 #include "unary.h"
30 #include "bytestream.h"
31 #include "wavpack.h"
32
33 /**
34  * @file
35  * WavPack lossless audio decoder
36  */
37
38 typedef struct SavedContext {
39     int offset;
40     int size;
41     int bits_used;
42     uint32_t crc;
43 } SavedContext;
44
45 typedef struct WavpackFrameContext {
46     AVCodecContext *avctx;
47     int frame_flags;
48     int stereo, stereo_in;
49     int joint;
50     uint32_t CRC;
51     GetBitContext gb;
52     int got_extra_bits;
53     uint32_t crc_extra_bits;
54     GetBitContext gb_extra_bits;
55     int data_size; // in bits
56     int samples;
57     int terms;
58     Decorr decorr[MAX_TERMS];
59     int zero, one, zeroes;
60     int extra_bits;
61     int and, or, shift;
62     int post_shift;
63     int hybrid, hybrid_bitrate;
64     int hybrid_maxclip, hybrid_minclip;
65     int float_flag;
66     int float_shift;
67     int float_max_exp;
68     WvChannel ch[2];
69     int pos;
70     SavedContext sc, extra_sc;
71 } WavpackFrameContext;
72
73 #define WV_MAX_FRAME_DECODERS 14
74
75 typedef struct WavpackContext {
76     AVCodecContext *avctx;
77
78     WavpackFrameContext *fdec[WV_MAX_FRAME_DECODERS];
79     int fdec_num;
80
81     int block;
82     int samples;
83     int ch_offset;
84 } WavpackContext;
85
86 #define LEVEL_DECAY(a)  ((a + 0x80) >> 8)
87
88 static av_always_inline int get_tail(GetBitContext *gb, int k)
89 {
90     int p, e, res;
91
92     if (k < 1)
93         return 0;
94     p   = av_log2(k);
95     e   = (1 << (p + 1)) - k - 1;
96     res = p ? get_bits(gb, p) : 0;
97     if (res >= e)
98         res = (res << 1) - e + get_bits1(gb);
99     return res;
100 }
101
102 static void update_error_limit(WavpackFrameContext *ctx)
103 {
104     int i, br[2], sl[2];
105
106     for (i = 0; i <= ctx->stereo_in; i++) {
107         ctx->ch[i].bitrate_acc += ctx->ch[i].bitrate_delta;
108         br[i]                   = ctx->ch[i].bitrate_acc >> 16;
109         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             br[1] = br[0] << 1;
115             br[0] = 0;
116         } else if (-balance > br[0]) {
117             br[0] <<= 1;
118             br[1]   = 0;
119         } else {
120             br[1] = br[0] + balance;
121             br[0] = br[0] - balance;
122         }
123     }
124     for (i = 0; i <= ctx->stereo_in; i++) {
125         if (ctx->hybrid_bitrate) {
126             if (sl[i] - br[i] > -0x100)
127                 ctx->ch[i].error_limit = wp_exp2(sl[i] - br[i] + 0x100);
128             else
129                 ctx->ch[i].error_limit = 0;
130         } else {
131             ctx->ch[i].error_limit = wp_exp2(br[i]);
132         }
133     }
134 }
135
136 static int wv_get_value(WavpackFrameContext *ctx, GetBitContext *gb,
137                         int channel, int *last)
138 {
139     int t, t2;
140     int sign, base, add, ret;
141     WvChannel *c = &ctx->ch[channel];
142
143     *last = 0;
144
145     if ((ctx->ch[0].median[0] < 2U) && (ctx->ch[1].median[0] < 2U) &&
146         !ctx->zero && !ctx->one) {
147         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             if (t >= 2) {
156                 if (get_bits_left(gb) < t - 1)
157                     goto error;
158                 t = get_bits(gb, t - 1) | (1 << (t - 1));
159             } else {
160                 if (get_bits_left(gb) < 0)
161                     goto error;
162             }
163             ctx->zeroes = t;
164             if (ctx->zeroes) {
165                 memset(ctx->ch[0].median, 0, sizeof(ctx->ch[0].median));
166                 memset(ctx->ch[1].median, 0, sizeof(ctx->ch[1].median));
167                 c->slow_level -= LEVEL_DECAY(c->slow_level);
168                 return 0;
169             }
170         }
171     }
172
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             if (t2 < 2) {
183                 if (get_bits_left(gb) < 0)
184                     goto error;
185                 t += t2;
186             } else {
187                 if (get_bits_left(gb) < t2 - 1)
188                     goto error;
189                 t += get_bits(gb, t2 - 1) | (1 << (t2 - 1));
190             }
191         }
192
193         if (ctx->one) {
194             ctx->one = t & 1;
195             t        = (t >> 1) + 1;
196         } else {
197             ctx->one = t & 1;
198             t      >>= 1;
199         }
200         ctx->zero = !ctx->one;
201     }
202
203     if (ctx->hybrid && !channel)
204         update_error_limit(ctx);
205
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         INC_MED(0);
214         DEC_MED(1);
215     } else if (t == 2) {
216         base = GET_MED(0) + GET_MED(1);
217         add  = GET_MED(2) - 1;
218         INC_MED(0);
219         INC_MED(1);
220         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         INC_MED(0);
225         INC_MED(1);
226         INC_MED(2);
227     }
228     if (!c->error_limit) {
229         if (add >= 0x2000000U) {
230             av_log(ctx->avctx, AV_LOG_ERROR, "k %d is too large\n", add);
231             goto error;
232         }
233         ret = base + get_tail(gb, add);
234         if (get_bits_left(gb) <= 0)
235             goto error;
236     } else {
237         int mid = (base * 2 + add + 1) >> 1;
238         while (add > c->error_limit) {
239             if (get_bits_left(gb) <= 0)
240                 goto error;
241             if (get_bits1(gb)) {
242                 add -= (mid - base);
243                 base = mid;
244             } else
245                 add = mid - base - 1;
246             mid = (base * 2 + add + 1) >> 1;
247         }
248         ret = mid;
249     }
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 error:
256     *last = 1;
257     return 0;
258 }
259
260 static inline int wv_get_value_integer(WavpackFrameContext *s, uint32_t *crc,
261                                        int S)
262 {
263     int bit;
264
265     if (s->extra_bits) {
266         S <<= s->extra_bits;
267
268         if (s->got_extra_bits &&
269             get_bits_left(&s->gb_extra_bits) >= s->extra_bits) {
270             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     union {
287         float    f;
288         uint32_t u;
289     } value;
290
291     unsigned int sign;
292     int exp = s->float_max_exp;
293
294     if (s->got_extra_bits) {
295         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             return 0.0;
300     }
301
302     if (S) {
303         S  <<= s->float_shift;
304         sign = S < 0;
305         if (sign)
306             S = -S;
307         if (S >= 0x1000000) {
308             if (s->got_extra_bits && get_bits1(&s->gb_extra_bits))
309                 S = get_bits(&s->gb_extra_bits, 23);
310             else
311                 S = 0;
312             exp = 255;
313         } else if (exp) {
314             int shift = 23 - av_log2(S);
315             exp = s->float_max_exp;
316             if (exp <= shift)
317                 shift = --exp;
318             exp -= shift;
319
320             if (shift) {
321                 S <<= shift;
322                 if ((s->float_flag & WV_FLT_SHIFT_ONES) ||
323                     (s->got_extra_bits &&
324                      (s->float_flag & WV_FLT_SHIFT_SAME) &&
325                      get_bits1(&s->gb_extra_bits))) {
326                     S |= (1 << shift) - 1;
327                 } else if (s->got_extra_bits &&
328                            (s->float_flag & WV_FLT_SHIFT_SENT)) {
329                     S |= get_bits(&s->gb_extra_bits, shift);
330                 }
331             }
332         } else {
333             exp = s->float_max_exp;
334         }
335         S &= 0x7fffff;
336     } else {
337         sign = 0;
338         exp  = 0;
339         if (s->got_extra_bits && (s->float_flag & WV_FLT_ZERO_SENT)) {
340             if (get_bits1(&s->gb_extra_bits)) {
341                 S = get_bits(&s->gb_extra_bits, 23);
342                 if (s->float_max_exp >= 25)
343                     exp = get_bits(&s->gb_extra_bits, 8);
344                 sign = get_bits1(&s->gb_extra_bits);
345             } else {
346                 if (s->float_flag & WV_FLT_ZERO_SIGN)
347                     sign = get_bits1(&s->gb_extra_bits);
348             }
349         }
350     }
351
352     *crc = *crc * 27 + S * 9 + exp * 3 + sign;
353
354     value.u = (sign << 31) | (exp << 23) | S;
355     return value.f;
356 }
357
358 static void wv_reset_saved_context(WavpackFrameContext *s)
359 {
360     s->pos    = 0;
361     s->sc.crc = s->extra_sc.crc = 0xFFFFFFFF;
362 }
363
364 static inline int wv_check_crc(WavpackFrameContext *s, uint32_t crc,
365                                uint32_t crc_extra_bits)
366 {
367     if (crc != s->CRC) {
368         av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
369         return AVERROR_INVALIDDATA;
370     }
371     if (s->got_extra_bits && crc_extra_bits != s->crc_extra_bits) {
372         av_log(s->avctx, AV_LOG_ERROR, "Extra bits CRC error\n");
373         return AVERROR_INVALIDDATA;
374     }
375
376     return 0;
377 }
378
379 static inline int wv_unpack_stereo(WavpackFrameContext *s, GetBitContext *gb,
380                                    void *dst_l, void *dst_r, const int type)
381 {
382     int i, j, count = 0;
383     int last, t;
384     int A, B, L, L2, R, R2;
385     int pos                 = s->pos;
386     uint32_t crc            = s->sc.crc;
387     uint32_t crc_extra_bits = s->extra_sc.crc;
388     int16_t *dst16_l        = dst_l;
389     int16_t *dst16_r        = dst_r;
390     int32_t *dst32_l        = dst_l;
391     int32_t *dst32_r        = dst_r;
392     float *dstfl_l          = dst_l;
393     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         if (last)
399             break;
400         R = wv_get_value(s, gb, 1, &last);
401         if (last)
402             break;
403         for (i = 0; i < s->terms; i++) {
404             t = s->decorr[i].value;
405             if (t > 0) {
406                 if (t > 8) {
407                     if (t & 1) {
408                         A = 2 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
409                         B = 2 * s->decorr[i].samplesB[0] - s->decorr[i].samplesB[1];
410                     } else {
411                         A = (3 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1]) >> 1;
412                         B = (3 * s->decorr[i].samplesB[0] - s->decorr[i].samplesB[1]) >> 1;
413                     }
414                     s->decorr[i].samplesA[1] = s->decorr[i].samplesA[0];
415                     s->decorr[i].samplesB[1] = s->decorr[i].samplesB[0];
416                     j                        = 0;
417                 } else {
418                     A = s->decorr[i].samplesA[pos];
419                     B = s->decorr[i].samplesB[pos];
420                     j = (pos + t) & 7;
421                 }
422                 if (type != AV_SAMPLE_FMT_S16P) {
423                     L2 = L + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
424                     R2 = R + ((s->decorr[i].weightB * (int64_t)B + 512) >> 10);
425                 } else {
426                     L2 = L + ((s->decorr[i].weightA * A + 512) >> 10);
427                     R2 = R + ((s->decorr[i].weightB * B + 512) >> 10);
428                 }
429                 if (A && L)
430                     s->decorr[i].weightA -= ((((L ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
431                 if (B && R)
432                     s->decorr[i].weightB -= ((((R ^ B) >> 30) & 2) - 1) * s->decorr[i].delta;
433                 s->decorr[i].samplesA[j] = L = L2;
434                 s->decorr[i].samplesB[j] = R = R2;
435             } else if (t == -1) {
436                 if (type != AV_SAMPLE_FMT_S16P)
437                     L2 = L + ((s->decorr[i].weightA * (int64_t)s->decorr[i].samplesA[0] + 512) >> 10);
438                 else
439                     L2 = L + ((s->decorr[i].weightA * s->decorr[i].samplesA[0] + 512) >> 10);
440                 UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, s->decorr[i].samplesA[0], L);
441                 L = L2;
442                 if (type != AV_SAMPLE_FMT_S16P)
443                     R2 = R + ((s->decorr[i].weightB * (int64_t)L2 + 512) >> 10);
444                 else
445                     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                     R2 = R + ((s->decorr[i].weightB * (int64_t)s->decorr[i].samplesB[0] + 512) >> 10);
452                 else
453                     R2 = R + ((s->decorr[i].weightB * s->decorr[i].samplesB[0] + 512) >> 10);
454                 UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, s->decorr[i].samplesB[0], R);
455                 R = R2;
456
457                 if (t == -3) {
458                     R2                       = s->decorr[i].samplesA[0];
459                     s->decorr[i].samplesA[0] = R;
460                 }
461
462                 if (type != AV_SAMPLE_FMT_S16P)
463                     L2 = L + ((s->decorr[i].weightA * (int64_t)R2 + 512) >> 10);
464                 else
465                     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                 s->decorr[i].samplesB[0] = L;
469             }
470         }
471         pos = (pos + 1) & 7;
472         if (s->joint)
473             L += (R -= (L >> 1));
474         crc = (crc * 3 + L) * 3 + R;
475
476         if (type == AV_SAMPLE_FMT_FLTP) {
477             *dstfl_l++ = wv_get_value_float(s, &crc_extra_bits, L);
478             *dstfl_r++ = wv_get_value_float(s, &crc_extra_bits, R);
479         } else if (type == AV_SAMPLE_FMT_S32P) {
480             *dst32_l++ = wv_get_value_integer(s, &crc_extra_bits, L);
481             *dst32_r++ = wv_get_value_integer(s, &crc_extra_bits, R);
482         } else {
483             *dst16_l++ = wv_get_value_integer(s, &crc_extra_bits, L);
484             *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     if ((s->avctx->err_recognition & AV_EF_CRCCHECK) &&
491         wv_check_crc(s, crc, crc_extra_bits))
492         return AVERROR_INVALIDDATA;
493
494     return 0;
495 }
496
497 static inline int wv_unpack_mono(WavpackFrameContext *s, GetBitContext *gb,
498                                  void *dst, const int type)
499 {
500     int i, j, count = 0;
501     int last, t;
502     int A, S, T;
503     int pos                  = s->pos;
504     uint32_t crc             = s->sc.crc;
505     uint32_t crc_extra_bits  = s->extra_sc.crc;
506     int16_t *dst16           = dst;
507     int32_t *dst32           = dst;
508     float *dstfl             = dst;
509
510     s->one = s->zero = s->zeroes = 0;
511     do {
512         T = wv_get_value(s, gb, 0, &last);
513         S = 0;
514         if (last)
515             break;
516         for (i = 0; i < s->terms; i++) {
517             t = s->decorr[i].value;
518             if (t > 8) {
519                 if (t & 1)
520                     A =  2 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
521                 else
522                     A = (3 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1]) >> 1;
523                 s->decorr[i].samplesA[1] = s->decorr[i].samplesA[0];
524                 j                        = 0;
525             } else {
526                 A = s->decorr[i].samplesA[pos];
527                 j = (pos + t) & 7;
528             }
529             if (type != AV_SAMPLE_FMT_S16P)
530                 S = T + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
531             else
532                 S = T + ((s->decorr[i].weightA * A + 512) >> 10);
533             if (A && T)
534                 s->decorr[i].weightA -= ((((T ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
535             s->decorr[i].samplesA[j] = T = S;
536         }
537         pos = (pos + 1) & 7;
538         crc = crc * 3 + S;
539
540         if (type == AV_SAMPLE_FMT_FLTP) {
541             *dstfl++ = wv_get_value_float(s, &crc_extra_bits, S);
542         } else if (type == AV_SAMPLE_FMT_S32P) {
543             *dst32++ = wv_get_value_integer(s, &crc_extra_bits, S);
544         } else {
545             *dst16++ = wv_get_value_integer(s, &crc_extra_bits, S);
546         }
547         count++;
548     } while (!last && count < s->samples);
549
550     wv_reset_saved_context(s);
551     if (s->avctx->err_recognition & AV_EF_CRCCHECK) {
552         int ret = wv_check_crc(s, crc, crc_extra_bits);
553         if (ret < 0 && s->avctx->err_recognition & AV_EF_EXPLODE)
554             return ret;
555     }
556
557     return 0;
558 }
559
560 static av_cold int wv_alloc_frame_context(WavpackContext *c)
561 {
562     if (c->fdec_num == WV_MAX_FRAME_DECODERS)
563         return -1;
564
565     c->fdec[c->fdec_num] = av_mallocz(sizeof(**c->fdec));
566     if (!c->fdec[c->fdec_num])
567         return -1;
568     c->fdec_num++;
569     c->fdec[c->fdec_num - 1]->avctx = c->avctx;
570     wv_reset_saved_context(c->fdec[c->fdec_num - 1]);
571
572     return 0;
573 }
574
575 static int init_thread_copy(AVCodecContext *avctx)
576 {
577     WavpackContext *s = avctx->priv_data;
578     s->avctx = avctx;
579     return 0;
580 }
581
582 static av_cold int wavpack_decode_init(AVCodecContext *avctx)
583 {
584     WavpackContext *s = avctx->priv_data;
585
586     s->avctx = avctx;
587
588     s->fdec_num = 0;
589
590     return 0;
591 }
592
593 static av_cold int wavpack_decode_end(AVCodecContext *avctx)
594 {
595     WavpackContext *s = avctx->priv_data;
596     int i;
597
598     for (i = 0; i < s->fdec_num; i++)
599         av_freep(&s->fdec[i]);
600     s->fdec_num = 0;
601
602     return 0;
603 }
604
605 static int wavpack_decode_block(AVCodecContext *avctx, int block_no,
606                                 AVFrame *frame, const uint8_t *buf, int buf_size)
607 {
608     WavpackContext *wc = avctx->priv_data;
609     ThreadFrame tframe = { .f = frame };
610     WavpackFrameContext *s;
611     GetByteContext gb;
612     void *samples_l, *samples_r;
613     int ret;
614     int got_terms   = 0, got_weights = 0, got_samples = 0,
615         got_entropy = 0, got_bs      = 0, got_float   = 0, got_hybrid = 0;
616     int i, j, id, size, ssize, weights, t;
617     int bpp, chan = 0, chmask = 0, orig_bpp, sample_rate = 0;
618     int multiblock;
619
620     if (block_no >= wc->fdec_num && wv_alloc_frame_context(wc) < 0) {
621         av_log(avctx, AV_LOG_ERROR, "Error creating frame decode context\n");
622         return AVERROR_INVALIDDATA;
623     }
624
625     s = wc->fdec[block_no];
626     if (!s) {
627         av_log(avctx, AV_LOG_ERROR, "Context for block %d is not present\n",
628                block_no);
629         return AVERROR_INVALIDDATA;
630     }
631
632     memset(s->decorr, 0, MAX_TERMS * sizeof(Decorr));
633     memset(s->ch, 0, sizeof(s->ch));
634     s->extra_bits     = 0;
635     s->and            = s->or = s->shift = 0;
636     s->got_extra_bits = 0;
637
638     bytestream2_init(&gb, buf, buf_size);
639
640     s->samples = bytestream2_get_le32(&gb);
641     if (s->samples != wc->samples) {
642         av_log(avctx, AV_LOG_ERROR, "Mismatching number of samples in "
643                "a sequence: %d and %d\n", wc->samples, s->samples);
644         return AVERROR_INVALIDDATA;
645     }
646     s->frame_flags = bytestream2_get_le32(&gb);
647     bpp            = av_get_bytes_per_sample(avctx->sample_fmt);
648     orig_bpp       = ((s->frame_flags & 0x03) + 1) << 3;
649     multiblock     = (s->frame_flags & WV_SINGLE_BLOCK) != WV_SINGLE_BLOCK;
650
651     s->stereo         = !(s->frame_flags & WV_MONO);
652     s->stereo_in      =  (s->frame_flags & WV_FALSE_STEREO) ? 0 : s->stereo;
653     s->joint          =   s->frame_flags & WV_JOINT_STEREO;
654     s->hybrid         =   s->frame_flags & WV_HYBRID_MODE;
655     s->hybrid_bitrate =   s->frame_flags & WV_HYBRID_BITRATE;
656     s->post_shift     = bpp * 8 - orig_bpp + ((s->frame_flags >> 13) & 0x1f);
657     s->hybrid_maxclip =  ((1LL << (orig_bpp - 1)) - 1);
658     s->hybrid_minclip = ((-1LL << (orig_bpp - 1)));
659     s->CRC            = bytestream2_get_le32(&gb);
660
661     // parse metadata blocks
662     while (bytestream2_get_bytes_left(&gb)) {
663         id   = bytestream2_get_byte(&gb);
664         size = bytestream2_get_byte(&gb);
665         if (id & WP_IDF_LONG) {
666             size |= (bytestream2_get_byte(&gb)) << 8;
667             size |= (bytestream2_get_byte(&gb)) << 16;
668         }
669         size <<= 1; // size is specified in words
670         ssize  = size;
671         if (id & WP_IDF_ODD)
672             size--;
673         if (size < 0) {
674             av_log(avctx, AV_LOG_ERROR,
675                    "Got incorrect block %02X with size %i\n", id, size);
676             break;
677         }
678         if (bytestream2_get_bytes_left(&gb) < ssize) {
679             av_log(avctx, AV_LOG_ERROR,
680                    "Block size %i is out of bounds\n", size);
681             break;
682         }
683         switch (id & WP_IDF_MASK) {
684         case WP_ID_DECTERMS:
685             if (size > MAX_TERMS) {
686                 av_log(avctx, AV_LOG_ERROR, "Too many decorrelation terms\n");
687                 s->terms = 0;
688                 bytestream2_skip(&gb, ssize);
689                 continue;
690             }
691             s->terms = size;
692             for (i = 0; i < s->terms; i++) {
693                 uint8_t val = bytestream2_get_byte(&gb);
694                 s->decorr[s->terms - i - 1].value = (val & 0x1F) - 5;
695                 s->decorr[s->terms - i - 1].delta =  val >> 5;
696             }
697             got_terms = 1;
698             break;
699         case WP_ID_DECWEIGHTS:
700             if (!got_terms) {
701                 av_log(avctx, AV_LOG_ERROR, "No decorrelation terms met\n");
702                 continue;
703             }
704             weights = size >> s->stereo_in;
705             if (weights > MAX_TERMS || weights > s->terms) {
706                 av_log(avctx, AV_LOG_ERROR, "Too many decorrelation weights\n");
707                 bytestream2_skip(&gb, ssize);
708                 continue;
709             }
710             for (i = 0; i < weights; i++) {
711                 t = (int8_t)bytestream2_get_byte(&gb);
712                 s->decorr[s->terms - i - 1].weightA = t << 3;
713                 if (s->decorr[s->terms - i - 1].weightA > 0)
714                     s->decorr[s->terms - i - 1].weightA +=
715                         (s->decorr[s->terms - i - 1].weightA + 64) >> 7;
716                 if (s->stereo_in) {
717                     t = (int8_t)bytestream2_get_byte(&gb);
718                     s->decorr[s->terms - i - 1].weightB = t << 3;
719                     if (s->decorr[s->terms - i - 1].weightB > 0)
720                         s->decorr[s->terms - i - 1].weightB +=
721                             (s->decorr[s->terms - i - 1].weightB + 64) >> 7;
722                 }
723             }
724             got_weights = 1;
725             break;
726         case WP_ID_DECSAMPLES:
727             if (!got_terms) {
728                 av_log(avctx, AV_LOG_ERROR, "No decorrelation terms met\n");
729                 continue;
730             }
731             t = 0;
732             for (i = s->terms - 1; (i >= 0) && (t < size); i--) {
733                 if (s->decorr[i].value > 8) {
734                     s->decorr[i].samplesA[0] =
735                         wp_exp2(bytestream2_get_le16(&gb));
736                     s->decorr[i].samplesA[1] =
737                         wp_exp2(bytestream2_get_le16(&gb));
738
739                     if (s->stereo_in) {
740                         s->decorr[i].samplesB[0] =
741                             wp_exp2(bytestream2_get_le16(&gb));
742                         s->decorr[i].samplesB[1] =
743                             wp_exp2(bytestream2_get_le16(&gb));
744                         t                       += 4;
745                     }
746                     t += 4;
747                 } else if (s->decorr[i].value < 0) {
748                     s->decorr[i].samplesA[0] =
749                         wp_exp2(bytestream2_get_le16(&gb));
750                     s->decorr[i].samplesB[0] =
751                         wp_exp2(bytestream2_get_le16(&gb));
752                     t                       += 4;
753                 } else {
754                     for (j = 0; j < s->decorr[i].value; j++) {
755                         s->decorr[i].samplesA[j] =
756                             wp_exp2(bytestream2_get_le16(&gb));
757                         if (s->stereo_in) {
758                             s->decorr[i].samplesB[j] =
759                                 wp_exp2(bytestream2_get_le16(&gb));
760                         }
761                     }
762                     t += s->decorr[i].value * 2 * (s->stereo_in + 1);
763                 }
764             }
765             got_samples = 1;
766             break;
767         case WP_ID_ENTROPY:
768             if (size != 6 * (s->stereo_in + 1)) {
769                 av_log(avctx, AV_LOG_ERROR,
770                        "Entropy vars size should be %i, got %i.\n",
771                        6 * (s->stereo_in + 1), size);
772                 bytestream2_skip(&gb, ssize);
773                 continue;
774             }
775             for (j = 0; j <= s->stereo_in; j++)
776                 for (i = 0; i < 3; i++) {
777                     s->ch[j].median[i] = wp_exp2(bytestream2_get_le16(&gb));
778                 }
779             got_entropy = 1;
780             break;
781         case WP_ID_HYBRID:
782             if (s->hybrid_bitrate) {
783                 for (i = 0; i <= s->stereo_in; i++) {
784                     s->ch[i].slow_level = wp_exp2(bytestream2_get_le16(&gb));
785                     size               -= 2;
786                 }
787             }
788             for (i = 0; i < (s->stereo_in + 1); i++) {
789                 s->ch[i].bitrate_acc = bytestream2_get_le16(&gb) << 16;
790                 size                -= 2;
791             }
792             if (size > 0) {
793                 for (i = 0; i < (s->stereo_in + 1); i++) {
794                     s->ch[i].bitrate_delta =
795                         wp_exp2((int16_t)bytestream2_get_le16(&gb));
796                 }
797             } else {
798                 for (i = 0; i < (s->stereo_in + 1); i++)
799                     s->ch[i].bitrate_delta = 0;
800             }
801             got_hybrid = 1;
802             break;
803         case WP_ID_INT32INFO: {
804             uint8_t val[4];
805             if (size != 4) {
806                 av_log(avctx, AV_LOG_ERROR,
807                        "Invalid INT32INFO, size = %i\n",
808                        size);
809                 bytestream2_skip(&gb, ssize - 4);
810                 continue;
811             }
812             bytestream2_get_buffer(&gb, val, 4);
813             if (val[0]) {
814                 s->extra_bits = val[0];
815             } else if (val[1]) {
816                 s->shift = val[1];
817             } else if (val[2]) {
818                 s->and   = s->or = 1;
819                 s->shift = val[2];
820             } else if (val[3]) {
821                 s->and   = 1;
822                 s->shift = val[3];
823             }
824             /* original WavPack decoder forces 32-bit lossy sound to be treated
825              * as 24-bit one in order to have proper clipping */
826             if (s->hybrid && bpp == 4 && s->post_shift < 8 && s->shift > 8) {
827                 s->post_shift      += 8;
828                 s->shift           -= 8;
829                 s->hybrid_maxclip >>= 8;
830                 s->hybrid_minclip >>= 8;
831             }
832             break;
833         }
834         case WP_ID_FLOATINFO:
835             if (size != 4) {
836                 av_log(avctx, AV_LOG_ERROR,
837                        "Invalid FLOATINFO, size = %i\n", size);
838                 bytestream2_skip(&gb, ssize);
839                 continue;
840             }
841             s->float_flag    = bytestream2_get_byte(&gb);
842             s->float_shift   = bytestream2_get_byte(&gb);
843             s->float_max_exp = bytestream2_get_byte(&gb);
844             got_float        = 1;
845             bytestream2_skip(&gb, 1);
846             break;
847         case WP_ID_DATA:
848             s->sc.offset = bytestream2_tell(&gb);
849             s->sc.size   = size * 8;
850             if ((ret = init_get_bits8(&s->gb, gb.buffer, size)) < 0)
851                 return ret;
852             s->data_size = size * 8;
853             bytestream2_skip(&gb, size);
854             got_bs       = 1;
855             break;
856         case WP_ID_EXTRABITS:
857             if (size <= 4) {
858                 av_log(avctx, AV_LOG_ERROR, "Invalid EXTRABITS, size = %i\n",
859                        size);
860                 bytestream2_skip(&gb, size);
861                 continue;
862             }
863             s->extra_sc.offset = bytestream2_tell(&gb);
864             s->extra_sc.size   = size * 8;
865             if ((ret = init_get_bits8(&s->gb_extra_bits, gb.buffer, size)) < 0)
866                 return ret;
867             s->crc_extra_bits  = get_bits_long(&s->gb_extra_bits, 32);
868             bytestream2_skip(&gb, size);
869             s->got_extra_bits  = 1;
870             break;
871         case WP_ID_CHANINFO:
872             if (size <= 1) {
873                 av_log(avctx, AV_LOG_ERROR,
874                        "Insufficient channel information\n");
875                 return AVERROR_INVALIDDATA;
876             }
877             chan = bytestream2_get_byte(&gb);
878             switch (size - 2) {
879             case 0:
880                 chmask = bytestream2_get_byte(&gb);
881                 break;
882             case 1:
883                 chmask = bytestream2_get_le16(&gb);
884                 break;
885             case 2:
886                 chmask = bytestream2_get_le24(&gb);
887                 break;
888             case 3:
889                 chmask = bytestream2_get_le32(&gb);
890                 break;
891             case 5:
892                 bytestream2_skip(&gb, 1);
893                 chan  |= (bytestream2_get_byte(&gb) & 0xF) << 8;
894                 chmask = bytestream2_get_le16(&gb);
895                 break;
896             default:
897                 av_log(avctx, AV_LOG_ERROR, "Invalid channel info size %d\n",
898                        size);
899                 chan   = avctx->channels;
900                 chmask = avctx->channel_layout;
901             }
902             break;
903         case WP_ID_SAMPLE_RATE:
904             if (size != 3) {
905                 av_log(avctx, AV_LOG_ERROR, "Invalid custom sample rate.\n");
906                 return AVERROR_INVALIDDATA;
907             }
908             sample_rate = bytestream2_get_le24(&gb);
909             break;
910         default:
911             bytestream2_skip(&gb, size);
912         }
913         if (id & WP_IDF_ODD)
914             bytestream2_skip(&gb, 1);
915     }
916
917     if (!got_terms) {
918         av_log(avctx, AV_LOG_ERROR, "No block with decorrelation terms\n");
919         return AVERROR_INVALIDDATA;
920     }
921     if (!got_weights) {
922         av_log(avctx, AV_LOG_ERROR, "No block with decorrelation weights\n");
923         return AVERROR_INVALIDDATA;
924     }
925     if (!got_samples) {
926         av_log(avctx, AV_LOG_ERROR, "No block with decorrelation samples\n");
927         return AVERROR_INVALIDDATA;
928     }
929     if (!got_entropy) {
930         av_log(avctx, AV_LOG_ERROR, "No block with entropy info\n");
931         return AVERROR_INVALIDDATA;
932     }
933     if (s->hybrid && !got_hybrid) {
934         av_log(avctx, AV_LOG_ERROR, "Hybrid config not found\n");
935         return AVERROR_INVALIDDATA;
936     }
937     if (!got_bs) {
938         av_log(avctx, AV_LOG_ERROR, "Packed samples not found\n");
939         return AVERROR_INVALIDDATA;
940     }
941     if (!got_float && avctx->sample_fmt == AV_SAMPLE_FMT_FLTP) {
942         av_log(avctx, AV_LOG_ERROR, "Float information not found\n");
943         return AVERROR_INVALIDDATA;
944     }
945     if (s->got_extra_bits && avctx->sample_fmt != AV_SAMPLE_FMT_FLTP) {
946         const int size   = get_bits_left(&s->gb_extra_bits);
947         const int wanted = s->samples * s->extra_bits << s->stereo_in;
948         if (size < wanted) {
949             av_log(avctx, AV_LOG_ERROR, "Too small EXTRABITS\n");
950             s->got_extra_bits = 0;
951         }
952     }
953
954     if (!wc->ch_offset) {
955         int sr = (s->frame_flags >> 23) & 0xf;
956         if (sr == 0xf) {
957             if (!sample_rate) {
958                 av_log(avctx, AV_LOG_ERROR, "Custom sample rate missing.\n");
959                 return AVERROR_INVALIDDATA;
960             }
961             avctx->sample_rate = sample_rate;
962         } else
963             avctx->sample_rate = wv_rates[sr];
964
965         if (multiblock) {
966             if (chan)
967                 avctx->channels = chan;
968             if (chmask)
969                 avctx->channel_layout = chmask;
970         } else {
971             avctx->channels       = s->stereo ? 2 : 1;
972             avctx->channel_layout = s->stereo ? AV_CH_LAYOUT_STEREO :
973                                                 AV_CH_LAYOUT_MONO;
974         }
975
976         /* get output buffer */
977         frame->nb_samples = s->samples + 1;
978         if ((ret = ff_thread_get_buffer(avctx, &tframe, 0)) < 0)
979             return ret;
980         frame->nb_samples = s->samples;
981     }
982
983     if (wc->ch_offset + s->stereo >= avctx->channels) {
984         av_log(avctx, AV_LOG_WARNING, "Too many channels coded in a packet.\n");
985         return (avctx->err_recognition & AV_EF_EXPLODE) ? AVERROR_INVALIDDATA : 0;
986     }
987
988     samples_l = frame->extended_data[wc->ch_offset];
989     if (s->stereo)
990         samples_r = frame->extended_data[wc->ch_offset + 1];
991
992     wc->ch_offset += 1 + s->stereo;
993
994     if (s->stereo_in) {
995         ret = wv_unpack_stereo(s, &s->gb, samples_l, samples_r, avctx->sample_fmt);
996         if (ret < 0)
997             return ret;
998     } else {
999         ret = wv_unpack_mono(s, &s->gb, samples_l, avctx->sample_fmt);
1000         if (ret < 0)
1001             return ret;
1002
1003         if (s->stereo)
1004             memcpy(samples_r, samples_l, bpp * s->samples);
1005     }
1006
1007     return 0;
1008 }
1009
1010 static void wavpack_decode_flush(AVCodecContext *avctx)
1011 {
1012     WavpackContext *s = avctx->priv_data;
1013     int i;
1014
1015     for (i = 0; i < s->fdec_num; i++)
1016         wv_reset_saved_context(s->fdec[i]);
1017 }
1018
1019 static int wavpack_decode_frame(AVCodecContext *avctx, void *data,
1020                                 int *got_frame_ptr, AVPacket *avpkt)
1021 {
1022     WavpackContext *s  = avctx->priv_data;
1023     const uint8_t *buf = avpkt->data;
1024     int buf_size       = avpkt->size;
1025     AVFrame *frame     = data;
1026     int frame_size, ret, frame_flags;
1027
1028     if (avpkt->size <= WV_HEADER_SIZE)
1029         return AVERROR_INVALIDDATA;
1030
1031     s->block     = 0;
1032     s->ch_offset = 0;
1033
1034     /* determine number of samples */
1035     s->samples  = AV_RL32(buf + 20);
1036     frame_flags = AV_RL32(buf + 24);
1037     if (s->samples <= 0 || s->samples > WV_MAX_SAMPLES) {
1038         av_log(avctx, AV_LOG_ERROR, "Invalid number of samples: %d\n",
1039                s->samples);
1040         return AVERROR_INVALIDDATA;
1041     }
1042
1043     if (frame_flags & 0x80) {
1044         avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1045     } else if ((frame_flags & 0x03) <= 1) {
1046         avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
1047     } else {
1048         avctx->sample_fmt          = AV_SAMPLE_FMT_S32P;
1049         avctx->bits_per_raw_sample = ((frame_flags & 0x03) + 1) << 3;
1050     }
1051
1052     while (buf_size > 0) {
1053         if (buf_size <= WV_HEADER_SIZE)
1054             break;
1055         frame_size = AV_RL32(buf + 4) - 12;
1056         buf       += 20;
1057         buf_size  -= 20;
1058         if (frame_size <= 0 || frame_size > buf_size) {
1059             av_log(avctx, AV_LOG_ERROR,
1060                    "Block %d has invalid size (size %d vs. %d bytes left)\n",
1061                    s->block, frame_size, buf_size);
1062             wavpack_decode_flush(avctx);
1063             return AVERROR_INVALIDDATA;
1064         }
1065         if ((ret = wavpack_decode_block(avctx, s->block,
1066                                         frame, buf, frame_size)) < 0) {
1067             wavpack_decode_flush(avctx);
1068             return ret;
1069         }
1070         s->block++;
1071         buf      += frame_size;
1072         buf_size -= frame_size;
1073     }
1074
1075     if (s->ch_offset != avctx->channels) {
1076         av_log(avctx, AV_LOG_ERROR, "Not enough channels coded in a packet.\n");
1077         return AVERROR_INVALIDDATA;
1078     }
1079
1080     *got_frame_ptr = 1;
1081
1082     return avpkt->size;
1083 }
1084
1085 AVCodec ff_wavpack_decoder = {
1086     .name           = "wavpack",
1087     .long_name      = NULL_IF_CONFIG_SMALL("WavPack"),
1088     .type           = AVMEDIA_TYPE_AUDIO,
1089     .id             = AV_CODEC_ID_WAVPACK,
1090     .priv_data_size = sizeof(WavpackContext),
1091     .init           = wavpack_decode_init,
1092     .close          = wavpack_decode_end,
1093     .decode         = wavpack_decode_frame,
1094     .flush          = wavpack_decode_flush,
1095     .init_thread_copy = ONLY_IF_THREADS_ENABLED(init_thread_copy),
1096     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_FRAME_THREADS,
1097 };