lavc: Add per-thread surfaces in get_hw_frame_parameters()
[ffmpeg.git] / libavcodec / wmalosslessdec.c
index ec5bbc4..b829987 100644 (file)
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
+#include <inttypes.h>
+
+#include "libavutil/attributes.h"
+#include "libavutil/avassert.h"
+
 #include "avcodec.h"
+#include "bitstream.h"
 #include "internal.h"
-#include "get_bits.h"
 #include "put_bits.h"
 #include "wma.h"
 #include "wma_common.h"
@@ -37,7 +42,7 @@
 #define MAX_ORDER             256
 
 #define WMALL_BLOCK_MIN_BITS    6                       ///< log2 of min block size
-#define WMALL_BLOCK_MAX_BITS   12                       ///< log2 of max block size
+#define WMALL_BLOCK_MAX_BITS   14                       ///< log2 of max block size
 #define WMALL_BLOCK_MAX_SIZE (1 << WMALL_BLOCK_MAX_BITS)    ///< maximum block size
 #define WMALL_BLOCK_SIZES    (WMALL_BLOCK_MAX_BITS - WMALL_BLOCK_MIN_BITS + 1) ///< possible block sizes
 
@@ -45,7 +50,7 @@
 /**
  * @brief frame-specific decoder context for a single channel
  */
-typedef struct {
+typedef struct WmallChannelCtx {
     int16_t     prev_block_len;                         ///< length of the previous block
     uint8_t     transmit_coefs;
     uint8_t     num_subframes;
@@ -63,8 +68,8 @@ typedef struct {
 typedef struct WmallDecodeCtx {
     /* generic decoder variables */
     AVCodecContext  *avctx;
-    AVFrame         frame;
-    uint8_t         frame_data[MAX_FRAMESIZE + FF_INPUT_BUFFER_PADDING_SIZE];  ///< compressed frame data
+    AVFrame         *frame;
+    uint8_t         frame_data[MAX_FRAMESIZE + AV_INPUT_BUFFER_PADDING_SIZE];  ///< compressed frame data
     PutBitContext   pb;                             ///< context for filling the frame_data buffer
 
     /* frame size dependent frame information (set during initialization) */
@@ -82,7 +87,7 @@ typedef struct WmallDecodeCtx {
     uint16_t        min_samples_per_subframe;
 
     /* packet decode state */
-    GetBitContext   pgb;                            ///< bitstream reader context for the packet
+    BitstreamContext pbc;                           ///< bitstream reader context for the packet
     int             next_packet_start;              ///< start offset of the next WMA packet in the demuxer packet
     uint8_t         packet_offset;                  ///< offset to the frame in the packet
     uint8_t         packet_sequence_number;         ///< current packet number
@@ -94,12 +99,10 @@ typedef struct WmallDecodeCtx {
 
     /* frame decode state */
     uint32_t        frame_num;                      ///< current frame number (not used for decoding)
-    GetBitContext   gb;                             ///< bitstream reader context
+    BitstreamContext bc;                            ///< bitstream reader context
     int             buf_bit_size;                   ///< buffer size in bits
-    int16_t         *samples_16;                    ///< current samplebuffer pointer (16-bit)
-    int16_t         *samples_16_end;                ///< maximum samplebuffer pointer
-    int             *samples_32;                    ///< current samplebuffer pointer (24-bit)
-    int             *samples_32_end;                ///< maximum samplebuffer pointer
+    int16_t         *samples_16[WMALL_MAX_CHANNELS]; ///< current sample buffer pointer (16-bit)
+    int32_t         *samples_32[WMALL_MAX_CHANNELS]; ///< current sample buffer pointer (24-bit)
     uint8_t         drc_gain;                       ///< gain for the DRC tool
     int8_t          skip_frame;                     ///< skip output step
     int8_t          parsed_all_subframes;           ///< all subframes decoded?
@@ -126,10 +129,10 @@ typedef struct WmallDecodeCtx {
 
     int8_t  mclms_order;
     int8_t  mclms_scaling;
-    int16_t mclms_coeffs[128];
-    int16_t mclms_coeffs_cur[4];
-    int16_t mclms_prevvalues[64];
-    int16_t mclms_updates[64];
+    int16_t mclms_coeffs[WMALL_MAX_CHANNELS * WMALL_MAX_CHANNELS * 32];
+    int16_t mclms_coeffs_cur[WMALL_MAX_CHANNELS * WMALL_MAX_CHANNELS];
+    int16_t mclms_prevvalues[WMALL_MAX_CHANNELS * 2 * 32];
+    int16_t mclms_updates[WMALL_MAX_CHANNELS * 2 * 32];
     int     mclms_recent;
 
     int     movave_scaling;
@@ -159,14 +162,14 @@ typedef struct WmallDecodeCtx {
 
     int ave_sum[2];
 
-    int channel_residues[2][2048];
+    int channel_residues[2][WMALL_BLOCK_MAX_SIZE];
 
     int lpc_coefs[2][40];
     int lpc_order;
     int lpc_scaling;
     int lpc_intbits;
 
-    int channel_coeffs[2][2048];
+    int channel_coeffs[2][WMALL_BLOCK_MAX_SIZE];
 } WmallDecodeCtx;
 
 
@@ -175,7 +178,7 @@ static av_cold int decode_init(AVCodecContext *avctx)
     WmallDecodeCtx *s  = avctx->priv_data;
     uint8_t *edata_ptr = avctx->extradata;
     unsigned int channel_mask;
-    int i, log2_max_num_subframes, num_possible_block_sizes;
+    int i, log2_max_num_subframes;
 
     s->avctx = avctx;
     init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
@@ -185,24 +188,24 @@ static av_cold int decode_init(AVCodecContext *avctx)
         channel_mask       = AV_RL32(edata_ptr +  2);
         s->bits_per_sample = AV_RL16(edata_ptr);
         if (s->bits_per_sample == 16)
-            avctx->sample_fmt = AV_SAMPLE_FMT_S16;
+            avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
         else if (s->bits_per_sample == 24) {
-            avctx->sample_fmt = AV_SAMPLE_FMT_S32;
-            av_log_missing_feature(avctx, "bit-depth higher than 16", 0);
+            avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
+            avpriv_report_missing_feature(avctx, "Bit-depth higher than 16");
             return AVERROR_PATCHWELCOME;
         } else {
-            av_log(avctx, AV_LOG_ERROR, "Unknown bit-depth: %d\n",
+            av_log(avctx, AV_LOG_ERROR, "Unknown bit-depth: %"PRIu8"\n",
                    s->bits_per_sample);
             return AVERROR_INVALIDDATA;
         }
         /* dump the extradata */
         for (i = 0; i < avctx->extradata_size; i++)
-            av_dlog(avctx, "[%x] ", avctx->extradata[i]);
-        av_dlog(avctx, "\n");
+            ff_dlog(avctx, "[%x] ", avctx->extradata[i]);
+        ff_dlog(avctx, "\n");
 
     } else {
-        av_log_ask_for_sample(avctx, "Unsupported extradata size\n");
-        return AVERROR_INVALIDDATA;
+        avpriv_request_sample(avctx, "Unsupported extradata size");
+        return AVERROR_PATCHWELCOME;
     }
 
     /* generic init */
@@ -216,6 +219,7 @@ static av_cold int decode_init(AVCodecContext *avctx)
     /* get frame len */
     s->samples_per_frame = 1 << ff_wma_get_frame_len_bits(avctx->sample_rate,
                                                           3, s->decode_flags);
+    av_assert0(s->samples_per_frame <= WMALL_BLOCK_MAX_SIZE);
 
     /* init previous block len */
     for (i = 0; i < avctx->channels; i++)
@@ -227,13 +231,12 @@ static av_cold int decode_init(AVCodecContext *avctx)
     s->max_subframe_len_bit = 0;
     s->subframe_len_bits    = av_log2(log2_max_num_subframes) + 1;
 
-    num_possible_block_sizes     = log2_max_num_subframes + 1;
     s->min_samples_per_subframe  = s->samples_per_frame / s->max_num_subframes;
     s->dynamic_range_compression = s->decode_flags & 0x80;
     s->bV3RTM                    = s->decode_flags & 0x100;
 
     if (s->max_num_subframes > MAX_SUBFRAMES) {
-        av_log(avctx, AV_LOG_ERROR, "invalid number of subframes %i\n",
+        av_log(avctx, AV_LOG_ERROR, "invalid number of subframes %"PRIu8"\n",
                s->max_num_subframes);
         return AVERROR_INVALIDDATA;
     }
@@ -251,16 +254,19 @@ static av_cold int decode_init(AVCodecContext *avctx)
     }
 
     if (s->num_channels < 0) {
-        av_log(avctx, AV_LOG_ERROR, "invalid number of channels %d\n",
+        av_log(avctx, AV_LOG_ERROR, "invalid number of channels %"PRId8"\n",
                s->num_channels);
         return AVERROR_INVALIDDATA;
     } else if (s->num_channels > WMALL_MAX_CHANNELS) {
-        av_log_ask_for_sample(avctx, "unsupported number of channels\n");
+        avpriv_request_sample(avctx,
+                              "More than %d channels", WMALL_MAX_CHANNELS);
         return AVERROR_PATCHWELCOME;
     }
 
-    avcodec_get_frame_defaults(&s->frame);
-    avctx->coded_frame    = &s->frame;
+    s->frame = av_frame_alloc();
+    if (!s->frame)
+        return AVERROR(ENOMEM);
+
     avctx->channel_layout = channel_mask;
     return 0;
 }
@@ -280,7 +286,7 @@ static int decode_subframe_length(WmallDecodeCtx *s, int offset)
         return s->min_samples_per_subframe;
 
     len             = av_log2(s->max_num_subframes - 1) + 1;
-    frame_len_ratio = get_bits(&s->gb, len);
+    frame_len_ratio = bitstream_read(&s->bc, len);
     subframe_len    = s->min_samples_per_subframe * (frame_len_ratio + 1);
 
     /* sanity check the length */
@@ -326,27 +332,34 @@ static int decode_tilehdr(WmallDecodeCtx *s)
     for (c = 0; c < s->num_channels; c++)
         s->channel[c].num_subframes = 0;
 
-    tile_aligned = get_bits1(&s->gb);
+    tile_aligned = bitstream_read_bit(&s->bc);
     if (s->max_num_subframes == 1 || tile_aligned)
         fixed_channel_layout = 1;
 
     /* loop until the frame data is split between the subframes */
     do {
-        int subframe_len;
+        int subframe_len, in_use = 0;
 
         /* check which channels contain the subframe */
         for (c = 0; c < s->num_channels; c++) {
             if (num_samples[c] == min_channel_len) {
                 if (fixed_channel_layout || channels_for_cur_subframe == 1 ||
                    (min_channel_len == s->samples_per_frame - s->min_samples_per_subframe)) {
-                    contains_subframe[c] = 1;
+                    contains_subframe[c] = in_use = 1;
                 } else {
-                    contains_subframe[c] = get_bits1(&s->gb);
+                    if (bitstream_read_bit(&s->bc))
+                        contains_subframe[c] = in_use = 1;
                 }
             } else
                 contains_subframe[c] = 0;
         }
 
+        if (!in_use) {
+            av_log(s->avctx, AV_LOG_ERROR,
+                   "Found empty subframe\n");
+            return AVERROR_INVALIDDATA;
+        }
+
         /* get subframe length, subframe_len == 0 is not allowed */
         if ((subframe_len = decode_subframe_length(s, min_channel_len)) <= 0)
             return AVERROR_INVALIDDATA;
@@ -366,7 +379,7 @@ static int decode_tilehdr(WmallDecodeCtx *s)
                 ++chan->num_subframes;
                 if (num_samples[c] > s->samples_per_frame) {
                     av_log(s->avctx, AV_LOG_ERROR, "broken frame: "
-                           "channel len(%d) > samples_per_frame(%d)\n",
+                           "channel len(%"PRIu16") > samples_per_frame(%"PRIu16")\n",
                            num_samples[c], s->samples_per_frame);
                     return AVERROR_INVALIDDATA;
                 }
@@ -394,32 +407,32 @@ static int decode_tilehdr(WmallDecodeCtx *s)
 static void decode_ac_filter(WmallDecodeCtx *s)
 {
     int i;
-    s->acfilter_order   = get_bits(&s->gb, 4) + 1;
-    s->acfilter_scaling = get_bits(&s->gb, 4);
+    s->acfilter_order   = bitstream_read(&s->bc, 4) + 1;
+    s->acfilter_scaling = bitstream_read(&s->bc, 4);
 
     for (i = 0; i < s->acfilter_order; i++)
-        s->acfilter_coeffs[i] = get_bits(&s->gb, s->acfilter_scaling) + 1;
+        s->acfilter_coeffs[i] = bitstream_read(&s->bc, s->acfilter_scaling) + 1;
 }
 
 static void decode_mclms(WmallDecodeCtx *s)
 {
-    s->mclms_order   = (get_bits(&s->gb, 4) + 1) * 2;
-    s->mclms_scaling = get_bits(&s->gb, 4);
-    if (get_bits1(&s->gb)) {
+    s->mclms_order   = (bitstream_read(&s->bc, 4) + 1) * 2;
+    s->mclms_scaling =  bitstream_read(&s->bc, 4);
+    if (bitstream_read_bit(&s->bc)) {
         int i, send_coef_bits;
         int cbits = av_log2(s->mclms_scaling + 1);
         if (1 << cbits < s->mclms_scaling + 1)
             cbits++;
 
-        send_coef_bits = (cbits ? get_bits(&s->gb, cbits) : 0) + 2;
+        send_coef_bits = bitstream_read(&s->bc, cbits) + 2;
 
         for (i = 0; i < s->mclms_order * s->num_channels * s->num_channels; i++)
-            s->mclms_coeffs[i] = get_bits(&s->gb, send_coef_bits);
+            s->mclms_coeffs[i] = bitstream_read(&s->bc, send_coef_bits);
 
         for (i = 0; i < s->num_channels; i++) {
             int c;
             for (c = 0; c < i; c++)
-                s->mclms_coeffs_cur[i * s->num_channels + c] = get_bits(&s->gb, send_coef_bits);
+                s->mclms_coeffs_cur[i * s->num_channels + c] = bitstream_read(&s->bc, send_coef_bits);
         }
     }
 }
@@ -427,12 +440,12 @@ static void decode_mclms(WmallDecodeCtx *s)
 static int decode_cdlms(WmallDecodeCtx *s)
 {
     int c, i;
-    int cdlms_send_coef = get_bits1(&s->gb);
+    int cdlms_send_coef = bitstream_read_bit(&s->bc);
 
     for (c = 0; c < s->num_channels; c++) {
-        s->cdlms_ttl[c] = get_bits(&s->gb, 3) + 1;
+        s->cdlms_ttl[c] = bitstream_read(&s->bc, 3) + 1;
         for (i = 0; i < s->cdlms_ttl[c]; i++) {
-            s->cdlms[c][i].order = (get_bits(&s->gb, 7) + 1) * 8;
+            s->cdlms[c][i].order = (bitstream_read(&s->bc, 7) + 1) * 8;
             if (s->cdlms[c][i].order > MAX_ORDER) {
                 av_log(s->avctx, AV_LOG_ERROR,
                        "Order[%d][%d] %d > max (%d), not supported\n",
@@ -443,7 +456,7 @@ static int decode_cdlms(WmallDecodeCtx *s)
         }
 
         for (i = 0; i < s->cdlms_ttl[c]; i++)
-            s->cdlms[c][i].scaling = get_bits(&s->gb, 4);
+            s->cdlms[c][i].scaling = bitstream_read(&s->bc, 4);
 
         if (cdlms_send_coef) {
             for (i = 0; i < s->cdlms_ttl[c]; i++) {
@@ -451,18 +464,18 @@ static int decode_cdlms(WmallDecodeCtx *s)
                 cbits = av_log2(s->cdlms[c][i].order);
                 if ((1 << cbits) < s->cdlms[c][i].order)
                     cbits++;
-                s->cdlms[c][i].coefsend = get_bits(&s->gb, cbits) + 1;
+                s->cdlms[c][i].coefsend = bitstream_read(&s->bc, cbits) + 1;
 
                 cbits = av_log2(s->cdlms[c][i].scaling + 1);
                 if ((1 << cbits) < s->cdlms[c][i].scaling + 1)
                     cbits++;
 
-                s->cdlms[c][i].bitsend = get_bits(&s->gb, cbits) + 2;
+                s->cdlms[c][i].bitsend = bitstream_read(&s->bc, cbits) + 2;
                 shift_l = 32 - s->cdlms[c][i].bitsend;
                 shift_r = 32 - s->cdlms[c][i].scaling - 2;
                 for (j = 0; j < s->cdlms[c][i].coefsend; j++)
                     s->cdlms[c][i].coefs[j] =
-                        (get_bits(&s->gb, s->cdlms[c][i].bitsend) << shift_l) >> shift_r;
+                        (bitstream_read(&s->bc, s->cdlms[c][i].bitsend) << shift_l) >> shift_r;
             }
         }
     }
@@ -474,9 +487,9 @@ static int decode_channel_residues(WmallDecodeCtx *s, int ch, int tile_size)
 {
     int i = 0;
     unsigned int ave_mean;
-    s->transient[ch] = get_bits1(&s->gb);
+    s->transient[ch] = bitstream_read_bit(&s->bc);
     if (s->transient[ch]) {
-        s->transient_pos[ch] = get_bits(&s->gb, av_log2(tile_size));
+        s->transient_pos[ch] = bitstream_read(&s->bc, av_log2(tile_size));
         if (s->transient_pos[ch])
             s->transient[ch] = 0;
         s->channel[ch].transient_counter =
@@ -485,33 +498,33 @@ static int decode_channel_residues(WmallDecodeCtx *s, int ch, int tile_size)
         s->transient[ch] = 1;
 
     if (s->seekable_tile) {
-        ave_mean = get_bits(&s->gb, s->bits_per_sample);
+        ave_mean = bitstream_read(&s->bc, s->bits_per_sample);
         s->ave_sum[ch] = ave_mean << (s->movave_scaling + 1);
     }
 
     if (s->seekable_tile) {
         if (s->do_inter_ch_decorr)
-            s->channel_residues[ch][0] = get_sbits(&s->gb, s->bits_per_sample + 1);
+            s->channel_residues[ch][0] = bitstream_read_signed(&s->bc, s->bits_per_sample + 1);
         else
-            s->channel_residues[ch][0] = get_sbits(&s->gb, s->bits_per_sample);
+            s->channel_residues[ch][0] = bitstream_read_signed(&s->bc, s->bits_per_sample);
         i++;
     }
     for (; i < tile_size; i++) {
         int quo = 0, rem, rem_bits, residue;
-        while(get_bits1(&s->gb)) {
+        while (bitstream_read_bit(&s->bc)) {
             quo++;
-            if (get_bits_left(&s->gb) <= 0)
+            if (bitstream_bits_left(&s->bc) <= 0)
                 return -1;
         }
         if (quo >= 32)
-            quo += get_bits_long(&s->gb, get_bits(&s->gb, 5) + 1);
+            quo += bitstream_read(&s->bc, bitstream_read(&s->bc, 5) + 1);
 
         ave_mean = (s->ave_sum[ch] + (1 << s->movave_scaling)) >> (s->movave_scaling + 1);
         if (ave_mean <= 1)
             residue = quo;
         else {
             rem_bits = av_ceil_log2(ave_mean);
-            rem      = rem_bits ? get_bits(&s->gb, rem_bits) : 0;
+            rem      = rem_bits ? bitstream_read(&s->bc, rem_bits) : 0;
             residue  = (quo << rem_bits) + rem;
         }
 
@@ -532,13 +545,13 @@ static int decode_channel_residues(WmallDecodeCtx *s, int ch, int tile_size)
 static void decode_lpc(WmallDecodeCtx *s)
 {
     int ch, i, cbits;
-    s->lpc_order   = get_bits(&s->gb, 5) + 1;
-    s->lpc_scaling = get_bits(&s->gb, 4);
-    s->lpc_intbits = get_bits(&s->gb, 3) + 1;
+    s->lpc_order   = bitstream_read(&s->bc, 5) + 1;
+    s->lpc_scaling = bitstream_read(&s->bc, 4);
+    s->lpc_intbits = bitstream_read(&s->bc, 3) + 1;
     cbits = s->lpc_scaling + s->lpc_intbits;
     for (ch = 0; ch < s->num_channels; ch++)
         for (i = 0; i < s->lpc_order; i++)
-            s->lpc_coefs[ch][i] = get_sbits(&s->gb, cbits);
+            s->lpc_coefs[ch][i] = bitstream_read_signed(&s->bc, cbits);
 }
 
 static void clear_codec_buffers(WmallDecodeCtx *s)
@@ -650,9 +663,9 @@ static void mclms_predict(WmallDecodeCtx *s, int icoef, int *pred)
     int num_channels = s->num_channels;
 
     for (ich = 0; ich < num_channels; ich++) {
+        pred[ich] = 0;
         if (!s->is_channel_coded[ich])
             continue;
-        pred[ich] = 0;
         for (i = 0; i < order * num_channels; i++)
             pred[ich] += s->mclms_prevvalues[i + s->mclms_recent] *
                          s->mclms_coeffs[i + order * num_channels * ich];
@@ -785,7 +798,7 @@ static void revert_inter_ch_decorr(WmallDecodeCtx *s, int tile_size)
 {
     if (s->num_channels != 2)
         return;
-    else if (s->is_channel_coded[0] && s->is_channel_coded[1]) {
+    else if (s->is_channel_coded[0] || s->is_channel_coded[1]) {
         int icoef;
         for (icoef = 0; icoef < tile_size; icoef++) {
             s->channel_residues[0][icoef] -= s->channel_residues[1][icoef] >> 1;
@@ -833,7 +846,7 @@ static int decode_subframe(WmallDecodeCtx *s)
     int total_samples = s->samples_per_frame * s->num_channels;
     int i, j, rawpcm_tile, padding_zeroes, res;
 
-    s->subframe_offset = get_bits_count(&s->gb);
+    s->subframe_offset = bitstream_tell(&s->bc);
 
     /* reset channel context and find the next block offset and size
         == the next block of the channel with the smallest number of
@@ -870,18 +883,18 @@ static int decode_subframe(WmallDecodeCtx *s)
         s->parsed_all_subframes = 1;
 
 
-    s->seekable_tile = get_bits1(&s->gb);
+    s->seekable_tile = bitstream_read_bit(&s->bc);
     if (s->seekable_tile) {
         clear_codec_buffers(s);
 
-        s->do_arith_coding    = get_bits1(&s->gb);
+        s->do_arith_coding    = bitstream_read_bit(&s->bc);
         if (s->do_arith_coding) {
-            av_log_missing_feature(s->avctx, "arithmetic coding", 1);
+            avpriv_request_sample(s->avctx, "Arithmetic coding");
             return AVERROR_PATCHWELCOME;
         }
-        s->do_ac_filter       = get_bits1(&s->gb);
-        s->do_inter_ch_decorr = get_bits1(&s->gb);
-        s->do_mclms           = get_bits1(&s->gb);
+        s->do_ac_filter       = bitstream_read_bit(&s->bc);
+        s->do_inter_ch_decorr = bitstream_read_bit(&s->bc);
+        s->do_mclms           = bitstream_read_bit(&s->bc);
 
         if (s->do_ac_filter)
             decode_ac_filter(s);
@@ -891,51 +904,57 @@ static int decode_subframe(WmallDecodeCtx *s)
 
         if ((res = decode_cdlms(s)) < 0)
             return res;
-        s->movave_scaling = get_bits(&s->gb, 3);
-        s->quant_stepsize = get_bits(&s->gb, 8) + 1;
+        s->movave_scaling = bitstream_read(&s->bc, 3);
+        s->quant_stepsize = bitstream_read(&s->bc, 8) + 1;
 
         reset_codec(s);
     } else if (!s->cdlms[0][0].order) {
         av_log(s->avctx, AV_LOG_DEBUG,
                "Waiting for seekable tile\n");
+        av_frame_unref(s->frame);
         return -1;
     }
 
-    rawpcm_tile = get_bits1(&s->gb);
+    rawpcm_tile = bitstream_read_bit(&s->bc);
 
     for (i = 0; i < s->num_channels; i++)
         s->is_channel_coded[i] = 1;
 
     if (!rawpcm_tile) {
         for (i = 0; i < s->num_channels; i++)
-            s->is_channel_coded[i] = get_bits1(&s->gb);
+            s->is_channel_coded[i] = bitstream_read_bit(&s->bc);
 
         if (s->bV3RTM) {
             // LPC
-            s->do_lpc = get_bits1(&s->gb);
+            s->do_lpc = bitstream_read_bit(&s->bc);
             if (s->do_lpc) {
                 decode_lpc(s);
-                av_log_ask_for_sample(s->avctx, "Inverse LPC filter not "
-                                      "implemented. Expect wrong output.\n");
+                avpriv_request_sample(s->avctx, "Expect wrong output since "
+                                      "inverse LPC filter");
             }
         } else
             s->do_lpc = 0;
     }
 
 
-    if (get_bits1(&s->gb))
-        padding_zeroes = get_bits(&s->gb, 5);
+    if (bitstream_read_bit(&s->bc))
+        padding_zeroes = bitstream_read(&s->bc, 5);
     else
         padding_zeroes = 0;
 
     if (rawpcm_tile) {
         int bits = s->bits_per_sample - padding_zeroes;
-        av_dlog(s->avctx, "RAWPCM %d bits per sample. "
+        if (bits <= 0) {
+            av_log(s->avctx, AV_LOG_ERROR,
+                   "Invalid number of padding bits in raw PCM tile\n");
+            return AVERROR_INVALIDDATA;
+        }
+        ff_dlog(s->avctx, "RAWPCM %d bits per sample. "
                 "total %d bits, remain=%d\n", bits,
-                bits * s->num_channels * subframe_len, get_bits_count(&s->gb));
+                bits * s->num_channels * subframe_len, bitstream_tell(&s->bc));
         for (i = 0; i < s->num_channels; i++)
             for (j = 0; j < subframe_len; j++)
-                s->channel_coeffs[i][j] = get_sbits(&s->gb, bits);
+                s->channel_coeffs[i][j] = bitstream_read_signed(&s->bc, bits);
     } else {
         for (i = 0; i < s->num_channels; i++)
             if (s->is_channel_coded[i]) {
@@ -945,6 +964,8 @@ static int decode_subframe(WmallDecodeCtx *s)
                 else
                     use_normal_update_speed(s, i);
                 revert_cdlms(s, i, 0, subframe_len);
+            } else {
+                memset(s->channel_residues[i], 0, sizeof(**s->channel_residues) * subframe_len);
             }
     }
     if (s->do_mclms)
@@ -961,13 +982,18 @@ static int decode_subframe(WmallDecodeCtx *s)
                 s->channel_residues[i][j] *= s->quant_stepsize;
 
     /* Write to proper output buffer depending on bit-depth */
-    for (i = 0; i < subframe_len; i++)
-        for (j = 0; j < s->num_channels; j++) {
-            if (s->bits_per_sample == 16)
-                *s->samples_16++ = (int16_t) s->channel_residues[j][i];
-            else
-                *s->samples_32++ = s->channel_residues[j][i];
+    for (i = 0; i < s->channels_for_cur_subframe; i++) {
+        int c = s->channel_indexes_for_cur_subframe[i];
+        int subframe_len = s->channel[c].subframe_len[s->channel[c].cur_subframe];
+
+        for (j = 0; j < subframe_len; j++) {
+            if (s->bits_per_sample == 16) {
+                *s->samples_16[c]++ = (int16_t) s->channel_residues[c][j] << padding_zeroes;
+            } else {
+                *s->samples_32[c]++ = s->channel_residues[c][j] << padding_zeroes;
+            }
         }
+    }
 
     /* handled one subframe */
     for (i = 0; i < s->channels_for_cur_subframe; i++) {
@@ -989,23 +1015,25 @@ static int decode_subframe(WmallDecodeCtx *s)
  */
 static int decode_frame(WmallDecodeCtx *s)
 {
-    GetBitContext* gb = &s->gb;
+    BitstreamContext *bc = &s->bc;
     int more_frames = 0, len = 0, i, ret;
 
-    s->frame.nb_samples = s->samples_per_frame;
-    if ((ret = s->avctx->get_buffer(s->avctx, &s->frame)) < 0) {
+    s->frame->nb_samples = s->samples_per_frame;
+    if ((ret = ff_get_buffer(s->avctx, s->frame, 0)) < 0) {
         /* return an error if no frame could be decoded at all */
         av_log(s->avctx, AV_LOG_ERROR,
                "not enough space for the output samples\n");
         s->packet_loss = 1;
         return ret;
     }
-    s->samples_16 = (int16_t *)s->frame.data[0];
-    s->samples_32 = (int32_t *)s->frame.data[0];
+    for (i = 0; i < s->num_channels; i++) {
+        s->samples_16[i] = (int16_t *)s->frame->extended_data[i];
+        s->samples_32[i] = (int32_t *)s->frame->extended_data[i];
+    }
 
     /* get frame length */
     if (s->len_prefix)
-        len = get_bits(gb, s->log2_frame_size);
+        len = bitstream_read(bc, s->log2_frame_size);
 
     /* decode tile information */
     if (decode_tilehdr(s)) {
@@ -1015,23 +1043,23 @@ static int decode_frame(WmallDecodeCtx *s)
 
     /* read drc info */
     if (s->dynamic_range_compression)
-        s->drc_gain = get_bits(gb, 8);
+        s->drc_gain = bitstream_read(bc, 8);
 
     /* no idea what these are for, might be the number of samples
        that need to be skipped at the beginning or end of a stream */
-    if (get_bits1(gb)) {
-        int skip;
+    if (bitstream_read_bit(bc)) {
+        int av_unused skip;
 
         /* usually true for the first frame */
-        if (get_bits1(gb)) {
-            skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
-            av_dlog(s->avctx, "start skip: %i\n", skip);
+        if (bitstream_read_bit(bc)) {
+            skip = bitstream_read(bc, av_log2(s->samples_per_frame * 2));
+            ff_dlog(s->avctx, "start skip: %i\n", skip);
         }
 
         /* sometimes true for the last frame */
-        if (get_bits1(gb)) {
-            skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
-            av_dlog(s->avctx, "end skip: %i\n", skip);
+        if (bitstream_read_bit(bc)) {
+            skip = bitstream_read(bc, av_log2(s->samples_per_frame * 2));
+            ff_dlog(s->avctx, "end skip: %i\n", skip);
         }
 
     }
@@ -1051,27 +1079,28 @@ static int decode_frame(WmallDecodeCtx *s)
         }
     }
 
-    av_dlog(s->avctx, "Frame done\n");
+    ff_dlog(s->avctx, "Frame done\n");
 
     if (s->skip_frame)
         s->skip_frame = 0;
 
     if (s->len_prefix) {
-        if (len != (get_bits_count(gb) - s->frame_offset) + 2) {
+        if (len != (bitstream_tell(bc) - s->frame_offset) + 2) {
             /* FIXME: not sure if this is always an error */
             av_log(s->avctx, AV_LOG_ERROR,
-                   "frame[%i] would have to skip %i bits\n", s->frame_num,
-                   len - (get_bits_count(gb) - s->frame_offset) - 1);
+                   "frame[%"PRIu32"] would have to skip %i bits\n",
+                   s->frame_num,
+                   len - (bitstream_tell(bc) - s->frame_offset) - 1);
             s->packet_loss = 1;
             return 0;
         }
 
         /* skip the rest of the frame data */
-        skip_bits_long(gb, len - (get_bits_count(gb) - s->frame_offset) - 1);
+        bitstream_skip(bc, len - (bitstream_tell(bc) - s->frame_offset) - 1);
     }
 
     /* decode trailer bit */
-    more_frames = get_bits1(gb);
+    more_frames = bitstream_read_bit(bc);
     ++s->frame_num;
     return more_frames;
 }
@@ -1079,22 +1108,22 @@ static int decode_frame(WmallDecodeCtx *s)
 /**
  * @brief Calculate remaining input buffer length.
  * @param s  codec context
- * @param gb bitstream reader context
+ * @param bc bitstream reader context
  * @return remaining size in bits
  */
-static int remaining_bits(WmallDecodeCtx *s, GetBitContext *gb)
+static int remaining_bits(WmallDecodeCtx *s, BitstreamContext *bc)
 {
-    return s->buf_bit_size - get_bits_count(gb);
+    return s->buf_bit_size - bitstream_tell(bc);
 }
 
 /**
  * @brief Fill the bit reservoir with a (partial) frame.
  * @param s      codec context
- * @param gb     bitstream reader context
+ * @param bc     bitstream reader context
  * @param len    length of the partial frame
  * @param append decides whether to reset the buffer or not
  */
-static void save_bits(WmallDecodeCtx *s, GetBitContext* gb, int len,
+static void save_bits(WmallDecodeCtx *s, BitstreamContext *bc, int len,
                       int append)
 {
     int buflen;
@@ -1105,7 +1134,7 @@ static void save_bits(WmallDecodeCtx *s, GetBitContext* gb, int len,
         and skipped later so that a fast byte copy is possible */
 
     if (!append) {
-        s->frame_offset   = get_bits_count(gb) & 7;
+        s->frame_offset   = bitstream_tell(bc) & 7;
         s->num_saved_bits = s->frame_offset;
         init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
     }
@@ -1113,48 +1142,41 @@ static void save_bits(WmallDecodeCtx *s, GetBitContext* gb, int len,
     buflen = (s->num_saved_bits + len + 8) >> 3;
 
     if (len <= 0 || buflen > MAX_FRAMESIZE) {
-        av_log_ask_for_sample(s->avctx, "input buffer too small\n");
+        avpriv_request_sample(s->avctx, "Too small input buffer");
         s->packet_loss = 1;
         return;
     }
 
     s->num_saved_bits += len;
     if (!append) {
-        avpriv_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3),
+        avpriv_copy_bits(&s->pb, bc->buffer + (bitstream_tell(bc) >> 3),
                          s->num_saved_bits);
     } else {
-        int align = 8 - (get_bits_count(gb) & 7);
+        int align = 8 - (bitstream_tell(bc) & 7);
         align = FFMIN(align, len);
-        put_bits(&s->pb, align, get_bits(gb, align));
+        put_bits(&s->pb, align, bitstream_read(bc, align));
         len -= align;
-        avpriv_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3), len);
+        avpriv_copy_bits(&s->pb, bc->buffer + (bitstream_tell(bc) >> 3), len);
     }
-    skip_bits_long(gb, len);
+    bitstream_skip(bc, len);
 
     tmp = s->pb;
     flush_put_bits(&tmp);
 
-    init_get_bits(&s->gb, s->frame_data, s->num_saved_bits);
-    skip_bits(&s->gb, s->frame_offset);
+    bitstream_init(&s->bc, s->frame_data, s->num_saved_bits);
+    bitstream_skip(&s->bc, s->frame_offset);
 }
 
-/**
- * @brief Decode a single WMA packet.
- * @param avctx     codec context
- * @param data      the output buffer
- * @param data_size number of bytes that were written to the output buffer
- * @param avpkt     input packet
- * @return number of bytes that were read from the input buffer
- */
 static int decode_packet(AVCodecContext *avctx, void *data, int *got_frame_ptr,
                          AVPacket* avpkt)
 {
     WmallDecodeCtx *s = avctx->priv_data;
-    GetBitContext* gb  = &s->pgb;
+    BitstreamContext *bc = &s->pbc;
     const uint8_t* buf = avpkt->data;
     int buf_size       = avpkt->size;
-    int num_bits_prev_frame, packet_sequence_number,
-        seekable_frame_in_packet, spliced_packet;
+    int num_bits_prev_frame, packet_sequence_number, spliced_packet;
+
+    s->frame->nb_samples = 0;
 
     if (s->packet_done || s->packet_loss) {
         s->packet_done = 0;
@@ -1168,25 +1190,28 @@ static int decode_packet(AVCodecContext *avctx, void *data, int *got_frame_ptr,
         s->buf_bit_size      = buf_size << 3;
 
         /* parse packet header */
-        init_get_bits(gb, buf, s->buf_bit_size);
-        packet_sequence_number   = get_bits(gb, 4);
-        seekable_frame_in_packet = get_bits1(gb);
-        spliced_packet           = get_bits1(gb);
+        bitstream_init(bc, buf, s->buf_bit_size);
+        packet_sequence_number = bitstream_read(bc, 4);
+        bitstream_skip(bc, 1); // Skip seekable_frame_in_packet, currently ununused
+        spliced_packet = bitstream_read_bit(bc);
+        if (spliced_packet)
+            avpriv_request_sample(avctx, "Bitstream splicing");
 
         /* get number of bits that need to be added to the previous frame */
-        num_bits_prev_frame = get_bits(gb, s->log2_frame_size);
+        num_bits_prev_frame = bitstream_read(bc, s->log2_frame_size);
 
         /* check for packet loss */
         if (!s->packet_loss &&
             ((s->packet_sequence_number + 1) & 0xF) != packet_sequence_number) {
             s->packet_loss = 1;
-            av_log(avctx, AV_LOG_ERROR, "Packet loss detected! seq %x vs %x\n",
+            av_log(avctx, AV_LOG_ERROR,
+                   "Packet loss detected! seq %"PRIx8" vs %x\n",
                    s->packet_sequence_number, packet_sequence_number);
         }
         s->packet_sequence_number = packet_sequence_number;
 
         if (num_bits_prev_frame > 0) {
-            int remaining_packet_bits = s->buf_bit_size - get_bits_count(gb);
+            int remaining_packet_bits = s->buf_bit_size - bitstream_tell(bc);
             if (num_bits_prev_frame >= remaining_packet_bits) {
                 num_bits_prev_frame = remaining_packet_bits;
                 s->packet_done = 1;
@@ -1194,13 +1219,13 @@ static int decode_packet(AVCodecContext *avctx, void *data, int *got_frame_ptr,
 
             /* Append the previous frame data to the remaining data from the
              * previous packet to create a full frame. */
-            save_bits(s, gb, num_bits_prev_frame, 1);
+            save_bits(s, bc, num_bits_prev_frame, 1);
 
             /* decode the cross packet frame if it is valid */
-            if (!s->packet_loss)
+            if (num_bits_prev_frame < remaining_packet_bits && !s->packet_loss)
                 decode_frame(s);
         } else if (s->num_saved_bits - s->frame_offset) {
-            av_dlog(avctx, "ignoring %x previously saved bits\n",
+            ff_dlog(avctx, "ignoring %x previously saved bits\n",
                     s->num_saved_bits - s->frame_offset);
         }
 
@@ -1209,22 +1234,23 @@ static int decode_packet(AVCodecContext *avctx, void *data, int *got_frame_ptr,
              * to decode incomplete frames in the s->len_prefix == 0 case. */
             s->num_saved_bits = 0;
             s->packet_loss    = 0;
+            init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
         }
 
     } else {
         int frame_size;
 
         s->buf_bit_size = (avpkt->size - s->next_packet_start) << 3;
-        init_get_bits(gb, avpkt->data, s->buf_bit_size);
-        skip_bits(gb, s->packet_offset);
+        bitstream_init(bc, avpkt->data, s->buf_bit_size);
+        bitstream_skip(bc, s->packet_offset);
 
-        if (s->len_prefix && remaining_bits(s, gb) > s->log2_frame_size &&
-            (frame_size = show_bits(gb, s->log2_frame_size)) &&
-            frame_size <= remaining_bits(s, gb)) {
-            save_bits(s, gb, frame_size, 0);
+        if (s->len_prefix && remaining_bits(s, bc) > s->log2_frame_size &&
+            (frame_size = bitstream_peek(bc, s->log2_frame_size)) &&
+            frame_size <= remaining_bits(s, bc)) {
+            save_bits(s, bc, frame_size, 0);
             s->packet_done = !decode_frame(s);
         } else if (!s->len_prefix
-                   && s->num_saved_bits > get_bits_count(&s->gb)) {
+                   && s->num_saved_bits > bitstream_tell(&s->bc)) {
             /* when the frames do not have a length prefix, we don't know the
              * compressed length of the individual frames however, we know what
              * part of a new packet belongs to the previous frame therefore we
@@ -1238,27 +1264,54 @@ static int decode_packet(AVCodecContext *avctx, void *data, int *got_frame_ptr,
     }
 
     if (s->packet_done && !s->packet_loss &&
-        remaining_bits(s, gb) > 0) {
+        remaining_bits(s, bc) > 0) {
         /* save the rest of the data so that it can be decoded
          * with the next packet */
-        save_bits(s, gb, remaining_bits(s, gb), 0);
+        save_bits(s, bc, remaining_bits(s, bc), 0);
     }
 
-    *(AVFrame *)data = s->frame;
-    *got_frame_ptr   = s->frame.nb_samples > 0;
-    s->packet_offset = get_bits_count(gb) & 7;
+    *got_frame_ptr   = s->frame->nb_samples > 0;
+    av_frame_move_ref(data, s->frame);
 
-    return (s->packet_loss) ? AVERROR_INVALIDDATA : get_bits_count(gb) >> 3;
+    s->packet_offset = bitstream_tell(bc) & 7;
+
+    return (s->packet_loss) ? AVERROR_INVALIDDATA : bitstream_tell(bc) >> 3;
+}
+
+static void flush(AVCodecContext *avctx)
+{
+    WmallDecodeCtx *s    = avctx->priv_data;
+    s->packet_loss       = 1;
+    s->packet_done       = 0;
+    s->num_saved_bits    = 0;
+    s->frame_offset      = 0;
+    s->next_packet_start = 0;
+    s->cdlms[0][0].order = 0;
+    s->frame->nb_samples = 0;
+    init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
 }
 
+static av_cold int decode_close(AVCodecContext *avctx)
+{
+    WmallDecodeCtx *s = avctx->priv_data;
+
+    av_frame_free(&s->frame);
+
+    return 0;
+}
 
 AVCodec ff_wmalossless_decoder = {
     .name           = "wmalossless",
+    .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Audio Lossless"),
     .type           = AVMEDIA_TYPE_AUDIO,
-    .id             = CODEC_ID_WMALOSSLESS,
+    .id             = AV_CODEC_ID_WMALOSSLESS,
     .priv_data_size = sizeof(WmallDecodeCtx),
     .init           = decode_init,
+    .close          = decode_close,
     .decode         = decode_packet,
-    .capabilities   = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1 | CODEC_CAP_DELAY,
-    .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Audio Lossless"),
+    .flush          = flush,
+    .capabilities   = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY,
+    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
+                                                      AV_SAMPLE_FMT_S32P,
+                                                      AV_SAMPLE_FMT_NONE },
 };