OSDN Git Service

wavpack: Check error codes rather than working around error conditions.
[coroid/libav_saccubus.git] / libavcodec / wavpack.c
index 4a7a9e5..0604452 100644 (file)
@@ -1,30 +1,31 @@
 /*
  * WavPack lossless audio decoder
- * Copyright (c) 2006 Konstantin Shishkov
+ * Copyright (c) 2006,2011 Konstantin Shishkov
  *
- * This file is part of FFmpeg.
+ * This file is part of Libav.
  *
- * FFmpeg is free software; you can redistribute it and/or
+ * Libav is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
- * FFmpeg is distributed in the hope that it will be useful,
+ * Libav is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
+ * License along with Libav; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 #define ALT_BITSTREAM_READER_LE
 #include "avcodec.h"
 #include "get_bits.h"
 #include "unary.h"
+#include "libavutil/audioconvert.h"
 
 /**
- * @file libavcodec/wavpack.c
+ * @file
  * WavPack lossless audio decoder
  */
 
 #define WV_HYBRID_BITRATE 0x00000200
 #define WV_HYBRID_BALANCE 0x00000400
 
+#define WV_FLT_SHIFT_ONES 0x01
+#define WV_FLT_SHIFT_SAME 0x02
+#define WV_FLT_SHIFT_SENT 0x04
+#define WV_FLT_ZERO_SENT  0x08
+#define WV_FLT_ZERO_SIGN  0x10
+
 enum WP_ID_Flags{
     WP_IDF_MASK   = 0x1F,
     WP_IDF_IGNORE = 0x20,
@@ -57,10 +64,17 @@ enum WP_ID{
     WP_ID_INT32INFO,
     WP_ID_DATA,
     WP_ID_CORR,
-    WP_ID_FLT,
+    WP_ID_EXTRABITS,
     WP_ID_CHANINFO
 };
 
+typedef struct SavedContext {
+    int offset;
+    int size;
+    int bits_used;
+    uint32_t crc;
+} SavedContext;
+
 #define MAX_TERMS 16
 
 typedef struct Decorr {
@@ -78,22 +92,49 @@ typedef struct WvChannel {
     int bitrate_acc, bitrate_delta;
 } WvChannel;
 
-typedef struct WavpackContext {
+typedef struct WavpackFrameContext {
     AVCodecContext *avctx;
     int frame_flags;
     int stereo, stereo_in;
     int joint;
     uint32_t CRC;
     GetBitContext gb;
+    int got_extra_bits;
+    uint32_t crc_extra_bits;
+    GetBitContext gb_extra_bits;
     int data_size; // in bits
     int samples;
     int terms;
     Decorr decorr[MAX_TERMS];
     int zero, one, zeroes;
+    int extra_bits;
     int and, or, shift;
     int post_shift;
     int hybrid, hybrid_bitrate;
+    int float_flag;
+    int float_shift;
+    int float_max_exp;
     WvChannel ch[2];
+    int samples_left;
+    int max_samples;
+    int pos;
+    SavedContext sc, extra_sc;
+} WavpackFrameContext;
+
+#define WV_MAX_FRAME_DECODERS 14
+
+typedef struct WavpackContext {
+    AVCodecContext *avctx;
+
+    WavpackFrameContext *fdec[WV_MAX_FRAME_DECODERS];
+    int fdec_num;
+
+    int multichannel;
+    int mkv_mode;
+    int block;
+    int samples;
+    int samples_left;
+    int ch_offset;
 } WavpackContext;
 
 // exponent table copied from WavPack source
@@ -200,7 +241,7 @@ static av_always_inline int get_tail(GetBitContext *gb, int k)
     return res;
 }
 
-static void update_error_limit(WavpackContext *ctx)
+static void update_error_limit(WavpackFrameContext *ctx)
 {
     int i, br[2], sl[2];
 
@@ -234,7 +275,7 @@ static void update_error_limit(WavpackContext *ctx)
     }
 }
 
-static int wv_get_value(WavpackContext *ctx, GetBitContext *gb, int channel, int *last)
+static int wv_get_value(WavpackFrameContext *ctx, GetBitContext *gb, int channel, int *last)
 {
     int t, t2;
     int sign, base, add, ret;
@@ -251,7 +292,14 @@ static int wv_get_value(WavpackContext *ctx, GetBitContext *gb, int channel, int
             }
         }else{
             t = get_unary_0_33(gb);
-            if(t >= 2) t = get_bits(gb, t - 1) | (1 << (t-1));
+            if(t >= 2){
+                if(get_bits_left(gb) < t-1)
+                    goto error;
+                t = get_bits(gb, t - 1) | (1 << (t-1));
+            }else{
+                if(get_bits_left(gb) < 0)
+                    goto error;
+            }
             ctx->zeroes = t;
             if(ctx->zeroes){
                 memset(ctx->ch[0].median, 0, sizeof(ctx->ch[0].median));
@@ -262,24 +310,24 @@ static int wv_get_value(WavpackContext *ctx, GetBitContext *gb, int channel, int
         }
     }
 
-    if(get_bits_count(gb) >= ctx->data_size){
-        *last = 1;
-        return 0;
-    }
-
     if(ctx->zero){
         t = 0;
         ctx->zero = 0;
     }else{
         t = get_unary_0_33(gb);
-        if(get_bits_count(gb) >= ctx->data_size){
-            *last = 1;
-            return 0;
-        }
+        if(get_bits_left(gb) < 0)
+            goto error;
         if(t == 16) {
             t2 = get_unary_0_33(gb);
-            if(t2 < 2) t += t2;
-            else t += get_bits(gb, t2 - 1) | (1 << (t2 - 1));
+            if(t2 < 2){
+                if(get_bits_left(gb) < 0)
+                    goto error;
+                t += t2;
+            }else{
+                if(get_bits_left(gb) < t2 - 1)
+                    goto error;
+                t += get_bits(gb, t2 - 1) | (1 << (t2 - 1));
+            }
         }
 
         if(ctx->one){
@@ -319,9 +367,13 @@ static int wv_get_value(WavpackContext *ctx, GetBitContext *gb, int channel, int
     }
     if(!c->error_limit){
         ret = base + get_tail(gb, add);
+        if (get_bits_left(gb) <= 0)
+            goto error;
     }else{
         int mid = (base*2 + add + 1) >> 1;
         while(add > c->error_limit){
+            if(get_bits_left(gb) <= 0)
+                goto error;
             if(get_bits1(gb)){
                 add -= (mid - base);
                 base = mid;
@@ -335,143 +387,123 @@ static int wv_get_value(WavpackContext *ctx, GetBitContext *gb, int channel, int
     if(ctx->hybrid_bitrate)
         c->slow_level += wp_log2(ret) - LEVEL_DECAY(c->slow_level);
     return sign ? ~ret : ret;
+
+error:
+    *last = 1;
+    return 0;
 }
 
-static int wv_unpack_stereo(WavpackContext *s, GetBitContext *gb, int16_t *dst)
+static inline int wv_get_value_integer(WavpackFrameContext *s, uint32_t *crc, int S)
 {
-    int i, j, count = 0;
-    int last, t;
-    int A, B, L, L2, R, R2, bit;
-    int pos = 0;
-    uint32_t crc = 0xFFFFFFFF;
+    int bit;
 
-    s->one = s->zero = s->zeroes = 0;
-    do{
-        L = wv_get_value(s, gb, 0, &last);
-        if(last) break;
-        R = wv_get_value(s, gb, 1, &last);
-        if(last) break;
-        for(i = 0; i < s->terms; i++){
-            t = s->decorr[i].value;
-            j = 0;
-            if(t > 0){
-                if(t > 8){
-                    if(t & 1){
-                        A = 2 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
-                        B = 2 * s->decorr[i].samplesB[0] - s->decorr[i].samplesB[1];
-                    }else{
-                        A = (3 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1]) >> 1;
-                        B = (3 * s->decorr[i].samplesB[0] - s->decorr[i].samplesB[1]) >> 1;
-                    }
-                    s->decorr[i].samplesA[1] = s->decorr[i].samplesA[0];
-                    s->decorr[i].samplesB[1] = s->decorr[i].samplesB[0];
-                    j = 0;
-                }else{
-                    A = s->decorr[i].samplesA[pos];
-                    B = s->decorr[i].samplesB[pos];
-                    j = (pos + t) & 7;
-                }
-                L2 = L + ((s->decorr[i].weightA * A + 512) >> 10);
-                R2 = R + ((s->decorr[i].weightB * B + 512) >> 10);
-                if(A && L) s->decorr[i].weightA -= ((((L ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
-                if(B && R) s->decorr[i].weightB -= ((((R ^ B) >> 30) & 2) - 1) * s->decorr[i].delta;
-                s->decorr[i].samplesA[j] = L = L2;
-                s->decorr[i].samplesB[j] = R = R2;
-            }else if(t == -1){
-                L2 = L + ((s->decorr[i].weightA * s->decorr[i].samplesA[0] + 512) >> 10);
-                UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, s->decorr[i].samplesA[0], L);
-                L = L2;
-                R2 = R + ((s->decorr[i].weightB * L2 + 512) >> 10);
-                UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, L2, R);
-                R = R2;
-                s->decorr[i].samplesA[0] = R;
-            }else{
-                R2 = R + ((s->decorr[i].weightB * s->decorr[i].samplesB[0] + 512) >> 10);
-                UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, s->decorr[i].samplesB[0], R);
-                R = R2;
-
-                if(t == -3){
-                    R2 = s->decorr[i].samplesA[0];
-                    s->decorr[i].samplesA[0] = R;
-                }
+    if(s->extra_bits){
+        S <<= s->extra_bits;
 
-                L2 = L + ((s->decorr[i].weightA * R2 + 512) >> 10);
-                UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, R2, L);
-                L = L2;
-                s->decorr[i].samplesB[0] = L;
-            }
+        if(s->got_extra_bits && get_bits_left(&s->gb_extra_bits) >= s->extra_bits){
+            S |= get_bits(&s->gb_extra_bits, s->extra_bits);
+            *crc = *crc * 9 + (S&0xffff) * 3 + ((unsigned)S>>16);
         }
-        pos = (pos + 1) & 7;
-        if(s->joint)
-            L += (R -= (L >> 1));
-        crc = (crc * 3 + L) * 3 + R;
-        bit = (L & s->and) | s->or;
-        *dst++ = (((L + bit) << s->shift) - bit) << s->post_shift;
-        bit = (R & s->and) | s->or;
-        *dst++ = (((R + bit) << s->shift) - bit) << s->post_shift;
-        count++;
-    }while(!last && count < s->samples);
-
-    if(crc != s->CRC){
-        av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
-        return -1;
     }
-    return count * 2;
+    bit = (S & s->and) | s->or;
+    return (((S + bit) << s->shift) - bit) << s->post_shift;
 }
 
-static int wv_unpack_mono(WavpackContext *s, GetBitContext *gb, int16_t *dst)
+static float wv_get_value_float(WavpackFrameContext *s, uint32_t *crc, int S)
 {
-    int i, j, count = 0;
-    int last, t;
-    int A, S, T, bit;
-    int pos = 0;
-    uint32_t crc = 0xFFFFFFFF;
+    union {
+        float    f;
+        uint32_t u;
+    } value;
 
-    s->one = s->zero = s->zeroes = 0;
-    do{
-        T = wv_get_value(s, gb, 0, &last);
-        S = 0;
-        if(last) break;
-        for(i = 0; i < s->terms; i++){
-            t = s->decorr[i].value;
-            if(t > 8){
-                if(t & 1)
-                    A = 2 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];
-                else
-                    A = (3 * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1]) >> 1;
-                s->decorr[i].samplesA[1] = s->decorr[i].samplesA[0];
-                j = 0;
+    int sign;
+    int exp = s->float_max_exp;
+
+    if(s->got_extra_bits){
+        const int max_bits = 1 + 23 + 8 + 1;
+        const int left_bits = get_bits_left(&s->gb_extra_bits);
+
+        if(left_bits + 8 * FF_INPUT_BUFFER_PADDING_SIZE < max_bits)
+            return 0.0;
+    }
+
+    if(S){
+        S <<= s->float_shift;
+        sign = S < 0;
+        if(sign)
+            S = -S;
+        if(S >= 0x1000000){
+            if(s->got_extra_bits && get_bits1(&s->gb_extra_bits)){
+                S = get_bits(&s->gb_extra_bits, 23);
             }else{
-                A = s->decorr[i].samplesA[pos];
-                j = (pos + t) & 7;
+                S = 0;
             }
-            S = T + ((s->decorr[i].weightA * A + 512) >> 10);
-            if(A && T) s->decorr[i].weightA -= ((((T ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
-            s->decorr[i].samplesA[j] = T = S;
-        }
-        pos = (pos + 1) & 7;
-        crc = crc * 3 + S;
-        bit = (S & s->and) | s->or;
-        *dst++ = (((S + bit) << s->shift) - bit) << s->post_shift;
-        count++;
-    }while(!last && count < s->samples);
+            exp = 255;
+        }else if(exp){
+            int shift = 23 - av_log2(S);
+            exp = s->float_max_exp;
+            if(exp <= shift){
+                shift = --exp;
+            }
+            exp -= shift;
 
-    if(crc != s->CRC){
-        av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
-        return -1;
+            if(shift){
+                S <<= shift;
+                if((s->float_flag & WV_FLT_SHIFT_ONES) ||
+                   (s->got_extra_bits && (s->float_flag & WV_FLT_SHIFT_SAME) && get_bits1(&s->gb_extra_bits)) ){
+                    S |= (1 << shift) - 1;
+                } else if(s->got_extra_bits && (s->float_flag & WV_FLT_SHIFT_SENT)){
+                    S |= get_bits(&s->gb_extra_bits, shift);
+                }
+            }
+        }else{
+            exp = s->float_max_exp;
+        }
+        S &= 0x7fffff;
+    }else{
+        sign = 0;
+        exp = 0;
+        if(s->got_extra_bits && (s->float_flag & WV_FLT_ZERO_SENT)){
+            if(get_bits1(&s->gb_extra_bits)){
+                S = get_bits(&s->gb_extra_bits, 23);
+                if(s->float_max_exp >= 25)
+                    exp = get_bits(&s->gb_extra_bits, 8);
+                sign = get_bits1(&s->gb_extra_bits);
+            }else{
+                if(s->float_flag & WV_FLT_ZERO_SIGN)
+                    sign = get_bits1(&s->gb_extra_bits);
+            }
+        }
     }
-    return count;
+
+    *crc = *crc * 27 + S * 9 + exp * 3 + sign;
+
+    value.u = (sign << 31) | (exp << 23) | S;
+    return value.f;
 }
 
-static int wv_unpack_stereo_hires(WavpackContext *s, GetBitContext *gb, int32_t *dst)
+static void wv_reset_saved_context(WavpackFrameContext *s)
+{
+    s->pos = 0;
+    s->samples_left = 0;
+    s->sc.crc = s->extra_sc.crc = 0xFFFFFFFF;
+}
+
+static inline int wv_unpack_stereo(WavpackFrameContext *s, GetBitContext *gb, void *dst, const int type)
 {
     int i, j, count = 0;
     int last, t;
-    int A, B, L, L2, R, R2, bit;
-    int pos = 0;
-    uint32_t crc = 0xFFFFFFFF;
+    int A, B, L, L2, R, R2;
+    int pos = s->pos;
+    uint32_t crc = s->sc.crc;
+    uint32_t crc_extra_bits = s->extra_sc.crc;
+    int16_t *dst16 = dst;
+    int32_t *dst32 = dst;
+    float   *dstfl = dst;
+    const int channel_pad = s->avctx->channels - 2;
 
-    s->one = s->zero = s->zeroes = 0;
+    if(s->samples_left == s->samples)
+        s->one = s->zero = s->zeroes = 0;
     do{
         L = wv_get_value(s, gb, 0, &last);
         if(last) break;
@@ -479,7 +511,6 @@ static int wv_unpack_stereo_hires(WavpackContext *s, GetBitContext *gb, int32_t
         if(last) break;
         for(i = 0; i < s->terms; i++){
             t = s->decorr[i].value;
-            j = 0;
             if(t > 0){
                 if(t > 8){
                     if(t & 1){
@@ -497,22 +528,36 @@ static int wv_unpack_stereo_hires(WavpackContext *s, GetBitContext *gb, int32_t
                     B = s->decorr[i].samplesB[pos];
                     j = (pos + t) & 7;
                 }
-                L2 = L + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
-                R2 = R + ((s->decorr[i].weightB * (int64_t)B + 512) >> 10);
+                if(type != AV_SAMPLE_FMT_S16){
+                    L2 = L + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
+                    R2 = R + ((s->decorr[i].weightB * (int64_t)B + 512) >> 10);
+                }else{
+                    L2 = L + ((s->decorr[i].weightA * A + 512) >> 10);
+                    R2 = R + ((s->decorr[i].weightB * B + 512) >> 10);
+                }
                 if(A && L) s->decorr[i].weightA -= ((((L ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
                 if(B && R) s->decorr[i].weightB -= ((((R ^ B) >> 30) & 2) - 1) * s->decorr[i].delta;
                 s->decorr[i].samplesA[j] = L = L2;
                 s->decorr[i].samplesB[j] = R = R2;
             }else if(t == -1){
-                L2 = L + ((s->decorr[i].weightA * (int64_t)s->decorr[i].samplesA[0] + 512) >> 10);
+                if(type != AV_SAMPLE_FMT_S16)
+                    L2 = L + ((s->decorr[i].weightA * (int64_t)s->decorr[i].samplesA[0] + 512) >> 10);
+                else
+                    L2 = L + ((s->decorr[i].weightA * s->decorr[i].samplesA[0] + 512) >> 10);
                 UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, s->decorr[i].samplesA[0], L);
                 L = L2;
-                R2 = R + ((s->decorr[i].weightB * (int64_t)L2 + 512) >> 10);
+                if(type != AV_SAMPLE_FMT_S16)
+                    R2 = R + ((s->decorr[i].weightB * (int64_t)L2 + 512) >> 10);
+                else
+                    R2 = R + ((s->decorr[i].weightB * L2 + 512) >> 10);
                 UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, L2, R);
                 R = R2;
                 s->decorr[i].samplesA[0] = R;
             }else{
-                R2 = R + ((s->decorr[i].weightB * (int64_t)s->decorr[i].samplesB[0] + 512) >> 10);
+                if(type != AV_SAMPLE_FMT_S16)
+                    R2 = R + ((s->decorr[i].weightB * (int64_t)s->decorr[i].samplesB[0] + 512) >> 10);
+                else
+                    R2 = R + ((s->decorr[i].weightB * s->decorr[i].samplesB[0] + 512) >> 10);
                 UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, s->decorr[i].samplesB[0], R);
                 R = R2;
 
@@ -521,7 +566,10 @@ static int wv_unpack_stereo_hires(WavpackContext *s, GetBitContext *gb, int32_t
                     s->decorr[i].samplesA[0] = R;
                 }
 
-                L2 = L + ((s->decorr[i].weightA * (int64_t)R2 + 512) >> 10);
+                if(type != AV_SAMPLE_FMT_S16)
+                    L2 = L + ((s->decorr[i].weightA * (int64_t)R2 + 512) >> 10);
+                else
+                    L2 = L + ((s->decorr[i].weightA * R2 + 512) >> 10);
                 UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, R2, L);
                 L = L2;
                 s->decorr[i].samplesB[0] = L;
@@ -531,29 +579,64 @@ static int wv_unpack_stereo_hires(WavpackContext *s, GetBitContext *gb, int32_t
         if(s->joint)
             L += (R -= (L >> 1));
         crc = (crc * 3 + L) * 3 + R;
-        bit = (L & s->and) | s->or;
-        *dst++ = (((L + bit) << s->shift) - bit) << s->post_shift;
-        bit = (R & s->and) | s->or;
-        *dst++ = (((R + bit) << s->shift) - bit) << s->post_shift;
+
+        if(type == AV_SAMPLE_FMT_FLT){
+            *dstfl++ = wv_get_value_float(s, &crc_extra_bits, L);
+            *dstfl++ = wv_get_value_float(s, &crc_extra_bits, R);
+            dstfl += channel_pad;
+        } else if(type == AV_SAMPLE_FMT_S32){
+            *dst32++ = wv_get_value_integer(s, &crc_extra_bits, L);
+            *dst32++ = wv_get_value_integer(s, &crc_extra_bits, R);
+            dst32 += channel_pad;
+        } else {
+            *dst16++ = wv_get_value_integer(s, &crc_extra_bits, L);
+            *dst16++ = wv_get_value_integer(s, &crc_extra_bits, R);
+            dst16 += channel_pad;
+        }
         count++;
-    }while(!last && count < s->samples);
+    }while(!last && count < s->max_samples);
 
-    if(crc != s->CRC){
-        av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
-        return -1;
+    if (last)
+        s->samples_left = 0;
+    else
+        s->samples_left -= count;
+    if(!s->samples_left){
+        wv_reset_saved_context(s);
+        if(crc != s->CRC){
+            av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
+            return -1;
+        }
+        if(s->got_extra_bits && crc_extra_bits != s->crc_extra_bits){
+            av_log(s->avctx, AV_LOG_ERROR, "Extra bits CRC error\n");
+            return -1;
+        }
+    }else{
+        s->pos = pos;
+        s->sc.crc = crc;
+        s->sc.bits_used = get_bits_count(&s->gb);
+        if(s->got_extra_bits){
+            s->extra_sc.crc = crc_extra_bits;
+            s->extra_sc.bits_used = get_bits_count(&s->gb_extra_bits);
+        }
     }
     return count * 2;
 }
 
-static int wv_unpack_mono_hires(WavpackContext *s, GetBitContext *gb, int32_t *dst)
+static inline int wv_unpack_mono(WavpackFrameContext *s, GetBitContext *gb, void *dst, const int type)
 {
     int i, j, count = 0;
     int last, t;
-    int A, S, T, bit;
-    int pos = 0;
-    uint32_t crc = 0xFFFFFFFF;
+    int A, S, T;
+    int pos = s->pos;
+    uint32_t crc = s->sc.crc;
+    uint32_t crc_extra_bits = s->extra_sc.crc;
+    int16_t *dst16 = dst;
+    int32_t *dst32 = dst;
+    float   *dstfl = dst;
+    const int channel_stride = s->avctx->channels;
 
-    s->one = s->zero = s->zeroes = 0;
+    if(s->samples_left == s->samples)
+        s->one = s->zero = s->zeroes = 0;
     do{
         T = wv_get_value(s, gb, 0, &last);
         S = 0;
@@ -571,81 +654,190 @@ static int wv_unpack_mono_hires(WavpackContext *s, GetBitContext *gb, int32_t *d
                 A = s->decorr[i].samplesA[pos];
                 j = (pos + t) & 7;
             }
-            S = T + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
+            if(type != AV_SAMPLE_FMT_S16)
+                S = T + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);
+            else
+                S = T + ((s->decorr[i].weightA * A + 512) >> 10);
             if(A && T) s->decorr[i].weightA -= ((((T ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;
             s->decorr[i].samplesA[j] = T = S;
         }
         pos = (pos + 1) & 7;
         crc = crc * 3 + S;
-        bit = (S & s->and) | s->or;
-        *dst++ = (((S + bit) << s->shift) - bit) << s->post_shift;
+
+        if(type == AV_SAMPLE_FMT_FLT){
+            *dstfl = wv_get_value_float(s, &crc_extra_bits, S);
+            dstfl += channel_stride;
+        }else if(type == AV_SAMPLE_FMT_S32){
+            *dst32 = wv_get_value_integer(s, &crc_extra_bits, S);
+            dst32 += channel_stride;
+        }else{
+            *dst16 = wv_get_value_integer(s, &crc_extra_bits, S);
+            dst16 += channel_stride;
+        }
         count++;
-    }while(!last && count < s->samples);
+    }while(!last && count < s->max_samples);
 
-    if(crc != s->CRC){
-        av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
-        return -1;
+    if (last)
+        s->samples_left = 0;
+    else
+        s->samples_left -= count;
+    if(!s->samples_left){
+        wv_reset_saved_context(s);
+        if(crc != s->CRC){
+            av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
+            return -1;
+        }
+        if(s->got_extra_bits && crc_extra_bits != s->crc_extra_bits){
+            av_log(s->avctx, AV_LOG_ERROR, "Extra bits CRC error\n");
+            return -1;
+        }
+    }else{
+        s->pos = pos;
+        s->sc.crc = crc;
+        s->sc.bits_used = get_bits_count(&s->gb);
+        if(s->got_extra_bits){
+            s->extra_sc.crc = crc_extra_bits;
+            s->extra_sc.bits_used = get_bits_count(&s->gb_extra_bits);
+        }
     }
     return count;
 }
 
+static av_cold int wv_alloc_frame_context(WavpackContext *c)
+{
+
+    if(c->fdec_num == WV_MAX_FRAME_DECODERS)
+        return -1;
+
+    c->fdec[c->fdec_num] = av_mallocz(sizeof(**c->fdec));
+    if(!c->fdec[c->fdec_num])
+        return -1;
+    c->fdec_num++;
+    c->fdec[c->fdec_num - 1]->avctx = c->avctx;
+    wv_reset_saved_context(c->fdec[c->fdec_num - 1]);
+
+    return 0;
+}
+
 static av_cold int wavpack_decode_init(AVCodecContext *avctx)
 {
     WavpackContext *s = avctx->priv_data;
 
     s->avctx = avctx;
-    s->stereo = (avctx->channels == 2);
     if(avctx->bits_per_coded_sample <= 16)
-        avctx->sample_fmt = SAMPLE_FMT_S16;
+        avctx->sample_fmt = AV_SAMPLE_FMT_S16;
     else
-        avctx->sample_fmt = SAMPLE_FMT_S32;
-    avctx->channel_layout = (avctx->channels==2) ? CH_LAYOUT_STEREO : CH_LAYOUT_MONO;
+        avctx->sample_fmt = AV_SAMPLE_FMT_S32;
+    if(avctx->channels <= 2 && !avctx->channel_layout)
+        avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
+
+    s->multichannel = avctx->channels > 2;
+    /* lavf demuxer does not provide extradata, Matroska stores 0x403
+       there, use this to detect decoding mode for multichannel */
+    s->mkv_mode = 0;
+    if(s->multichannel && avctx->extradata && avctx->extradata_size == 2){
+        int ver = AV_RL16(avctx->extradata);
+        if(ver >= 0x402 && ver <= 0x410)
+            s->mkv_mode = 1;
+    }
+
+    s->fdec_num = 0;
 
     return 0;
 }
 
-static int wavpack_decode_frame(AVCodecContext *avctx,
-                            void *data, int *data_size,
-                            AVPacket *avpkt)
+static av_cold int wavpack_decode_end(AVCodecContext *avctx)
 {
-    const uint8_t *buf = avpkt->data;
-    int buf_size = avpkt->size;
     WavpackContext *s = avctx->priv_data;
-    int16_t *samples = data;
-    int32_t *samples32 = data;
+    int i;
+
+    for(i = 0; i < s->fdec_num; i++)
+        av_freep(&s->fdec[i]);
+    s->fdec_num = 0;
+
+    return 0;
+}
+
+static int wavpack_decode_block(AVCodecContext *avctx, int block_no,
+                                void *data, int *data_size,
+                                const uint8_t *buf, int buf_size)
+{
+    WavpackContext *wc = avctx->priv_data;
+    WavpackFrameContext *s;
+    void *samples = data;
     int samplecount;
-    int got_terms = 0, got_weights = 0, got_samples = 0, got_entropy = 0, got_bs = 0;
+    int got_terms = 0, got_weights = 0, got_samples = 0, got_entropy = 0, got_bs = 0, got_float = 0;
     int got_hybrid = 0;
+    const uint8_t* orig_buf = buf;
     const uint8_t* buf_end = buf + buf_size;
     int i, j, id, size, ssize, weights, t;
-    int bpp = avctx->bits_per_coded_sample <= 16 ? 2 : 4;
+    int bpp, chan, chmask;
 
     if (buf_size == 0){
         *data_size = 0;
         return 0;
     }
 
-    memset(s->decorr, 0, MAX_TERMS * sizeof(Decorr));
-    memset(s->ch, 0, sizeof(s->ch));
-    s->and = s->or = s->shift = 0;
-
-    s->samples = AV_RL32(buf); buf += 4;
-    if(!s->samples){
-        *data_size = 0;
-        return buf_size;
+    if(block_no >= wc->fdec_num && wv_alloc_frame_context(wc) < 0){
+        av_log(avctx, AV_LOG_ERROR, "Error creating frame decode context\n");
+        return -1;
     }
-    /* should not happen but who knows */
-    if(s->samples * bpp * avctx->channels > *data_size){
-        av_log(avctx, AV_LOG_ERROR, "Packet size is too big to be handled in lavc!\n");
+
+    s = wc->fdec[block_no];
+    if(!s){
+        av_log(avctx, AV_LOG_ERROR, "Context for block %d is not present\n", block_no);
         return -1;
     }
+
+    if(!s->samples_left){
+        memset(s->decorr, 0, MAX_TERMS * sizeof(Decorr));
+        memset(s->ch, 0, sizeof(s->ch));
+        s->extra_bits = 0;
+        s->and = s->or = s->shift = 0;
+        s->got_extra_bits = 0;
+    }
+
+    if(!wc->mkv_mode){
+        s->samples = AV_RL32(buf); buf += 4;
+        if(!s->samples){
+            *data_size = 0;
+            return 0;
+        }
+    }else{
+        s->samples = wc->samples;
+    }
     s->frame_flags = AV_RL32(buf); buf += 4;
+    if(s->frame_flags&0x80){
+        bpp = sizeof(float);
+        avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
+    } else if((s->frame_flags&0x03) <= 1){
+        bpp = 2;
+        avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+    } else {
+        bpp = 4;
+        avctx->sample_fmt = AV_SAMPLE_FMT_S32;
+    }
+    samples = (uint8_t*)samples + bpp * wc->ch_offset;
+
+    s->stereo = !(s->frame_flags & WV_MONO);
     s->stereo_in = (s->frame_flags & WV_FALSE_STEREO) ? 0 : s->stereo;
     s->joint = s->frame_flags & WV_JOINT_STEREO;
     s->hybrid = s->frame_flags & WV_HYBRID_MODE;
     s->hybrid_bitrate = s->frame_flags & WV_HYBRID_BITRATE;
     s->post_shift = 8 * (bpp-1-(s->frame_flags&0x03)) + ((s->frame_flags >> 13) & 0x1f);
     s->CRC = AV_RL32(buf); buf += 4;
+    if(wc->mkv_mode)
+        buf += 4; //skip block size;
+
+    wc->ch_offset += 1 + s->stereo;
+
+    s->max_samples = *data_size / (bpp * avctx->channels);
+    s->max_samples = FFMIN(s->max_samples, s->samples);
+    if(s->samples_left > 0){
+        s->max_samples = FFMIN(s->max_samples, s->samples_left);
+        buf = buf_end;
+    }
+
     // parse metadata blocks
     while(buf < buf_end){
         id = *buf++;
@@ -780,12 +972,14 @@ static int wavpack_decode_frame(AVCodecContext *avctx,
             got_hybrid = 1;
             break;
         case WP_ID_INT32INFO:
-            if(size != 4 || *buf){
+            if(size != 4){
                 av_log(avctx, AV_LOG_ERROR, "Invalid INT32INFO, size = %i, sent_bits = %i\n", size, *buf);
                 buf += ssize;
                 continue;
             }
-            if(buf[1])
+            if(buf[0])
+                s->extra_bits = buf[0];
+            else if(buf[1])
                 s->shift = buf[1];
             else if(buf[2]){
                 s->and = s->or = 1;
@@ -796,85 +990,252 @@ static int wavpack_decode_frame(AVCodecContext *avctx,
             }
             buf += 4;
             break;
+        case WP_ID_FLOATINFO:
+            if(size != 4){
+                av_log(avctx, AV_LOG_ERROR, "Invalid FLOATINFO, size = %i\n", size);
+                buf += ssize;
+                continue;
+            }
+            s->float_flag = buf[0];
+            s->float_shift = buf[1];
+            s->float_max_exp = buf[2];
+            buf += 4;
+            got_float = 1;
+            break;
         case WP_ID_DATA:
+            s->sc.offset = buf - orig_buf;
+            s->sc.size   = size * 8;
             init_get_bits(&s->gb, buf, size * 8);
             s->data_size = size * 8;
             buf += size;
             got_bs = 1;
             break;
+        case WP_ID_EXTRABITS:
+            if(size <= 4){
+                av_log(avctx, AV_LOG_ERROR, "Invalid EXTRABITS, size = %i\n", size);
+                buf += size;
+                continue;
+            }
+            s->extra_sc.offset = buf - orig_buf;
+            s->extra_sc.size   = size * 8;
+            init_get_bits(&s->gb_extra_bits, buf, size * 8);
+            s->crc_extra_bits = get_bits_long(&s->gb_extra_bits, 32);
+            buf += size;
+            s->got_extra_bits = 1;
+            break;
+        case WP_ID_CHANINFO:
+            if(size <= 1){
+                av_log(avctx, AV_LOG_ERROR, "Insufficient channel information\n");
+                return -1;
+            }
+            chan = *buf++;
+            switch(size - 2){
+            case 0:
+                chmask = *buf;
+                break;
+            case 1:
+                chmask = AV_RL16(buf);
+                break;
+            case 2:
+                chmask = AV_RL24(buf);
+                break;
+            case 3:
+                chmask = AV_RL32(buf);
+                break;
+            case 5:
+                chan |= (buf[1] & 0xF) << 8;
+                chmask = AV_RL24(buf + 2);
+                break;
+            default:
+                av_log(avctx, AV_LOG_ERROR, "Invalid channel info size %d\n", size);
+                chan = avctx->channels;
+                chmask = avctx->channel_layout;
+            }
+            if(chan != avctx->channels){
+                av_log(avctx, AV_LOG_ERROR, "Block reports total %d channels, decoder believes it's %d channels\n",
+                       chan, avctx->channels);
+                return -1;
+            }
+            if(!avctx->channel_layout)
+                avctx->channel_layout = chmask;
+            buf += size - 1;
+            break;
         default:
             buf += size;
         }
         if(id & WP_IDF_ODD) buf++;
     }
-    if(!got_terms){
-        av_log(avctx, AV_LOG_ERROR, "No block with decorrelation terms\n");
-        return -1;
-    }
-    if(!got_weights){
-        av_log(avctx, AV_LOG_ERROR, "No block with decorrelation weights\n");
-        return -1;
-    }
-    if(!got_samples){
-        av_log(avctx, AV_LOG_ERROR, "No block with decorrelation samples\n");
-        return -1;
-    }
-    if(!got_entropy){
-        av_log(avctx, AV_LOG_ERROR, "No block with entropy info\n");
-        return -1;
-    }
-    if(s->hybrid && !got_hybrid){
-        av_log(avctx, AV_LOG_ERROR, "Hybrid config not found\n");
-        return -1;
-    }
-    if(!got_bs){
-        av_log(avctx, AV_LOG_ERROR, "Packed samples not found\n");
-        return -1;
+    if(!s->samples_left){
+        if(!got_terms){
+            av_log(avctx, AV_LOG_ERROR, "No block with decorrelation terms\n");
+            return -1;
+        }
+        if(!got_weights){
+            av_log(avctx, AV_LOG_ERROR, "No block with decorrelation weights\n");
+            return -1;
+        }
+        if(!got_samples){
+            av_log(avctx, AV_LOG_ERROR, "No block with decorrelation samples\n");
+            return -1;
+        }
+        if(!got_entropy){
+            av_log(avctx, AV_LOG_ERROR, "No block with entropy info\n");
+            return -1;
+        }
+        if(s->hybrid && !got_hybrid){
+            av_log(avctx, AV_LOG_ERROR, "Hybrid config not found\n");
+            return -1;
+        }
+        if(!got_bs){
+            av_log(avctx, AV_LOG_ERROR, "Packed samples not found\n");
+            return -1;
+        }
+        if(!got_float && avctx->sample_fmt == AV_SAMPLE_FMT_FLT){
+            av_log(avctx, AV_LOG_ERROR, "Float information not found\n");
+            return -1;
+        }
+        if(s->got_extra_bits && avctx->sample_fmt != AV_SAMPLE_FMT_FLT){
+            const int size = get_bits_left(&s->gb_extra_bits);
+            const int wanted = s->samples * s->extra_bits << s->stereo_in;
+            if(size < wanted){
+                av_log(avctx, AV_LOG_ERROR, "Too small EXTRABITS\n");
+                s->got_extra_bits = 0;
+            }
+        }
+        s->samples_left = s->samples;
+    }else{
+        init_get_bits(&s->gb, orig_buf + s->sc.offset, s->sc.size);
+        skip_bits_long(&s->gb, s->sc.bits_used);
+        if(s->got_extra_bits){
+            init_get_bits(&s->gb_extra_bits, orig_buf + s->extra_sc.offset,
+                          s->extra_sc.size);
+            skip_bits_long(&s->gb_extra_bits, s->extra_sc.bits_used);
+        }
     }
 
     if(s->stereo_in){
-        if(bpp == 2)
-            samplecount = wv_unpack_stereo(s, &s->gb, samples);
+        if(avctx->sample_fmt == AV_SAMPLE_FMT_S16)
+            samplecount = wv_unpack_stereo(s, &s->gb, samples, AV_SAMPLE_FMT_S16);
+        else if(avctx->sample_fmt == AV_SAMPLE_FMT_S32)
+            samplecount = wv_unpack_stereo(s, &s->gb, samples, AV_SAMPLE_FMT_S32);
         else
-            samplecount = wv_unpack_stereo_hires(s, &s->gb, samples32);
+            samplecount = wv_unpack_stereo(s, &s->gb, samples, AV_SAMPLE_FMT_FLT);
+
+        if (samplecount < 0)
+            return -1;
+
+        samplecount >>= 1;
     }else{
-        if(bpp == 2)
-            samplecount = wv_unpack_mono(s, &s->gb, samples);
+        const int channel_stride = avctx->channels;
+
+        if(avctx->sample_fmt == AV_SAMPLE_FMT_S16)
+            samplecount = wv_unpack_mono(s, &s->gb, samples, AV_SAMPLE_FMT_S16);
+        else if(avctx->sample_fmt == AV_SAMPLE_FMT_S32)
+            samplecount = wv_unpack_mono(s, &s->gb, samples, AV_SAMPLE_FMT_S32);
         else
-            samplecount = wv_unpack_mono_hires(s, &s->gb, samples32);
-        if(s->stereo && bpp == 2){
-            int16_t *dst = samples + samplecount * 2;
-            int16_t *src = samples + samplecount;
+            samplecount = wv_unpack_mono(s, &s->gb, samples, AV_SAMPLE_FMT_FLT);
+
+        if (samplecount < 0)
+            return -1;
+
+        if(s->stereo && avctx->sample_fmt == AV_SAMPLE_FMT_S16){
+            int16_t *dst = (int16_t*)samples + 1;
+            int16_t *src = (int16_t*)samples;
+            int cnt = samplecount;
+            while(cnt--){
+                *dst = *src;
+                src += channel_stride;
+                dst += channel_stride;
+            }
+        }else if(s->stereo && avctx->sample_fmt == AV_SAMPLE_FMT_S32){
+            int32_t *dst = (int32_t*)samples + 1;
+            int32_t *src = (int32_t*)samples;
             int cnt = samplecount;
             while(cnt--){
-                *--dst = *--src;
-                *--dst = *src;
+                *dst = *src;
+                src += channel_stride;
+                dst += channel_stride;
             }
-            samplecount *= 2;
-        }else if(s->stereo){ //32-bit output
-            int32_t *dst = samples32 + samplecount * 2;
-            int32_t *src = samples32 + samplecount;
+        }else if(s->stereo){
+            float *dst = (float*)samples + 1;
+            float *src = (float*)samples;
             int cnt = samplecount;
             while(cnt--){
-                *--dst = *--src;
-                *--dst = *src;
+                *dst = *src;
+                src += channel_stride;
+                dst += channel_stride;
             }
-            samplecount *= 2;
         }
     }
-    *data_size = samplecount * bpp;
 
-    return buf_size;
+    wc->samples_left = s->samples_left;
+
+    return samplecount * bpp;
+}
+
+static int wavpack_decode_frame(AVCodecContext *avctx,
+                            void *data, int *data_size,
+                            AVPacket *avpkt)
+{
+    WavpackContext *s = avctx->priv_data;
+    const uint8_t *buf = avpkt->data;
+    int buf_size = avpkt->size;
+    int frame_size;
+    int samplecount = 0;
+
+    s->block = 0;
+    s->samples_left = 0;
+    s->ch_offset = 0;
+
+    if(s->mkv_mode){
+        s->samples = AV_RL32(buf); buf += 4;
+    }
+    while(buf_size > 0){
+        if(!s->multichannel){
+            frame_size = buf_size;
+        }else{
+            if(!s->mkv_mode){
+                frame_size = AV_RL32(buf) - 12; buf += 4; buf_size -= 4;
+            }else{
+                if(buf_size < 12) //MKV files can have zero flags after last block
+                    break;
+                frame_size = AV_RL32(buf + 8) + 12;
+            }
+        }
+        if(frame_size < 0 || frame_size > buf_size){
+            av_log(avctx, AV_LOG_ERROR, "Block %d has invalid size (size %d vs. %d bytes left)\n",
+                   s->block, frame_size, buf_size);
+            return -1;
+        }
+        if((samplecount = wavpack_decode_block(avctx, s->block, data,
+                                               data_size, buf, frame_size)) < 0)
+            return -1;
+        s->block++;
+        buf += frame_size; buf_size -= frame_size;
+    }
+    *data_size = samplecount * avctx->channels;
+
+    return s->samples_left > 0 ? 0 : avpkt->size;
+}
+
+static void wavpack_decode_flush(AVCodecContext *avctx)
+{
+    WavpackContext *s = avctx->priv_data;
+    int i;
+
+    for (i = 0; i < s->fdec_num; i++)
+        wv_reset_saved_context(s->fdec[i]);
 }
 
-AVCodec wavpack_decoder = {
-    "wavpack",
-    CODEC_TYPE_AUDIO,
-    CODEC_ID_WAVPACK,
-    sizeof(WavpackContext),
-    wavpack_decode_init,
-    NULL,
-    NULL,
-    wavpack_decode_frame,
+AVCodec ff_wavpack_decoder = {
+    .name           = "wavpack",
+    .type           = AVMEDIA_TYPE_AUDIO,
+    .id             = CODEC_ID_WAVPACK,
+    .priv_data_size = sizeof(WavpackContext),
+    .init           = wavpack_decode_init,
+    .close          = wavpack_decode_end,
+    .decode         = wavpack_decode_frame,
+    .flush          = wavpack_decode_flush,
+    .capabilities = CODEC_CAP_SUBFRAMES,
     .long_name = NULL_IF_CONFIG_SMALL("WavPack"),
 };