LCOV - code coverage report
Current view: top level - libavcodec - wmaprodec.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 591 843 70.1 %
Date: 2017-12-13 10:57:33 Functions: 19 26 73.1 %

          Line data    Source code
       1             : /*
       2             :  * Wmapro compatible decoder
       3             :  * Copyright (c) 2007 Baptiste Coudurier, Benjamin Larsson, Ulion
       4             :  * Copyright (c) 2008 - 2011 Sascha Sommer, Benjamin Larsson
       5             :  *
       6             :  * This file is part of FFmpeg.
       7             :  *
       8             :  * FFmpeg is free software; you can redistribute it and/or
       9             :  * modify it under the terms of the GNU Lesser General Public
      10             :  * License as published by the Free Software Foundation; either
      11             :  * version 2.1 of the License, or (at your option) any later version.
      12             :  *
      13             :  * FFmpeg is distributed in the hope that it will be useful,
      14             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      15             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      16             :  * Lesser General Public License for more details.
      17             :  *
      18             :  * You should have received a copy of the GNU Lesser General Public
      19             :  * License along with FFmpeg; if not, write to the Free Software
      20             :  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
      21             :  */
      22             : 
      23             : /**
      24             :  * @file
      25             :  * @brief wmapro decoder implementation
      26             :  * Wmapro is an MDCT based codec comparable to wma standard or AAC.
      27             :  * The decoding therefore consists of the following steps:
      28             :  * - bitstream decoding
      29             :  * - reconstruction of per-channel data
      30             :  * - rescaling and inverse quantization
      31             :  * - IMDCT
      32             :  * - windowing and overlapp-add
      33             :  *
      34             :  * The compressed wmapro bitstream is split into individual packets.
      35             :  * Every such packet contains one or more wma frames.
      36             :  * The compressed frames may have a variable length and frames may
      37             :  * cross packet boundaries.
      38             :  * Common to all wmapro frames is the number of samples that are stored in
      39             :  * a frame.
      40             :  * The number of samples and a few other decode flags are stored
      41             :  * as extradata that has to be passed to the decoder.
      42             :  *
      43             :  * The wmapro frames themselves are again split into a variable number of
      44             :  * subframes. Every subframe contains the data for 2^N time domain samples
      45             :  * where N varies between 7 and 12.
      46             :  *
      47             :  * Example wmapro bitstream (in samples):
      48             :  *
      49             :  * ||   packet 0           || packet 1 || packet 2      packets
      50             :  * ---------------------------------------------------
      51             :  * || frame 0      || frame 1       || frame 2    ||    frames
      52             :  * ---------------------------------------------------
      53             :  * ||   |      |   ||   |   |   |   ||            ||    subframes of channel 0
      54             :  * ---------------------------------------------------
      55             :  * ||      |   |   ||   |   |   |   ||            ||    subframes of channel 1
      56             :  * ---------------------------------------------------
      57             :  *
      58             :  * The frame layouts for the individual channels of a wma frame does not need
      59             :  * to be the same.
      60             :  *
      61             :  * However, if the offsets and lengths of several subframes of a frame are the
      62             :  * same, the subframes of the channels can be grouped.
      63             :  * Every group may then use special coding techniques like M/S stereo coding
      64             :  * to improve the compression ratio. These channel transformations do not
      65             :  * need to be applied to a whole subframe. Instead, they can also work on
      66             :  * individual scale factor bands (see below).
      67             :  * The coefficients that carry the audio signal in the frequency domain
      68             :  * are transmitted as huffman-coded vectors with 4, 2 and 1 elements.
      69             :  * In addition to that, the encoder can switch to a runlevel coding scheme
      70             :  * by transmitting subframe_length / 128 zero coefficients.
      71             :  *
      72             :  * Before the audio signal can be converted to the time domain, the
      73             :  * coefficients have to be rescaled and inverse quantized.
      74             :  * A subframe is therefore split into several scale factor bands that get
      75             :  * scaled individually.
      76             :  * Scale factors are submitted for every frame but they might be shared
      77             :  * between the subframes of a channel. Scale factors are initially DPCM-coded.
      78             :  * Once scale factors are shared, the differences are transmitted as runlevel
      79             :  * codes.
      80             :  * Every subframe length and offset combination in the frame layout shares a
      81             :  * common quantization factor that can be adjusted for every channel by a
      82             :  * modifier.
      83             :  * After the inverse quantization, the coefficients get processed by an IMDCT.
      84             :  * The resulting values are then windowed with a sine window and the first half
      85             :  * of the values are added to the second half of the output from the previous
      86             :  * subframe in order to reconstruct the output samples.
      87             :  */
      88             : 
      89             : #include <inttypes.h>
      90             : 
      91             : #include "libavutil/ffmath.h"
      92             : #include "libavutil/float_dsp.h"
      93             : #include "libavutil/intfloat.h"
      94             : #include "libavutil/intreadwrite.h"
      95             : #include "avcodec.h"
      96             : #include "internal.h"
      97             : #include "get_bits.h"
      98             : #include "put_bits.h"
      99             : #include "wmaprodata.h"
     100             : #include "sinewin.h"
     101             : #include "wma.h"
     102             : #include "wma_common.h"
     103             : 
     104             : /** current decoder limitations */
     105             : #define WMAPRO_MAX_CHANNELS    8                             ///< max number of handled channels
     106             : #define MAX_SUBFRAMES  32                                    ///< max number of subframes per channel
     107             : #define MAX_BANDS      29                                    ///< max number of scale factor bands
     108             : #define MAX_FRAMESIZE  32768                                 ///< maximum compressed frame size
     109             : #define XMA_MAX_STREAMS         8
     110             : #define XMA_MAX_CHANNELS        8
     111             : #define XMA_MAX_CHANNELS_STREAM 2
     112             : 
     113             : #define WMAPRO_BLOCK_MIN_BITS  6                                           ///< log2 of min block size
     114             : #define WMAPRO_BLOCK_MAX_BITS 13                                           ///< log2 of max block size
     115             : #define WMAPRO_BLOCK_MIN_SIZE (1 << WMAPRO_BLOCK_MIN_BITS)                 ///< minimum block size
     116             : #define WMAPRO_BLOCK_MAX_SIZE (1 << WMAPRO_BLOCK_MAX_BITS)                 ///< maximum block size
     117             : #define WMAPRO_BLOCK_SIZES    (WMAPRO_BLOCK_MAX_BITS - WMAPRO_BLOCK_MIN_BITS + 1) ///< possible block sizes
     118             : 
     119             : 
     120             : #define VLCBITS            9
     121             : #define SCALEVLCBITS       8
     122             : #define VEC4MAXDEPTH    ((HUFF_VEC4_MAXBITS+VLCBITS-1)/VLCBITS)
     123             : #define VEC2MAXDEPTH    ((HUFF_VEC2_MAXBITS+VLCBITS-1)/VLCBITS)
     124             : #define VEC1MAXDEPTH    ((HUFF_VEC1_MAXBITS+VLCBITS-1)/VLCBITS)
     125             : #define SCALEMAXDEPTH   ((HUFF_SCALE_MAXBITS+SCALEVLCBITS-1)/SCALEVLCBITS)
     126             : #define SCALERLMAXDEPTH ((HUFF_SCALE_RL_MAXBITS+VLCBITS-1)/VLCBITS)
     127             : 
     128             : static VLC              sf_vlc;           ///< scale factor DPCM vlc
     129             : static VLC              sf_rl_vlc;        ///< scale factor run length vlc
     130             : static VLC              vec4_vlc;         ///< 4 coefficients per symbol
     131             : static VLC              vec2_vlc;         ///< 2 coefficients per symbol
     132             : static VLC              vec1_vlc;         ///< 1 coefficient per symbol
     133             : static VLC              coef_vlc[2];      ///< coefficient run length vlc codes
     134             : static float            sin64[33];        ///< sine table for decorrelation
     135             : 
     136             : /**
     137             :  * @brief frame specific decoder context for a single channel
     138             :  */
     139             : typedef struct WMAProChannelCtx {
     140             :     int16_t  prev_block_len;                          ///< length of the previous block
     141             :     uint8_t  transmit_coefs;
     142             :     uint8_t  num_subframes;
     143             :     uint16_t subframe_len[MAX_SUBFRAMES];             ///< subframe length in samples
     144             :     uint16_t subframe_offset[MAX_SUBFRAMES];          ///< subframe positions in the current frame
     145             :     uint8_t  cur_subframe;                            ///< current subframe number
     146             :     uint16_t decoded_samples;                         ///< number of already processed samples
     147             :     uint8_t  grouped;                                 ///< channel is part of a group
     148             :     int      quant_step;                              ///< quantization step for the current subframe
     149             :     int8_t   reuse_sf;                                ///< share scale factors between subframes
     150             :     int8_t   scale_factor_step;                       ///< scaling step for the current subframe
     151             :     int      max_scale_factor;                        ///< maximum scale factor for the current subframe
     152             :     int      saved_scale_factors[2][MAX_BANDS];       ///< resampled and (previously) transmitted scale factor values
     153             :     int8_t   scale_factor_idx;                        ///< index for the transmitted scale factor values (used for resampling)
     154             :     int*     scale_factors;                           ///< pointer to the scale factor values used for decoding
     155             :     uint8_t  table_idx;                               ///< index in sf_offsets for the scale factor reference block
     156             :     float*   coeffs;                                  ///< pointer to the subframe decode buffer
     157             :     uint16_t num_vec_coeffs;                          ///< number of vector coded coefficients
     158             :     DECLARE_ALIGNED(32, float, out)[WMAPRO_BLOCK_MAX_SIZE + WMAPRO_BLOCK_MAX_SIZE / 2]; ///< output buffer
     159             : } WMAProChannelCtx;
     160             : 
     161             : /**
     162             :  * @brief channel group for channel transformations
     163             :  */
     164             : typedef struct WMAProChannelGrp {
     165             :     uint8_t num_channels;                                     ///< number of channels in the group
     166             :     int8_t  transform;                                        ///< transform on / off
     167             :     int8_t  transform_band[MAX_BANDS];                        ///< controls if the transform is enabled for a certain band
     168             :     float   decorrelation_matrix[WMAPRO_MAX_CHANNELS*WMAPRO_MAX_CHANNELS];
     169             :     float*  channel_data[WMAPRO_MAX_CHANNELS];                ///< transformation coefficients
     170             : } WMAProChannelGrp;
     171             : 
     172             : /**
     173             :  * @brief main decoder context
     174             :  */
     175             : typedef struct WMAProDecodeCtx {
     176             :     /* generic decoder variables */
     177             :     AVCodecContext*  avctx;                         ///< codec context for av_log
     178             :     AVFloatDSPContext *fdsp;
     179             :     uint8_t          frame_data[MAX_FRAMESIZE +
     180             :                       AV_INPUT_BUFFER_PADDING_SIZE];///< compressed frame data
     181             :     PutBitContext    pb;                            ///< context for filling the frame_data buffer
     182             :     FFTContext       mdct_ctx[WMAPRO_BLOCK_SIZES];  ///< MDCT context per block size
     183             :     DECLARE_ALIGNED(32, float, tmp)[WMAPRO_BLOCK_MAX_SIZE]; ///< IMDCT output buffer
     184             :     const float*     windows[WMAPRO_BLOCK_SIZES];   ///< windows for the different block sizes
     185             : 
     186             :     /* frame size dependent frame information (set during initialization) */
     187             :     uint32_t         decode_flags;                  ///< used compression features
     188             :     uint8_t          len_prefix;                    ///< frame is prefixed with its length
     189             :     uint8_t          dynamic_range_compression;     ///< frame contains DRC data
     190             :     uint8_t          bits_per_sample;               ///< integer audio sample size for the unscaled IMDCT output (used to scale to [-1.0, 1.0])
     191             :     uint16_t         samples_per_frame;             ///< number of samples to output
     192             :     uint16_t         log2_frame_size;
     193             :     int8_t           lfe_channel;                   ///< lfe channel index
     194             :     uint8_t          max_num_subframes;
     195             :     uint8_t          subframe_len_bits;             ///< number of bits used for the subframe length
     196             :     uint8_t          max_subframe_len_bit;          ///< flag indicating that the subframe is of maximum size when the first subframe length bit is 1
     197             :     uint16_t         min_samples_per_subframe;
     198             :     int8_t           num_sfb[WMAPRO_BLOCK_SIZES];   ///< scale factor bands per block size
     199             :     int16_t          sfb_offsets[WMAPRO_BLOCK_SIZES][MAX_BANDS];                    ///< scale factor band offsets (multiples of 4)
     200             :     int8_t           sf_offsets[WMAPRO_BLOCK_SIZES][WMAPRO_BLOCK_SIZES][MAX_BANDS]; ///< scale factor resample matrix
     201             :     int16_t          subwoofer_cutoffs[WMAPRO_BLOCK_SIZES]; ///< subwoofer cutoff values
     202             : 
     203             :     /* packet decode state */
     204             :     GetBitContext    pgb;                           ///< bitstream reader context for the packet
     205             :     int              next_packet_start;             ///< start offset of the next wma packet in the demuxer packet
     206             :     uint8_t          packet_offset;                 ///< frame offset in the packet
     207             :     uint8_t          packet_sequence_number;        ///< current packet number
     208             :     int              num_saved_bits;                ///< saved number of bits
     209             :     int              frame_offset;                  ///< frame offset in the bit reservoir
     210             :     int              subframe_offset;               ///< subframe offset in the bit reservoir
     211             :     uint8_t          packet_loss;                   ///< set in case of bitstream error
     212             :     uint8_t          packet_done;                   ///< set when a packet is fully decoded
     213             : 
     214             :     /* frame decode state */
     215             :     uint32_t         frame_num;                     ///< current frame number (not used for decoding)
     216             :     GetBitContext    gb;                            ///< bitstream reader context
     217             :     int              buf_bit_size;                  ///< buffer size in bits
     218             :     uint8_t          drc_gain;                      ///< gain for the DRC tool
     219             :     int8_t           skip_frame;                    ///< skip output step
     220             :     int8_t           parsed_all_subframes;          ///< all subframes decoded?
     221             :     uint8_t          skip_packets;                  ///< packets to skip to find next packet in a stream (XMA1/2)
     222             : 
     223             :     /* subframe/block decode state */
     224             :     int16_t          subframe_len;                  ///< current subframe length
     225             :     int8_t           nb_channels;                   ///< number of channels in stream (XMA1/2)
     226             :     int8_t           channels_for_cur_subframe;     ///< number of channels that contain the subframe
     227             :     int8_t           channel_indexes_for_cur_subframe[WMAPRO_MAX_CHANNELS];
     228             :     int8_t           num_bands;                     ///< number of scale factor bands
     229             :     int8_t           transmit_num_vec_coeffs;       ///< number of vector coded coefficients is part of the bitstream
     230             :     int16_t*         cur_sfb_offsets;               ///< sfb offsets for the current block
     231             :     uint8_t          table_idx;                     ///< index for the num_sfb, sfb_offsets, sf_offsets and subwoofer_cutoffs tables
     232             :     int8_t           esc_len;                       ///< length of escaped coefficients
     233             : 
     234             :     uint8_t          num_chgroups;                  ///< number of channel groups
     235             :     WMAProChannelGrp chgroup[WMAPRO_MAX_CHANNELS];  ///< channel group information
     236             : 
     237             :     WMAProChannelCtx channel[WMAPRO_MAX_CHANNELS];  ///< per channel data
     238             : } WMAProDecodeCtx;
     239             : 
     240             : typedef struct XMADecodeCtx {
     241             :     WMAProDecodeCtx xma[XMA_MAX_STREAMS];
     242             :     AVFrame *frames[XMA_MAX_STREAMS];
     243             :     int current_stream;
     244             :     int num_streams;
     245             :     float samples[XMA_MAX_CHANNELS][512 * 64];
     246             :     int offset[XMA_MAX_STREAMS];
     247             :     int start_channel[XMA_MAX_STREAMS];
     248             : } XMADecodeCtx;
     249             : 
     250             : /**
     251             :  *@brief helper function to print the most important members of the context
     252             :  *@param s context
     253             :  */
     254           0 : static av_cold void dump_context(WMAProDecodeCtx *s)
     255             : {
     256             : #define PRINT(a, b)     av_log(s->avctx, AV_LOG_DEBUG, " %s = %d\n", a, b);
     257             : #define PRINT_HEX(a, b) av_log(s->avctx, AV_LOG_DEBUG, " %s = %"PRIx32"\n", a, b);
     258             : 
     259           0 :     PRINT("ed sample bit depth", s->bits_per_sample);
     260           0 :     PRINT_HEX("ed decode flags", s->decode_flags);
     261           0 :     PRINT("samples per frame",   s->samples_per_frame);
     262           0 :     PRINT("log2 frame size",     s->log2_frame_size);
     263           0 :     PRINT("max num subframes",   s->max_num_subframes);
     264           0 :     PRINT("len prefix",          s->len_prefix);
     265           0 :     PRINT("num channels",        s->nb_channels);
     266           0 : }
     267             : 
     268             : /**
     269             :  *@brief Uninitialize the decoder and free all resources.
     270             :  *@param avctx codec context
     271             :  *@return 0 on success, < 0 otherwise
     272             :  */
     273           8 : static av_cold int decode_end(WMAProDecodeCtx *s)
     274             : {
     275             :     int i;
     276             : 
     277           8 :     av_freep(&s->fdsp);
     278             : 
     279          72 :     for (i = 0; i < WMAPRO_BLOCK_SIZES; i++)
     280          64 :         ff_mdct_end(&s->mdct_ctx[i]);
     281             : 
     282           8 :     return 0;
     283             : }
     284             : 
     285           8 : static av_cold int wmapro_decode_end(AVCodecContext *avctx)
     286             : {
     287           8 :     WMAProDecodeCtx *s = avctx->priv_data;
     288             : 
     289           8 :     decode_end(s);
     290             : 
     291           8 :     return 0;
     292             : }
     293             : 
     294          40 : static av_cold int get_rate(AVCodecContext *avctx)
     295             : {
     296          40 :     if (avctx->codec_id != AV_CODEC_ID_WMAPRO) { // XXX: is this really only for XMA?
     297           0 :         if (avctx->sample_rate > 44100)
     298           0 :             return 48000;
     299           0 :         else if (avctx->sample_rate > 32000)
     300           0 :             return 44100;
     301           0 :         else if (avctx->sample_rate > 24000)
     302           0 :             return 32000;
     303           0 :         return 24000;
     304             :     }
     305             : 
     306          40 :     return avctx->sample_rate;
     307             : }
     308             : 
     309             : /**
     310             :  *@brief Initialize the decoder.
     311             :  *@param avctx codec context
     312             :  *@return 0 on success, -1 otherwise
     313             :  */
     314           8 : static av_cold int decode_init(WMAProDecodeCtx *s, AVCodecContext *avctx, int num_stream)
     315             : {
     316           8 :     uint8_t *edata_ptr = avctx->extradata;
     317             :     unsigned int channel_mask;
     318             :     int i, bits;
     319             :     int log2_max_num_subframes;
     320             :     int num_possible_block_sizes;
     321             : 
     322           8 :     if (avctx->codec_id == AV_CODEC_ID_XMA1 || avctx->codec_id == AV_CODEC_ID_XMA2)
     323           0 :         avctx->block_align = 2048;
     324             : 
     325           8 :     if (!avctx->block_align) {
     326           0 :         av_log(avctx, AV_LOG_ERROR, "block_align is not set\n");
     327           0 :         return AVERROR(EINVAL);
     328             :     }
     329             : 
     330           8 :     s->avctx = avctx;
     331             : 
     332           8 :     init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
     333             : 
     334           8 :     avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
     335             : 
     336             :     /** dump the extradata */
     337           8 :     av_log(avctx, AV_LOG_DEBUG, "extradata:\n");
     338         152 :     for (i = 0; i < avctx->extradata_size; i++)
     339         144 :         av_log(avctx, AV_LOG_DEBUG, "[%x] ", avctx->extradata[i]);
     340           8 :     av_log(avctx, AV_LOG_DEBUG, "\n");
     341             : 
     342           8 :     if (avctx->codec_id == AV_CODEC_ID_XMA2 && avctx->extradata_size == 34) { /* XMA2WAVEFORMATEX */
     343           0 :         s->decode_flags    = 0x10d6;
     344           0 :         s->bits_per_sample = 16;
     345           0 :         channel_mask       = 0; //AV_RL32(edata_ptr+2); /* not always in expected order */
     346           0 :         if ((num_stream+1) * XMA_MAX_CHANNELS_STREAM > avctx->channels) /* stream config is 2ch + 2ch + ... + 1/2ch */
     347           0 :             s->nb_channels = 1;
     348             :         else
     349           0 :             s->nb_channels = 2;
     350           8 :     } else if (avctx->codec_id == AV_CODEC_ID_XMA2) { /* XMA2WAVEFORMAT */
     351           0 :         s->decode_flags    = 0x10d6;
     352           0 :         s->bits_per_sample = 16;
     353           0 :         channel_mask       = 0; /* would need to aggregate from all streams */
     354           0 :         s->nb_channels = edata_ptr[32 + ((edata_ptr[0]==3)?0:8) + 4*num_stream + 0]; /* nth stream config */
     355           8 :     } else if (avctx->codec_id == AV_CODEC_ID_XMA1) { /* XMAWAVEFORMAT */
     356           0 :         s->decode_flags    = 0x10d6;
     357           0 :         s->bits_per_sample = 16;
     358           0 :         channel_mask       = 0; /* would need to aggregate from all streams */
     359           0 :         s->nb_channels     = edata_ptr[8 + 20*num_stream + 17]; /* nth stream config */
     360           8 :     } else if (avctx->codec_id == AV_CODEC_ID_WMAPRO && avctx->extradata_size >= 18) {
     361           8 :         s->decode_flags    = AV_RL16(edata_ptr+14);
     362           8 :         channel_mask       = AV_RL32(edata_ptr+2);
     363           8 :         s->bits_per_sample = AV_RL16(edata_ptr);
     364           8 :         s->nb_channels     = avctx->channels;
     365             : 
     366          16 :         if (s->bits_per_sample > 32 || s->bits_per_sample < 1) {
     367           0 :             avpriv_request_sample(avctx, "bits per sample is %d", s->bits_per_sample);
     368           0 :             return AVERROR_PATCHWELCOME;
     369             :         }
     370             :     } else {
     371           0 :         avpriv_request_sample(avctx, "Unknown extradata size");
     372           0 :         return AVERROR_PATCHWELCOME;
     373             :     }
     374             : 
     375             :     /** generic init */
     376           8 :     s->log2_frame_size = av_log2(avctx->block_align) + 4;
     377           8 :     if (s->log2_frame_size > 25) {
     378           0 :         avpriv_request_sample(avctx, "Large block align");
     379           0 :         return AVERROR_PATCHWELCOME;
     380             :     }
     381             : 
     382             :     /** frame info */
     383           8 :     if (avctx->codec_id != AV_CODEC_ID_WMAPRO)
     384           0 :         s->skip_frame = 0;
     385             :     else
     386           8 :         s->skip_frame = 1; /* skip first frame */
     387             : 
     388           8 :     s->packet_loss = 1;
     389           8 :     s->len_prefix  = (s->decode_flags & 0x40);
     390             : 
     391             :     /** get frame len */
     392           8 :     if (avctx->codec_id == AV_CODEC_ID_WMAPRO) {
     393           8 :         bits = ff_wma_get_frame_len_bits(avctx->sample_rate, 3, s->decode_flags);
     394           8 :         if (bits > WMAPRO_BLOCK_MAX_BITS) {
     395           0 :             avpriv_request_sample(avctx, "14-bit block sizes");
     396           0 :             return AVERROR_PATCHWELCOME;
     397             :         }
     398           8 :         s->samples_per_frame = 1 << bits;
     399             :     } else {
     400           0 :         s->samples_per_frame = 512;
     401             :     }
     402             : 
     403             :     /** subframe info */
     404           8 :     log2_max_num_subframes       = ((s->decode_flags & 0x38) >> 3);
     405           8 :     s->max_num_subframes         = 1 << log2_max_num_subframes;
     406           8 :     if (s->max_num_subframes == 16 || s->max_num_subframes == 4)
     407           8 :         s->max_subframe_len_bit = 1;
     408           8 :     s->subframe_len_bits = av_log2(log2_max_num_subframes) + 1;
     409             : 
     410           8 :     num_possible_block_sizes     = log2_max_num_subframes + 1;
     411           8 :     s->min_samples_per_subframe  = s->samples_per_frame / s->max_num_subframes;
     412           8 :     s->dynamic_range_compression = (s->decode_flags & 0x80);
     413             : 
     414           8 :     if (s->max_num_subframes > MAX_SUBFRAMES) {
     415           0 :         av_log(avctx, AV_LOG_ERROR, "invalid number of subframes %"PRId8"\n",
     416           0 :                s->max_num_subframes);
     417           0 :         return AVERROR_INVALIDDATA;
     418             :     }
     419             : 
     420           8 :     if (s->min_samples_per_subframe < WMAPRO_BLOCK_MIN_SIZE) {
     421           0 :         av_log(avctx, AV_LOG_ERROR, "min_samples_per_subframe of %d too small\n",
     422           0 :                s->min_samples_per_subframe);
     423           0 :         return AVERROR_INVALIDDATA;
     424             :     }
     425             : 
     426           8 :     if (s->avctx->sample_rate <= 0) {
     427           0 :         av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
     428           0 :         return AVERROR_INVALIDDATA;
     429             :     }
     430             : 
     431           8 :     if (s->nb_channels <= 0) {
     432           0 :         av_log(avctx, AV_LOG_ERROR, "invalid number of channels %d\n",
     433           0 :                s->nb_channels);
     434           0 :         return AVERROR_INVALIDDATA;
     435           8 :     } else if (avctx->codec_id != AV_CODEC_ID_WMAPRO && s->nb_channels > XMA_MAX_CHANNELS_STREAM) {
     436           0 :         av_log(avctx, AV_LOG_ERROR, "invalid number of channels per XMA stream %d\n",
     437           0 :                s->nb_channels);
     438           0 :         return AVERROR_INVALIDDATA;
     439           8 :     } else if (s->nb_channels > WMAPRO_MAX_CHANNELS) {
     440           0 :         avpriv_request_sample(avctx,
     441             :                               "More than %d channels", WMAPRO_MAX_CHANNELS);
     442           0 :         return AVERROR_PATCHWELCOME;
     443             :     }
     444             : 
     445             :     /** init previous block len */
     446          32 :     for (i = 0; i < s->nb_channels; i++)
     447          24 :         s->channel[i].prev_block_len = s->samples_per_frame;
     448             : 
     449             :     /** extract lfe channel position */
     450           8 :     s->lfe_channel = -1;
     451             : 
     452           8 :     if (channel_mask & 8) {
     453             :         unsigned int mask;
     454          10 :         for (mask = 1; mask < 16; mask <<= 1) {
     455           8 :             if (channel_mask & mask)
     456           8 :                 ++s->lfe_channel;
     457             :         }
     458             :     }
     459             : 
     460           8 :     INIT_VLC_STATIC(&sf_vlc, SCALEVLCBITS, HUFF_SCALE_SIZE,
     461             :                     scale_huffbits, 1, 1,
     462             :                     scale_huffcodes, 2, 2, 616);
     463             : 
     464           8 :     INIT_VLC_STATIC(&sf_rl_vlc, VLCBITS, HUFF_SCALE_RL_SIZE,
     465             :                     scale_rl_huffbits, 1, 1,
     466             :                     scale_rl_huffcodes, 4, 4, 1406);
     467             : 
     468           8 :     INIT_VLC_STATIC(&coef_vlc[0], VLCBITS, HUFF_COEF0_SIZE,
     469             :                     coef0_huffbits, 1, 1,
     470             :                     coef0_huffcodes, 4, 4, 2108);
     471             : 
     472           8 :     INIT_VLC_STATIC(&coef_vlc[1], VLCBITS, HUFF_COEF1_SIZE,
     473             :                     coef1_huffbits, 1, 1,
     474             :                     coef1_huffcodes, 4, 4, 3912);
     475             : 
     476           8 :     INIT_VLC_STATIC(&vec4_vlc, VLCBITS, HUFF_VEC4_SIZE,
     477             :                     vec4_huffbits, 1, 1,
     478             :                     vec4_huffcodes, 2, 2, 604);
     479             : 
     480           8 :     INIT_VLC_STATIC(&vec2_vlc, VLCBITS, HUFF_VEC2_SIZE,
     481             :                     vec2_huffbits, 1, 1,
     482             :                     vec2_huffcodes, 2, 2, 562);
     483             : 
     484           8 :     INIT_VLC_STATIC(&vec1_vlc, VLCBITS, HUFF_VEC1_SIZE,
     485             :                     vec1_huffbits, 1, 1,
     486             :                     vec1_huffcodes, 2, 2, 562);
     487             : 
     488             :     /** calculate number of scale factor bands and their offsets
     489             :         for every possible block size */
     490          48 :     for (i = 0; i < num_possible_block_sizes; i++) {
     491          40 :         int subframe_len = s->samples_per_frame >> i;
     492             :         int x;
     493          40 :         int band = 1;
     494          40 :         int rate = get_rate(avctx);
     495             : 
     496          40 :         s->sfb_offsets[i][0] = 0;
     497             : 
     498        1040 :         for (x = 0; x < MAX_BANDS-1 && s->sfb_offsets[i][band - 1] < subframe_len; x++) {
     499        1040 :             int offset = (subframe_len * 2 * critical_freq[x]) / rate + 2;
     500        1040 :             offset &= ~3;
     501        1040 :             if (offset > s->sfb_offsets[i][band - 1])
     502         860 :                 s->sfb_offsets[i][band++] = offset;
     503             : 
     504        1040 :             if (offset >= subframe_len)
     505          40 :                 break;
     506             :         }
     507          40 :         s->sfb_offsets[i][band - 1] = subframe_len;
     508          40 :         s->num_sfb[i]               = band - 1;
     509          40 :         if (s->num_sfb[i] <= 0) {
     510           0 :             av_log(avctx, AV_LOG_ERROR, "num_sfb invalid\n");
     511           0 :             return AVERROR_INVALIDDATA;
     512             :         }
     513             :     }
     514             : 
     515             : 
     516             :     /** Scale factors can be shared between blocks of different size
     517             :         as every block has a different scale factor band layout.
     518             :         The matrix sf_offsets is needed to find the correct scale factor.
     519             :      */
     520             : 
     521          48 :     for (i = 0; i < num_possible_block_sizes; i++) {
     522             :         int b;
     523         900 :         for (b = 0; b < s->num_sfb[i]; b++) {
     524             :             int x;
     525        1720 :             int offset = ((s->sfb_offsets[i][b]
     526         860 :                            + s->sfb_offsets[i][b + 1] - 1) << i) >> 1;
     527        5160 :             for (x = 0; x < num_possible_block_sizes; x++) {
     528        4300 :                 int v = 0;
     529       52476 :                 while (s->sfb_offsets[x][v + 1] << x < offset) {
     530       43876 :                     v++;
     531       43876 :                     av_assert0(v < MAX_BANDS);
     532             :                 }
     533        4300 :                 s->sf_offsets[i][x][b] = v;
     534             :             }
     535             :         }
     536             :     }
     537             : 
     538           8 :     s->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
     539           8 :     if (!s->fdsp)
     540           0 :         return AVERROR(ENOMEM);
     541             : 
     542             :     /** init MDCT, FIXME: only init needed sizes */
     543          72 :     for (i = 0; i < WMAPRO_BLOCK_SIZES; i++)
     544          64 :         ff_mdct_init(&s->mdct_ctx[i], WMAPRO_BLOCK_MIN_BITS+1+i, 1,
     545          64 :                      1.0 / (1 << (WMAPRO_BLOCK_MIN_BITS + i - 1))
     546          64 :                      / (1 << (s->bits_per_sample - 1)));
     547             : 
     548             :     /** init MDCT windows: simple sine window */
     549          72 :     for (i = 0; i < WMAPRO_BLOCK_SIZES; i++) {
     550          64 :         const int win_idx = WMAPRO_BLOCK_MAX_BITS - i;
     551          64 :         ff_init_ff_sine_windows(win_idx);
     552          64 :         s->windows[WMAPRO_BLOCK_SIZES - i - 1] = ff_sine_windows[win_idx];
     553             :     }
     554             : 
     555             :     /** calculate subwoofer cutoff values */
     556          48 :     for (i = 0; i < num_possible_block_sizes; i++) {
     557          40 :         int block_size = s->samples_per_frame >> i;
     558          80 :         int cutoff = (440*block_size + 3LL * (s->avctx->sample_rate >> 1) - 1)
     559          40 :                      / s->avctx->sample_rate;
     560          40 :         s->subwoofer_cutoffs[i] = av_clip(cutoff, 4, block_size);
     561             :     }
     562             : 
     563             :     /** calculate sine values for the decorrelation matrix */
     564         272 :     for (i = 0; i < 33; i++)
     565         264 :         sin64[i] = sin(i*M_PI / 64.0);
     566             : 
     567           8 :     if (avctx->debug & FF_DEBUG_BITSTREAM)
     568           0 :         dump_context(s);
     569             : 
     570           8 :     avctx->channel_layout = channel_mask;
     571             : 
     572           8 :     return 0;
     573             : }
     574             : 
     575             : /**
     576             :  *@brief Initialize the decoder.
     577             :  *@param avctx codec context
     578             :  *@return 0 on success, -1 otherwise
     579             :  */
     580           8 : static av_cold int wmapro_decode_init(AVCodecContext *avctx)
     581             : {
     582           8 :     WMAProDecodeCtx *s = avctx->priv_data;
     583             : 
     584           8 :     return decode_init(s, avctx, 0);
     585             : }
     586             : 
     587             : /**
     588             :  *@brief Decode the subframe length.
     589             :  *@param s context
     590             :  *@param offset sample offset in the frame
     591             :  *@return decoded subframe length on success, < 0 in case of an error
     592             :  */
     593         527 : static int decode_subframe_length(WMAProDecodeCtx *s, int offset)
     594             : {
     595         527 :     int frame_len_shift = 0;
     596             :     int subframe_len;
     597             : 
     598             :     /** no need to read from the bitstream when only one length is possible */
     599         527 :     if (offset == s->samples_per_frame - s->min_samples_per_subframe)
     600           9 :         return s->min_samples_per_subframe;
     601             : 
     602         518 :     if (get_bits_left(&s->gb) < 1)
     603           0 :         return AVERROR_INVALIDDATA;
     604             : 
     605             :     /** 1 bit indicates if the subframe is of maximum length */
     606         518 :     if (s->max_subframe_len_bit) {
     607         518 :         if (get_bits1(&s->gb))
     608         279 :             frame_len_shift = 1 + get_bits(&s->gb, s->subframe_len_bits-1);
     609             :     } else
     610           0 :         frame_len_shift = get_bits(&s->gb, s->subframe_len_bits);
     611             : 
     612         518 :     subframe_len = s->samples_per_frame >> frame_len_shift;
     613             : 
     614             :     /** sanity check the length */
     615        1036 :     if (subframe_len < s->min_samples_per_subframe ||
     616         518 :         subframe_len > s->samples_per_frame) {
     617           0 :         av_log(s->avctx, AV_LOG_ERROR, "broken frame: subframe_len %i\n",
     618             :                subframe_len);
     619           0 :         return AVERROR_INVALIDDATA;
     620             :     }
     621         518 :     return subframe_len;
     622             : }
     623             : 
     624             : /**
     625             :  *@brief Decode how the data in the frame is split into subframes.
     626             :  *       Every WMA frame contains the encoded data for a fixed number of
     627             :  *       samples per channel. The data for every channel might be split
     628             :  *       into several subframes. This function will reconstruct the list of
     629             :  *       subframes for every channel.
     630             :  *
     631             :  *       If the subframes are not evenly split, the algorithm estimates the
     632             :  *       channels with the lowest number of total samples.
     633             :  *       Afterwards, for each of these channels a bit is read from the
     634             :  *       bitstream that indicates if the channel contains a subframe with the
     635             :  *       next subframe size that is going to be read from the bitstream or not.
     636             :  *       If a channel contains such a subframe, the subframe size gets added to
     637             :  *       the channel's subframe list.
     638             :  *       The algorithm repeats these steps until the frame is properly divided
     639             :  *       between the individual channels.
     640             :  *
     641             :  *@param s context
     642             :  *@return 0 on success, < 0 in case of an error
     643             :  */
     644         257 : static int decode_tilehdr(WMAProDecodeCtx *s)
     645             : {
     646         257 :     uint16_t num_samples[WMAPRO_MAX_CHANNELS] = { 0 };/**< sum of samples for all currently known subframes of a channel */
     647             :     uint8_t  contains_subframe[WMAPRO_MAX_CHANNELS];  /**< flag indicating if a channel contains the current subframe */
     648         257 :     int channels_for_cur_subframe = s->nb_channels;   /**< number of channels that contain the current subframe */
     649         257 :     int fixed_channel_layout = 0;                     /**< flag indicating that all channels use the same subframe offsets and sizes */
     650         257 :     int min_channel_len = 0;                          /**< smallest sum of samples (channels with this length will be processed first) */
     651             :     int c;
     652             : 
     653             :     /* Should never consume more than 3073 bits (256 iterations for the
     654             :      * while loop when always the minimum amount of 128 samples is subtracted
     655             :      * from missing samples in the 8 channel case).
     656             :      * 1 + BLOCK_MAX_SIZE * MAX_CHANNELS / BLOCK_MIN_SIZE * (MAX_CHANNELS  + 4)
     657             :      */
     658             : 
     659             :     /** reset tiling information */
     660        1183 :     for (c = 0; c < s->nb_channels; c++)
     661         926 :         s->channel[c].num_subframes = 0;
     662             : 
     663         257 :     if (s->max_num_subframes == 1 || get_bits1(&s->gb))
     664         225 :         fixed_channel_layout = 1;
     665             : 
     666             :     /** loop until the frame data is split between the subframes */
     667             :     do {
     668             :         int subframe_len;
     669             : 
     670             :         /** check which channels contain the subframe */
     671        2813 :         for (c = 0; c < s->nb_channels; c++) {
     672        2286 :             if (num_samples[c] == min_channel_len) {
     673        1501 :                 if (fixed_channel_layout || channels_for_cur_subframe == 1 ||
     674         224 :                    (min_channel_len == s->samples_per_frame - s->min_samples_per_subframe))
     675        1053 :                     contains_subframe[c] = 1;
     676             :                 else
     677         224 :                     contains_subframe[c] = get_bits1(&s->gb);
     678             :             } else
     679        1009 :                 contains_subframe[c] = 0;
     680             :         }
     681             : 
     682             :         /** get subframe length, subframe_len == 0 is not allowed */
     683         527 :         if ((subframe_len = decode_subframe_length(s, min_channel_len)) <= 0)
     684           0 :             return AVERROR_INVALIDDATA;
     685             : 
     686             :         /** add subframes to the individual channels and find new min_channel_len */
     687         527 :         min_channel_len += subframe_len;
     688        2813 :         for (c = 0; c < s->nb_channels; c++) {
     689        2286 :             WMAProChannelCtx* chan = &s->channel[c];
     690             : 
     691        2286 :             if (contains_subframe[c]) {
     692        1234 :                 if (chan->num_subframes >= MAX_SUBFRAMES) {
     693           0 :                     av_log(s->avctx, AV_LOG_ERROR,
     694             :                            "broken frame: num subframes > 31\n");
     695           0 :                     return AVERROR_INVALIDDATA;
     696             :                 }
     697        1234 :                 chan->subframe_len[chan->num_subframes] = subframe_len;
     698        1234 :                 num_samples[c] += subframe_len;
     699        1234 :                 ++chan->num_subframes;
     700        1234 :                 if (num_samples[c] > s->samples_per_frame) {
     701           0 :                     av_log(s->avctx, AV_LOG_ERROR, "broken frame: "
     702             :                            "channel len > samples_per_frame\n");
     703           0 :                     return AVERROR_INVALIDDATA;
     704             :                 }
     705        1052 :             } else if (num_samples[c] <= min_channel_len) {
     706         211 :                 if (num_samples[c] < min_channel_len) {
     707          43 :                     channels_for_cur_subframe = 0;
     708          43 :                     min_channel_len = num_samples[c];
     709             :                 }
     710         211 :                 ++channels_for_cur_subframe;
     711             :             }
     712             :         }
     713         527 :     } while (min_channel_len < s->samples_per_frame);
     714             : 
     715        1183 :     for (c = 0; c < s->nb_channels; c++) {
     716             :         int i;
     717         926 :         int offset = 0;
     718        2160 :         for (i = 0; i < s->channel[c].num_subframes; i++) {
     719             :             ff_dlog(s->avctx, "frame[%"PRIu32"] channel[%i] subframe[%i]"
     720             :                     " len %i\n", s->frame_num, c, i,
     721             :                     s->channel[c].subframe_len[i]);
     722        1234 :             s->channel[c].subframe_offset[i] = offset;
     723        1234 :             offset += s->channel[c].subframe_len[i];
     724             :         }
     725             :     }
     726             : 
     727         257 :     return 0;
     728             : }
     729             : 
     730             : /**
     731             :  *@brief Calculate a decorrelation matrix from the bitstream parameters.
     732             :  *@param s codec context
     733             :  *@param chgroup channel group for which the matrix needs to be calculated
     734             :  */
     735          79 : static void decode_decorrelation_matrix(WMAProDecodeCtx *s,
     736             :                                         WMAProChannelGrp *chgroup)
     737             : {
     738             :     int i;
     739          79 :     int offset = 0;
     740             :     int8_t rotation_offset[WMAPRO_MAX_CHANNELS * WMAPRO_MAX_CHANNELS];
     741         158 :     memset(chgroup->decorrelation_matrix, 0, s->nb_channels *
     742          79 :            s->nb_channels * sizeof(*chgroup->decorrelation_matrix));
     743             : 
     744         316 :     for (i = 0; i < chgroup->num_channels * (chgroup->num_channels - 1) >> 1; i++)
     745         237 :         rotation_offset[i] = get_bits(&s->gb, 6);
     746             : 
     747         316 :     for (i = 0; i < chgroup->num_channels; i++)
     748         237 :         chgroup->decorrelation_matrix[chgroup->num_channels * i + i] =
     749         237 :             get_bits1(&s->gb) ? 1.0 : -1.0;
     750             : 
     751         237 :     for (i = 1; i < chgroup->num_channels; i++) {
     752             :         int x;
     753         395 :         for (x = 0; x < i; x++) {
     754             :             int y;
     755         869 :             for (y = 0; y < i + 1; y++) {
     756         632 :                 float v1 = chgroup->decorrelation_matrix[x * chgroup->num_channels + y];
     757         632 :                 float v2 = chgroup->decorrelation_matrix[i * chgroup->num_channels + y];
     758         632 :                 int n = rotation_offset[offset + x];
     759             :                 float sinv;
     760             :                 float cosv;
     761             : 
     762         632 :                 if (n < 32) {
     763         442 :                     sinv = sin64[n];
     764         442 :                     cosv = sin64[32 - n];
     765             :                 } else {
     766         190 :                     sinv =  sin64[64 -  n];
     767         190 :                     cosv = -sin64[n  - 32];
     768             :                 }
     769             : 
     770        1264 :                 chgroup->decorrelation_matrix[y + x * chgroup->num_channels] =
     771        1264 :                                                (v1 * sinv) - (v2 * cosv);
     772        1264 :                 chgroup->decorrelation_matrix[y + i * chgroup->num_channels] =
     773        1264 :                                                (v1 * cosv) + (v2 * sinv);
     774             :             }
     775             :         }
     776         158 :         offset += i;
     777             :     }
     778          79 : }
     779             : 
     780             : /**
     781             :  *@brief Decode channel transformation parameters
     782             :  *@param s codec context
     783             :  *@return >= 0 in case of success, < 0 in case of bitstream errors
     784             :  */
     785         527 : static int decode_channel_transform(WMAProDecodeCtx* s)
     786             : {
     787             :     int i;
     788             :     /* should never consume more than 1921 bits for the 8 channel case
     789             :      * 1 + MAX_CHANNELS * (MAX_CHANNELS + 2 + 3 * MAX_CHANNELS * MAX_CHANNELS
     790             :      * + MAX_CHANNELS + MAX_BANDS + 1)
     791             :      */
     792             : 
     793             :     /** in the one channel case channel transforms are pointless */
     794         527 :     s->num_chgroups = 0;
     795         527 :     if (s->nb_channels > 1) {
     796         527 :         int remaining_channels = s->channels_for_cur_subframe;
     797             : 
     798         527 :         if (get_bits1(&s->gb)) {
     799           0 :             avpriv_request_sample(s->avctx,
     800             :                                   "Channel transform bit");
     801           0 :             return AVERROR_PATCHWELCOME;
     802             :         }
     803             : 
     804        2312 :         for (s->num_chgroups = 0; remaining_channels &&
     805        1258 :              s->num_chgroups < s->channels_for_cur_subframe; s->num_chgroups++) {
     806         629 :             WMAProChannelGrp* chgroup = &s->chgroup[s->num_chgroups];
     807         629 :             float** channel_data = chgroup->channel_data;
     808         629 :             chgroup->num_channels = 0;
     809         629 :             chgroup->transform = 0;
     810             : 
     811             :             /** decode channel mask */
     812         629 :             if (remaining_channels > 2) {
     813        1217 :                 for (i = 0; i < s->channels_for_cur_subframe; i++) {
     814        1035 :                     int channel_idx = s->channel_indexes_for_cur_subframe[i];
     815        1035 :                     if (!s->channel[channel_idx].grouped
     816         819 :                         && get_bits1(&s->gb)) {
     817         536 :                         ++chgroup->num_channels;
     818         536 :                         s->channel[channel_idx].grouped = 1;
     819         536 :                         *channel_data++ = s->channel[channel_idx].coeffs;
     820             :                     }
     821             :                 }
     822             :             } else {
     823         447 :                 chgroup->num_channels = remaining_channels;
     824        1222 :                 for (i = 0; i < s->channels_for_cur_subframe; i++) {
     825         775 :                     int channel_idx = s->channel_indexes_for_cur_subframe[i];
     826         775 :                     if (!s->channel[channel_idx].grouped)
     827         698 :                         *channel_data++ = s->channel[channel_idx].coeffs;
     828         775 :                     s->channel[channel_idx].grouped = 1;
     829             :                 }
     830             :             }
     831             : 
     832             :             /** decode transform type */
     833         629 :             if (chgroup->num_channels == 2) {
     834         276 :                 if (get_bits1(&s->gb)) {
     835          38 :                     if (get_bits1(&s->gb)) {
     836           0 :                         avpriv_request_sample(s->avctx,
     837             :                                               "Unknown channel transform type");
     838           0 :                         return AVERROR_PATCHWELCOME;
     839             :                     }
     840             :                 } else {
     841         238 :                     chgroup->transform = 1;
     842         238 :                     if (s->nb_channels == 2) {
     843         215 :                         chgroup->decorrelation_matrix[0] =  1.0;
     844         215 :                         chgroup->decorrelation_matrix[1] = -1.0;
     845         215 :                         chgroup->decorrelation_matrix[2] =  1.0;
     846         215 :                         chgroup->decorrelation_matrix[3] =  1.0;
     847             :                     } else {
     848             :                         /** cos(pi/4) */
     849          23 :                         chgroup->decorrelation_matrix[0] =  0.70703125;
     850          23 :                         chgroup->decorrelation_matrix[1] = -0.70703125;
     851          23 :                         chgroup->decorrelation_matrix[2] =  0.70703125;
     852          23 :                         chgroup->decorrelation_matrix[3] =  0.70703125;
     853             :                     }
     854             :                 }
     855         353 :             } else if (chgroup->num_channels > 2) {
     856         157 :                 if (get_bits1(&s->gb)) {
     857          79 :                     chgroup->transform = 1;
     858          79 :                     if (get_bits1(&s->gb)) {
     859          79 :                         decode_decorrelation_matrix(s, chgroup);
     860             :                     } else {
     861             :                         /** FIXME: more than 6 coupled channels not supported */
     862           0 :                         if (chgroup->num_channels > 6) {
     863           0 :                             avpriv_request_sample(s->avctx,
     864             :                                                   "Coupled channels > 6");
     865             :                         } else {
     866           0 :                             memcpy(chgroup->decorrelation_matrix,
     867           0 :                                    default_decorrelation[chgroup->num_channels],
     868           0 :                                    chgroup->num_channels * chgroup->num_channels *
     869             :                                    sizeof(*chgroup->decorrelation_matrix));
     870             :                         }
     871             :                     }
     872             :                 }
     873             :             }
     874             : 
     875             :             /** decode transform on / off */
     876         629 :             if (chgroup->transform) {
     877         317 :                 if (!get_bits1(&s->gb)) {
     878             :                     int i;
     879             :                     /** transform can be enabled for individual bands */
     880           0 :                     for (i = 0; i < s->num_bands; i++) {
     881           0 :                         chgroup->transform_band[i] = get_bits1(&s->gb);
     882             :                     }
     883             :                 } else {
     884         317 :                     memset(chgroup->transform_band, 1, s->num_bands);
     885             :                 }
     886             :             }
     887         629 :             remaining_channels -= chgroup->num_channels;
     888             :         }
     889             :     }
     890         527 :     return 0;
     891             : }
     892             : 
     893             : /**
     894             :  *@brief Extract the coefficients from the bitstream.
     895             :  *@param s codec context
     896             :  *@param c current channel number
     897             :  *@return 0 on success, < 0 in case of bitstream errors
     898             :  */
     899        1038 : static int decode_coeffs(WMAProDecodeCtx *s, int c)
     900             : {
     901             :     /* Integers 0..15 as single-precision floats.  The table saves a
     902             :        costly int to float conversion, and storing the values as
     903             :        integers allows fast sign-flipping. */
     904             :     static const uint32_t fval_tab[16] = {
     905             :         0x00000000, 0x3f800000, 0x40000000, 0x40400000,
     906             :         0x40800000, 0x40a00000, 0x40c00000, 0x40e00000,
     907             :         0x41000000, 0x41100000, 0x41200000, 0x41300000,
     908             :         0x41400000, 0x41500000, 0x41600000, 0x41700000,
     909             :     };
     910             :     int vlctable;
     911             :     VLC* vlc;
     912        1038 :     WMAProChannelCtx* ci = &s->channel[c];
     913        1038 :     int rl_mode = 0;
     914        1038 :     int cur_coeff = 0;
     915        1038 :     int num_zeros = 0;
     916             :     const uint16_t* run;
     917             :     const float* level;
     918             : 
     919             :     ff_dlog(s->avctx, "decode coefficients for channel %i\n", c);
     920             : 
     921        1038 :     vlctable = get_bits1(&s->gb);
     922        1038 :     vlc = &coef_vlc[vlctable];
     923             : 
     924        1038 :     if (vlctable) {
     925         321 :         run = coef1_run;
     926         321 :         level = coef1_level;
     927             :     } else {
     928         717 :         run = coef0_run;
     929         717 :         level = coef0_level;
     930             :     }
     931             : 
     932             :     /** decode vector coefficients (consumes up to 167 bits per iteration for
     933             :       4 vector coded large values) */
     934       78502 :     while ((s->transmit_num_vec_coeffs || !rl_mode) &&
     935       38213 :            (cur_coeff + 3 < ci->num_vec_coeffs)) {
     936             :         uint32_t vals[4];
     937             :         int i;
     938             :         unsigned int idx;
     939             : 
     940       38213 :         idx = get_vlc2(&s->gb, vec4_vlc.table, VLCBITS, VEC4MAXDEPTH);
     941             : 
     942       38213 :         if (idx == HUFF_VEC4_SIZE - 1) {
     943       65430 :             for (i = 0; i < 4; i += 2) {
     944       43620 :                 idx = get_vlc2(&s->gb, vec2_vlc.table, VLCBITS, VEC2MAXDEPTH);
     945       43620 :                 if (idx == HUFF_VEC2_SIZE - 1) {
     946             :                     uint32_t v0, v1;
     947       20544 :                     v0 = get_vlc2(&s->gb, vec1_vlc.table, VLCBITS, VEC1MAXDEPTH);
     948       20544 :                     if (v0 == HUFF_VEC1_SIZE - 1)
     949        1608 :                         v0 += ff_wma_get_large_val(&s->gb);
     950       20544 :                     v1 = get_vlc2(&s->gb, vec1_vlc.table, VLCBITS, VEC1MAXDEPTH);
     951       20544 :                     if (v1 == HUFF_VEC1_SIZE - 1)
     952        1665 :                         v1 += ff_wma_get_large_val(&s->gb);
     953       20544 :                     vals[i  ] = av_float2int(v0);
     954       20544 :                     vals[i+1] = av_float2int(v1);
     955             :                 } else {
     956       23076 :                     vals[i]   = fval_tab[symbol_to_vec2[idx] >> 4 ];
     957       23076 :                     vals[i+1] = fval_tab[symbol_to_vec2[idx] & 0xF];
     958             :                 }
     959             :             }
     960             :         } else {
     961       16403 :             vals[0] = fval_tab[ symbol_to_vec4[idx] >> 12      ];
     962       16403 :             vals[1] = fval_tab[(symbol_to_vec4[idx] >> 8) & 0xF];
     963       16403 :             vals[2] = fval_tab[(symbol_to_vec4[idx] >> 4) & 0xF];
     964       16403 :             vals[3] = fval_tab[ symbol_to_vec4[idx]       & 0xF];
     965             :         }
     966             : 
     967             :         /** decode sign */
     968      191065 :         for (i = 0; i < 4; i++) {
     969      152852 :             if (vals[i]) {
     970      111800 :                 uint32_t sign = get_bits1(&s->gb) - 1;
     971      111800 :                 AV_WN32A(&ci->coeffs[cur_coeff], vals[i] ^ sign << 31);
     972      111800 :                 num_zeros = 0;
     973             :             } else {
     974       41052 :                 ci->coeffs[cur_coeff] = 0;
     975             :                 /** switch to run level mode when subframe_len / 128 zeros
     976             :                     were found in a row */
     977       41052 :                 rl_mode |= (++num_zeros > s->subframe_len >> 8);
     978             :             }
     979      152852 :             ++cur_coeff;
     980             :         }
     981             :     }
     982             : 
     983             :     /** decode run level coded coefficients */
     984        1038 :     if (cur_coeff < s->subframe_len) {
     985        1038 :         memset(&ci->coeffs[cur_coeff], 0,
     986        1038 :                sizeof(*ci->coeffs) * (s->subframe_len - cur_coeff));
     987        4152 :         if (ff_wma_run_level_decode(s->avctx, &s->gb, vlc,
     988        1038 :                                     level, run, 1, ci->coeffs,
     989        1038 :                                     cur_coeff, s->subframe_len,
     990        2076 :                                     s->subframe_len, s->esc_len, 0))
     991           0 :             return AVERROR_INVALIDDATA;
     992             :     }
     993             : 
     994        1038 :     return 0;
     995             : }
     996             : 
     997             : /**
     998             :  *@brief Extract scale factors from the bitstream.
     999             :  *@param s codec context
    1000             :  *@return 0 on success, < 0 in case of bitstream errors
    1001             :  */
    1002         521 : static int decode_scale_factors(WMAProDecodeCtx* s)
    1003             : {
    1004             :     int i;
    1005             : 
    1006             :     /** should never consume more than 5344 bits
    1007             :      *  MAX_CHANNELS * (1 +  MAX_BANDS * 23)
    1008             :      */
    1009             : 
    1010        1745 :     for (i = 0; i < s->channels_for_cur_subframe; i++) {
    1011        1224 :         int c = s->channel_indexes_for_cur_subframe[i];
    1012             :         int* sf;
    1013             :         int* sf_end;
    1014        1224 :         s->channel[c].scale_factors = s->channel[c].saved_scale_factors[!s->channel[c].scale_factor_idx];
    1015        1224 :         sf_end = s->channel[c].scale_factors + s->num_bands;
    1016             : 
    1017             :         /** resample scale factors for the new block size
    1018             :          *  as the scale factors might need to be resampled several times
    1019             :          *  before some  new values are transmitted, a backup of the last
    1020             :          *  transmitted scale factors is kept in saved_scale_factors
    1021             :          */
    1022        1224 :         if (s->channel[c].reuse_sf) {
    1023         298 :             const int8_t* sf_offsets = s->sf_offsets[s->table_idx][s->channel[c].table_idx];
    1024             :             int b;
    1025        5471 :             for (b = 0; b < s->num_bands; b++)
    1026       10346 :                 s->channel[c].scale_factors[b] =
    1027       10346 :                     s->channel[c].saved_scale_factors[s->channel[c].scale_factor_idx][*sf_offsets++];
    1028             :         }
    1029             : 
    1030        1224 :         if (!s->channel[c].cur_subframe || get_bits1(&s->gb)) {
    1031             : 
    1032        1206 :             if (!s->channel[c].reuse_sf) {
    1033             :                 int val;
    1034             :                 /** decode DPCM coded scale factors */
    1035         926 :                 s->channel[c].scale_factor_step = get_bits(&s->gb, 2) + 1;
    1036         926 :                 val = 45 / s->channel[c].scale_factor_step;
    1037       24757 :                 for (sf = s->channel[c].scale_factors; sf < sf_end; sf++) {
    1038       23831 :                     val += get_vlc2(&s->gb, sf_vlc.table, SCALEVLCBITS, SCALEMAXDEPTH) - 60;
    1039       23831 :                     *sf = val;
    1040             :                 }
    1041             :             } else {
    1042             :                 int i;
    1043             :                 /** run level decode differences to the resampled factors */
    1044        1904 :                 for (i = 0; i < s->num_bands; i++) {
    1045             :                     int idx;
    1046             :                     int skip;
    1047             :                     int val;
    1048             :                     int sign;
    1049             : 
    1050        1904 :                     idx = get_vlc2(&s->gb, sf_rl_vlc.table, VLCBITS, SCALERLMAXDEPTH);
    1051             : 
    1052        1904 :                     if (!idx) {
    1053          41 :                         uint32_t code = get_bits(&s->gb, 14);
    1054          41 :                         val  =  code >> 6;
    1055          41 :                         sign = (code & 1) - 1;
    1056          41 :                         skip = (code & 0x3f) >> 1;
    1057        1863 :                     } else if (idx == 1) {
    1058         280 :                         break;
    1059             :                     } else {
    1060        1583 :                         skip = scale_rl_run[idx];
    1061        1583 :                         val  = scale_rl_level[idx];
    1062        1583 :                         sign = get_bits1(&s->gb)-1;
    1063             :                     }
    1064             : 
    1065        1624 :                     i += skip;
    1066        1624 :                     if (i >= s->num_bands) {
    1067           0 :                         av_log(s->avctx, AV_LOG_ERROR,
    1068             :                                "invalid scale factor coding\n");
    1069           0 :                         return AVERROR_INVALIDDATA;
    1070             :                     }
    1071        1624 :                     s->channel[c].scale_factors[i] += (val ^ sign) - sign;
    1072             :                 }
    1073             :             }
    1074             :             /** swap buffers */
    1075        1206 :             s->channel[c].scale_factor_idx = !s->channel[c].scale_factor_idx;
    1076        1206 :             s->channel[c].table_idx = s->table_idx;
    1077        1206 :             s->channel[c].reuse_sf  = 1;
    1078             :         }
    1079             : 
    1080             :         /** calculate new scale factor maximum */
    1081        1224 :         s->channel[c].max_scale_factor = s->channel[c].scale_factors[0];
    1082       29004 :         for (sf = s->channel[c].scale_factors + 1; sf < sf_end; sf++) {
    1083       27780 :             s->channel[c].max_scale_factor =
    1084       27780 :                 FFMAX(s->channel[c].max_scale_factor, *sf);
    1085             :         }
    1086             : 
    1087             :     }
    1088         521 :     return 0;
    1089             : }
    1090             : 
    1091             : /**
    1092             :  *@brief Reconstruct the individual channel data.
    1093             :  *@param s codec context
    1094             :  */
    1095         521 : static void inverse_channel_transform(WMAProDecodeCtx *s)
    1096             : {
    1097             :     int i;
    1098             : 
    1099        1144 :     for (i = 0; i < s->num_chgroups; i++) {
    1100         623 :         if (s->chgroup[i].transform) {
    1101             :             float data[WMAPRO_MAX_CHANNELS];
    1102         317 :             const int num_channels = s->chgroup[i].num_channels;
    1103         317 :             float** ch_data = s->chgroup[i].channel_data;
    1104         317 :             float** ch_end = ch_data + num_channels;
    1105         317 :             const int8_t* tb = s->chgroup[i].transform_band;
    1106             :             int16_t* sfb;
    1107             : 
    1108             :             /** multichannel decorrelation */
    1109        8330 :             for (sfb = s->cur_sfb_offsets;
    1110        7696 :                  sfb < s->cur_sfb_offsets + s->num_bands; sfb++) {
    1111             :                 int y;
    1112        7696 :                 if (*tb++ == 1) {
    1113             :                     /** multiply values with the decorrelation_matrix */
    1114      530064 :                     for (y = sfb[0]; y < FFMIN(sfb[1], s->subframe_len); y++) {
    1115      522368 :                         const float* mat = s->chgroup[i].decorrelation_matrix;
    1116      522368 :                         const float* data_end = data + num_channels;
    1117      522368 :                         float* data_ptr = data;
    1118             :                         float** ch;
    1119             : 
    1120     1728896 :                         for (ch = ch_data; ch < ch_end; ch++)
    1121     1206528 :                             *data_ptr++ = (*ch)[y];
    1122             : 
    1123     1728896 :                         for (ch = ch_data; ch < ch_end; ch++) {
    1124     1206528 :                             float sum = 0;
    1125     1206528 :                             data_ptr = data;
    1126     5311488 :                             while (data_ptr < data_end)
    1127     2898432 :                                 sum += *data_ptr++ * *mat++;
    1128             : 
    1129     1206528 :                             (*ch)[y] = sum;
    1130             :                         }
    1131             :                     }
    1132           0 :                 } else if (s->nb_channels == 2) {
    1133           0 :                     int len = FFMIN(sfb[1], s->subframe_len) - sfb[0];
    1134           0 :                     s->fdsp->vector_fmul_scalar(ch_data[0] + sfb[0],
    1135           0 :                                                ch_data[0] + sfb[0],
    1136             :                                                181.0 / 128, len);
    1137           0 :                     s->fdsp->vector_fmul_scalar(ch_data[1] + sfb[0],
    1138           0 :                                                ch_data[1] + sfb[0],
    1139             :                                                181.0 / 128, len);
    1140             :                 }
    1141             :             }
    1142             :         }
    1143             :     }
    1144         521 : }
    1145             : 
    1146             : /**
    1147             :  *@brief Apply sine window and reconstruct the output buffer.
    1148             :  *@param s codec context
    1149             :  */
    1150         527 : static void wmapro_window(WMAProDecodeCtx *s)
    1151             : {
    1152             :     int i;
    1153        1761 :     for (i = 0; i < s->channels_for_cur_subframe; i++) {
    1154        1234 :         int c = s->channel_indexes_for_cur_subframe[i];
    1155             :         const float* window;
    1156        1234 :         int winlen = s->channel[c].prev_block_len;
    1157        1234 :         float* start = s->channel[c].coeffs - (winlen >> 1);
    1158             : 
    1159        1234 :         if (s->subframe_len < winlen) {
    1160         142 :             start += (winlen - s->subframe_len) >> 1;
    1161         142 :             winlen = s->subframe_len;
    1162             :         }
    1163             : 
    1164        1234 :         window = s->windows[av_log2(winlen) - WMAPRO_BLOCK_MIN_BITS];
    1165             : 
    1166        1234 :         winlen >>= 1;
    1167             : 
    1168        1234 :         s->fdsp->vector_fmul_window(start, start, start + winlen,
    1169             :                                    window, winlen);
    1170             : 
    1171        1234 :         s->channel[c].prev_block_len = s->subframe_len;
    1172             :     }
    1173         527 : }
    1174             : 
    1175             : /**
    1176             :  *@brief Decode a single subframe (block).
    1177             :  *@param s codec context
    1178             :  *@return 0 on success, < 0 when decoding failed
    1179             :  */
    1180         527 : static int decode_subframe(WMAProDecodeCtx *s)
    1181             : {
    1182         527 :     int offset = s->samples_per_frame;
    1183         527 :     int subframe_len = s->samples_per_frame;
    1184             :     int i;
    1185         527 :     int total_samples   = s->samples_per_frame * s->nb_channels;
    1186         527 :     int transmit_coeffs = 0;
    1187             :     int cur_subwoofer_cutoff;
    1188             : 
    1189         527 :     s->subframe_offset = get_bits_count(&s->gb);
    1190             : 
    1191             :     /** reset channel context and find the next block offset and size
    1192             :         == the next block of the channel with the smallest number of
    1193             :         decoded samples
    1194             :     */
    1195        2813 :     for (i = 0; i < s->nb_channels; i++) {
    1196        2286 :         s->channel[i].grouped = 0;
    1197        2286 :         if (offset > s->channel[i].decoded_samples) {
    1198         539 :             offset = s->channel[i].decoded_samples;
    1199         539 :             subframe_len =
    1200         539 :                 s->channel[i].subframe_len[s->channel[i].cur_subframe];
    1201             :         }
    1202             :     }
    1203             : 
    1204             :     ff_dlog(s->avctx,
    1205             :             "processing subframe with offset %i len %i\n", offset, subframe_len);
    1206             : 
    1207             :     /** get a list of all channels that contain the estimated block */
    1208         527 :     s->channels_for_cur_subframe = 0;
    1209        2813 :     for (i = 0; i < s->nb_channels; i++) {
    1210        2286 :         const int cur_subframe = s->channel[i].cur_subframe;
    1211             :         /** subtract already processed samples */
    1212        2286 :         total_samples -= s->channel[i].decoded_samples;
    1213             : 
    1214             :         /** and count if there are multiple subframes that match our profile */
    1215        3563 :         if (offset == s->channel[i].decoded_samples &&
    1216        1277 :             subframe_len == s->channel[i].subframe_len[cur_subframe]) {
    1217        1234 :             total_samples -= s->channel[i].subframe_len[cur_subframe];
    1218        2468 :             s->channel[i].decoded_samples +=
    1219        1234 :                 s->channel[i].subframe_len[cur_subframe];
    1220        1234 :             s->channel_indexes_for_cur_subframe[s->channels_for_cur_subframe] = i;
    1221        1234 :             ++s->channels_for_cur_subframe;
    1222             :         }
    1223             :     }
    1224             : 
    1225             :     /** check if the frame will be complete after processing the
    1226             :         estimated block */
    1227         527 :     if (!total_samples)
    1228         257 :         s->parsed_all_subframes = 1;
    1229             : 
    1230             : 
    1231             :     ff_dlog(s->avctx, "subframe is part of %i channels\n",
    1232             :             s->channels_for_cur_subframe);
    1233             : 
    1234             :     /** calculate number of scale factor bands and their offsets */
    1235         527 :     s->table_idx         = av_log2(s->samples_per_frame/subframe_len);
    1236         527 :     s->num_bands         = s->num_sfb[s->table_idx];
    1237         527 :     s->cur_sfb_offsets   = s->sfb_offsets[s->table_idx];
    1238         527 :     cur_subwoofer_cutoff = s->subwoofer_cutoffs[s->table_idx];
    1239             : 
    1240             :     /** configure the decoder for the current subframe */
    1241         527 :     offset += s->samples_per_frame >> 1;
    1242             : 
    1243        1761 :     for (i = 0; i < s->channels_for_cur_subframe; i++) {
    1244        1234 :         int c = s->channel_indexes_for_cur_subframe[i];
    1245             : 
    1246        1234 :         s->channel[c].coeffs = &s->channel[c].out[offset];
    1247             :     }
    1248             : 
    1249         527 :     s->subframe_len = subframe_len;
    1250         527 :     s->esc_len = av_log2(s->subframe_len - 1) + 1;
    1251             : 
    1252             :     /** skip extended header if any */
    1253         527 :     if (get_bits1(&s->gb)) {
    1254             :         int num_fill_bits;
    1255         158 :         if (!(num_fill_bits = get_bits(&s->gb, 2))) {
    1256         158 :             int len = get_bits(&s->gb, 4);
    1257         158 :             num_fill_bits = get_bitsz(&s->gb, len) + 1;
    1258             :         }
    1259             : 
    1260         158 :         if (num_fill_bits >= 0) {
    1261         158 :             if (get_bits_count(&s->gb) + num_fill_bits > s->num_saved_bits) {
    1262           0 :                 av_log(s->avctx, AV_LOG_ERROR, "invalid number of fill bits\n");
    1263           0 :                 return AVERROR_INVALIDDATA;
    1264             :             }
    1265             : 
    1266         158 :             skip_bits_long(&s->gb, num_fill_bits);
    1267             :         }
    1268             :     }
    1269             : 
    1270             :     /** no idea for what the following bit is used */
    1271         527 :     if (get_bits1(&s->gb)) {
    1272           0 :         avpriv_request_sample(s->avctx, "Reserved bit");
    1273           0 :         return AVERROR_PATCHWELCOME;
    1274             :     }
    1275             : 
    1276             : 
    1277         527 :     if (decode_channel_transform(s) < 0)
    1278           0 :         return AVERROR_INVALIDDATA;
    1279             : 
    1280             : 
    1281        1761 :     for (i = 0; i < s->channels_for_cur_subframe; i++) {
    1282        1234 :         int c = s->channel_indexes_for_cur_subframe[i];
    1283        1234 :         if ((s->channel[c].transmit_coefs = get_bits1(&s->gb)))
    1284        1038 :             transmit_coeffs = 1;
    1285             :     }
    1286             : 
    1287         527 :     av_assert0(s->subframe_len <= WMAPRO_BLOCK_MAX_SIZE);
    1288         527 :     if (transmit_coeffs) {
    1289             :         int step;
    1290         521 :         int quant_step = 90 * s->bits_per_sample >> 4;
    1291             : 
    1292             :         /** decode number of vector coded coefficients */
    1293         521 :         if ((s->transmit_num_vec_coeffs = get_bits1(&s->gb))) {
    1294           0 :             int num_bits = av_log2((s->subframe_len + 3)/4) + 1;
    1295           0 :             for (i = 0; i < s->channels_for_cur_subframe; i++) {
    1296           0 :                 int c = s->channel_indexes_for_cur_subframe[i];
    1297           0 :                 int num_vec_coeffs = get_bits(&s->gb, num_bits) << 2;
    1298           0 :                 if (num_vec_coeffs > s->subframe_len) {
    1299           0 :                     av_log(s->avctx, AV_LOG_ERROR, "num_vec_coeffs %d is too large\n", num_vec_coeffs);
    1300           0 :                     return AVERROR_INVALIDDATA;
    1301             :                 }
    1302           0 :                 av_assert0(num_vec_coeffs + offset <= FF_ARRAY_ELEMS(s->channel[c].out));
    1303           0 :                 s->channel[c].num_vec_coeffs = num_vec_coeffs;
    1304             :             }
    1305             :         } else {
    1306        1745 :             for (i = 0; i < s->channels_for_cur_subframe; i++) {
    1307        1224 :                 int c = s->channel_indexes_for_cur_subframe[i];
    1308        1224 :                 s->channel[c].num_vec_coeffs = s->subframe_len;
    1309             :             }
    1310             :         }
    1311             :         /** decode quantization step */
    1312         521 :         step = get_sbits(&s->gb, 6);
    1313         521 :         quant_step += step;
    1314         521 :         if (step == -32 || step == 31) {
    1315          23 :             const int sign = (step == 31) - 1;
    1316          23 :             int quant = 0;
    1317          69 :             while (get_bits_count(&s->gb) + 5 < s->num_saved_bits &&
    1318          23 :                    (step = get_bits(&s->gb, 5)) == 31) {
    1319           0 :                 quant += 31;
    1320             :             }
    1321          23 :             quant_step += ((quant + step) ^ sign) - sign;
    1322             :         }
    1323         521 :         if (quant_step < 0) {
    1324           0 :             av_log(s->avctx, AV_LOG_DEBUG, "negative quant step\n");
    1325             :         }
    1326             : 
    1327             :         /** decode quantization step modifiers for every channel */
    1328             : 
    1329         521 :         if (s->channels_for_cur_subframe == 1) {
    1330         194 :             s->channel[s->channel_indexes_for_cur_subframe[0]].quant_step = quant_step;
    1331             :         } else {
    1332         327 :             int modifier_len = get_bits(&s->gb, 3);
    1333        1357 :             for (i = 0; i < s->channels_for_cur_subframe; i++) {
    1334        1030 :                 int c = s->channel_indexes_for_cur_subframe[i];
    1335        1030 :                 s->channel[c].quant_step = quant_step;
    1336        1030 :                 if (get_bits1(&s->gb)) {
    1337         511 :                     if (modifier_len) {
    1338         458 :                         s->channel[c].quant_step += get_bits(&s->gb, modifier_len) + 1;
    1339             :                     } else
    1340          53 :                         ++s->channel[c].quant_step;
    1341             :                 }
    1342             :             }
    1343             :         }
    1344             : 
    1345             :         /** decode scale factors */
    1346         521 :         if (decode_scale_factors(s) < 0)
    1347           0 :             return AVERROR_INVALIDDATA;
    1348             :     }
    1349             : 
    1350             :     ff_dlog(s->avctx, "BITSTREAM: subframe header length was %i\n",
    1351             :             get_bits_count(&s->gb) - s->subframe_offset);
    1352             : 
    1353             :     /** parse coefficients */
    1354        1761 :     for (i = 0; i < s->channels_for_cur_subframe; i++) {
    1355        1234 :         int c = s->channel_indexes_for_cur_subframe[i];
    1356        2272 :         if (s->channel[c].transmit_coefs &&
    1357        1038 :             get_bits_count(&s->gb) < s->num_saved_bits) {
    1358        1038 :             decode_coeffs(s, c);
    1359             :         } else
    1360         196 :             memset(s->channel[c].coeffs, 0,
    1361             :                    sizeof(*s->channel[c].coeffs) * subframe_len);
    1362             :     }
    1363             : 
    1364             :     ff_dlog(s->avctx, "BITSTREAM: subframe length was %i\n",
    1365             :             get_bits_count(&s->gb) - s->subframe_offset);
    1366             : 
    1367         527 :     if (transmit_coeffs) {
    1368         521 :         FFTContext *mdct = &s->mdct_ctx[av_log2(subframe_len) - WMAPRO_BLOCK_MIN_BITS];
    1369             :         /** reconstruct the per channel data */
    1370         521 :         inverse_channel_transform(s);
    1371        1745 :         for (i = 0; i < s->channels_for_cur_subframe; i++) {
    1372        1224 :             int c = s->channel_indexes_for_cur_subframe[i];
    1373        1224 :             const int* sf = s->channel[c].scale_factors;
    1374             :             int b;
    1375             : 
    1376        1224 :             if (c == s->lfe_channel)
    1377         103 :                 memset(&s->tmp[cur_subwoofer_cutoff], 0, sizeof(*s->tmp) *
    1378         103 :                        (subframe_len - cur_subwoofer_cutoff));
    1379             : 
    1380             :             /** inverse quantization and rescaling */
    1381       30228 :             for (b = 0; b < s->num_bands; b++) {
    1382       29004 :                 const int end = FFMIN(s->cur_sfb_offsets[b+1], s->subframe_len);
    1383       58008 :                 const int exp = s->channel[c].quant_step -
    1384       58008 :                             (s->channel[c].max_scale_factor - *sf++) *
    1385       29004 :                             s->channel[c].scale_factor_step;
    1386       29004 :                 const float quant = ff_exp10(exp / 20.0);
    1387       29004 :                 int start = s->cur_sfb_offsets[b];
    1388       58008 :                 s->fdsp->vector_fmul_scalar(s->tmp + start,
    1389       29004 :                                            s->channel[c].coeffs + start,
    1390             :                                            quant, end - start);
    1391             :             }
    1392             : 
    1393             :             /** apply imdct (imdct_half == DCTIV with reverse) */
    1394        1224 :             mdct->imdct_half(mdct, s->channel[c].coeffs, s->tmp);
    1395             :         }
    1396             :     }
    1397             : 
    1398             :     /** window and overlapp-add */
    1399         527 :     wmapro_window(s);
    1400             : 
    1401             :     /** handled one subframe */
    1402        1761 :     for (i = 0; i < s->channels_for_cur_subframe; i++) {
    1403        1234 :         int c = s->channel_indexes_for_cur_subframe[i];
    1404        1234 :         if (s->channel[c].cur_subframe >= s->channel[c].num_subframes) {
    1405           0 :             av_log(s->avctx, AV_LOG_ERROR, "broken subframe\n");
    1406           0 :             return AVERROR_INVALIDDATA;
    1407             :         }
    1408        1234 :         ++s->channel[c].cur_subframe;
    1409             :     }
    1410             : 
    1411         527 :     return 0;
    1412             : }
    1413             : 
    1414             : /**
    1415             :  *@brief Decode one WMA frame.
    1416             :  *@param s codec context
    1417             :  *@return 0 if the trailer bit indicates that this is the last frame,
    1418             :  *        1 if there are additional frames
    1419             :  */
    1420         257 : static int decode_frame(WMAProDecodeCtx *s, AVFrame *frame, int *got_frame_ptr)
    1421             : {
    1422         257 :     GetBitContext* gb = &s->gb;
    1423         257 :     int more_frames = 0;
    1424         257 :     int len = 0;
    1425             :     int i;
    1426             : 
    1427             :     /** get frame length */
    1428         257 :     if (s->len_prefix)
    1429         257 :         len = get_bits(gb, s->log2_frame_size);
    1430             : 
    1431             :     ff_dlog(s->avctx, "decoding frame with length %x\n", len);
    1432             : 
    1433             :     /** decode tile information */
    1434         257 :     if (decode_tilehdr(s)) {
    1435           0 :         s->packet_loss = 1;
    1436           0 :         return 0;
    1437             :     }
    1438             : 
    1439             :     /** read postproc transform */
    1440         257 :     if (s->nb_channels > 1 && get_bits1(gb)) {
    1441           0 :         if (get_bits1(gb)) {
    1442           0 :             for (i = 0; i < s->nb_channels * s->nb_channels; i++)
    1443           0 :                 skip_bits(gb, 4);
    1444             :         }
    1445             :     }
    1446             : 
    1447             :     /** read drc info */
    1448         257 :     if (s->dynamic_range_compression) {
    1449         257 :         s->drc_gain = get_bits(gb, 8);
    1450             :         ff_dlog(s->avctx, "drc_gain %i\n", s->drc_gain);
    1451             :     }
    1452             : 
    1453             :     /** no idea what these are for, might be the number of samples
    1454             :         that need to be skipped at the beginning or end of a stream */
    1455         257 :     if (get_bits1(gb)) {
    1456             :         int av_unused skip;
    1457             : 
    1458             :         /** usually true for the first frame */
    1459           4 :         if (get_bits1(gb)) {
    1460           3 :             skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
    1461             :             ff_dlog(s->avctx, "start skip: %i\n", skip);
    1462             :         }
    1463             : 
    1464             :         /** sometimes true for the last frame */
    1465           4 :         if (get_bits1(gb)) {
    1466           1 :             skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
    1467             :             ff_dlog(s->avctx, "end skip: %i\n", skip);
    1468             :         }
    1469             : 
    1470             :     }
    1471             : 
    1472             :     ff_dlog(s->avctx, "BITSTREAM: frame header length was %i\n",
    1473             :             get_bits_count(gb) - s->frame_offset);
    1474             : 
    1475             :     /** reset subframe states */
    1476         257 :     s->parsed_all_subframes = 0;
    1477        1183 :     for (i = 0; i < s->nb_channels; i++) {
    1478         926 :         s->channel[i].decoded_samples = 0;
    1479         926 :         s->channel[i].cur_subframe    = 0;
    1480         926 :         s->channel[i].reuse_sf        = 0;
    1481             :     }
    1482             : 
    1483             :     /** decode all subframes */
    1484        1041 :     while (!s->parsed_all_subframes) {
    1485         527 :         if (decode_subframe(s) < 0) {
    1486           0 :             s->packet_loss = 1;
    1487           0 :             return 0;
    1488             :         }
    1489             :     }
    1490             : 
    1491             :     /** copy samples to the output buffer */
    1492        1183 :     for (i = 0; i < s->nb_channels; i++)
    1493         926 :         memcpy(frame->extended_data[i], s->channel[i].out,
    1494         926 :                s->samples_per_frame * sizeof(*s->channel[i].out));
    1495             : 
    1496        1183 :     for (i = 0; i < s->nb_channels; i++) {
    1497             :         /** reuse second half of the IMDCT output for the next frame */
    1498        1852 :         memcpy(&s->channel[i].out[0],
    1499         926 :                &s->channel[i].out[s->samples_per_frame],
    1500         926 :                s->samples_per_frame * sizeof(*s->channel[i].out) >> 1);
    1501             :     }
    1502             : 
    1503         257 :     if (s->skip_frame) {
    1504           3 :         s->skip_frame = 0;
    1505           3 :         *got_frame_ptr = 0;
    1506           3 :         av_frame_unref(frame);
    1507             :     } else {
    1508         254 :         *got_frame_ptr = 1;
    1509             :     }
    1510             : 
    1511         257 :     if (s->len_prefix) {
    1512         257 :         if (len != (get_bits_count(gb) - s->frame_offset) + 2) {
    1513             :             /** FIXME: not sure if this is always an error */
    1514           0 :             av_log(s->avctx, AV_LOG_ERROR,
    1515             :                    "frame[%"PRIu32"] would have to skip %i bits\n",
    1516             :                    s->frame_num,
    1517           0 :                    len - (get_bits_count(gb) - s->frame_offset) - 1);
    1518           0 :             s->packet_loss = 1;
    1519           0 :             return 0;
    1520             :         }
    1521             : 
    1522             :         /** skip the rest of the frame data */
    1523         257 :         skip_bits_long(gb, len - (get_bits_count(gb) - s->frame_offset) - 1);
    1524             :     } else {
    1525           0 :         while (get_bits_count(gb) < s->num_saved_bits && get_bits1(gb) == 0) {
    1526             :         }
    1527             :     }
    1528             : 
    1529             :     /** decode trailer bit */
    1530         257 :     more_frames = get_bits1(gb);
    1531             : 
    1532         257 :     ++s->frame_num;
    1533         257 :     return more_frames;
    1534             : }
    1535             : 
    1536             : /**
    1537             :  *@brief Calculate remaining input buffer length.
    1538             :  *@param s codec context
    1539             :  *@param gb bitstream reader context
    1540             :  *@return remaining size in bits
    1541             :  */
    1542         849 : static int remaining_bits(WMAProDecodeCtx *s, GetBitContext *gb)
    1543             : {
    1544         849 :     return s->buf_bit_size - get_bits_count(gb);
    1545             : }
    1546             : 
    1547             : /**
    1548             :  *@brief Fill the bit reservoir with a (partial) frame.
    1549             :  *@param s codec context
    1550             :  *@param gb bitstream reader context
    1551             :  *@param len length of the partial frame
    1552             :  *@param append decides whether to reset the buffer or not
    1553             :  */
    1554         281 : static void save_bits(WMAProDecodeCtx *s, GetBitContext* gb, int len,
    1555             :                       int append)
    1556             : {
    1557             :     int buflen;
    1558             : 
    1559             :     /** when the frame data does not need to be concatenated, the input buffer
    1560             :         is reset and additional bits from the previous frame are copied
    1561             :         and skipped later so that a fast byte copy is possible */
    1562             : 
    1563         281 :     if (!append) {
    1564         260 :         s->frame_offset = get_bits_count(gb) & 7;
    1565         260 :         s->num_saved_bits = s->frame_offset;
    1566         260 :         init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
    1567             :     }
    1568             : 
    1569         281 :     buflen = (put_bits_count(&s->pb) + len + 8) >> 3;
    1570             : 
    1571         281 :     if (len <= 0 || buflen > MAX_FRAMESIZE) {
    1572           0 :         avpriv_request_sample(s->avctx, "Too small input buffer");
    1573           0 :         s->packet_loss = 1;
    1574           0 :         return;
    1575             :     }
    1576             : 
    1577         281 :     av_assert0(len <= put_bits_left(&s->pb));
    1578             : 
    1579         281 :     s->num_saved_bits += len;
    1580         281 :     if (!append) {
    1581         260 :         avpriv_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3),
    1582             :                      s->num_saved_bits);
    1583             :     } else {
    1584          21 :         int align = 8 - (get_bits_count(gb) & 7);
    1585          21 :         align = FFMIN(align, len);
    1586          21 :         put_bits(&s->pb, align, get_bits(gb, align));
    1587          21 :         len -= align;
    1588          21 :         avpriv_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3), len);
    1589             :     }
    1590         281 :     skip_bits_long(gb, len);
    1591             : 
    1592             :     {
    1593         281 :         PutBitContext tmp = s->pb;
    1594         281 :         flush_put_bits(&tmp);
    1595             :     }
    1596             : 
    1597         281 :     init_get_bits(&s->gb, s->frame_data, s->num_saved_bits);
    1598         281 :     skip_bits(&s->gb, s->frame_offset);
    1599             : }
    1600             : 
    1601         283 : static int decode_packet(AVCodecContext *avctx, WMAProDecodeCtx *s,
    1602             :                          void *data, int *got_frame_ptr, AVPacket *avpkt)
    1603             : {
    1604         283 :     GetBitContext* gb  = &s->pgb;
    1605         283 :     const uint8_t* buf = avpkt->data;
    1606         283 :     int buf_size       = avpkt->size;
    1607             :     int num_bits_prev_frame;
    1608             :     int packet_sequence_number;
    1609             : 
    1610         283 :     *got_frame_ptr = 0;
    1611             : 
    1612         283 :     if (s->packet_done || s->packet_loss) {
    1613          24 :         s->packet_done = 0;
    1614             : 
    1615             :         /** sanity check for the buffer length */
    1616          24 :         if (avctx->codec_id == AV_CODEC_ID_WMAPRO && buf_size < avctx->block_align) {
    1617           0 :             av_log(avctx, AV_LOG_ERROR, "Input packet too small (%d < %d)\n",
    1618             :                    buf_size, avctx->block_align);
    1619           0 :             return AVERROR_INVALIDDATA;
    1620             :         }
    1621             : 
    1622          24 :         if (avctx->codec_id == AV_CODEC_ID_WMAPRO) {
    1623          24 :             s->next_packet_start = buf_size - avctx->block_align;
    1624          24 :             buf_size = avctx->block_align;
    1625             :         } else {
    1626           0 :             s->next_packet_start = buf_size - FFMIN(buf_size, avctx->block_align);
    1627           0 :             buf_size = FFMIN(buf_size, avctx->block_align);
    1628             :         }
    1629          24 :         s->buf_bit_size = buf_size << 3;
    1630             : 
    1631             :         /** parse packet header */
    1632          24 :         init_get_bits(gb, buf, s->buf_bit_size);
    1633          24 :         if (avctx->codec_id != AV_CODEC_ID_XMA2) {
    1634          24 :             packet_sequence_number = get_bits(gb, 4);
    1635          24 :             skip_bits(gb, 2);
    1636             :         } else {
    1637           0 :             int num_frames = get_bits(gb, 6);
    1638             :             ff_dlog(avctx, "packet[%d]: number of frames %d\n", avctx->frame_number, num_frames);
    1639           0 :             packet_sequence_number = 0;
    1640             :         }
    1641             : 
    1642             :         /** get number of bits that need to be added to the previous frame */
    1643          24 :         num_bits_prev_frame = get_bits(gb, s->log2_frame_size);
    1644          24 :         if (avctx->codec_id != AV_CODEC_ID_WMAPRO) {
    1645           0 :             skip_bits(gb, 3);
    1646           0 :             s->skip_packets = get_bits(gb, 8);
    1647             :             ff_dlog(avctx, "packet[%d]: skip packets %d\n", avctx->frame_number, s->skip_packets);
    1648             :         }
    1649             : 
    1650             :         ff_dlog(avctx, "packet[%d]: nbpf %x\n", avctx->frame_number,
    1651             :                 num_bits_prev_frame);
    1652             : 
    1653             :         /** check for packet loss */
    1654          45 :         if (avctx->codec_id == AV_CODEC_ID_WMAPRO && !s->packet_loss &&
    1655          21 :             ((s->packet_sequence_number + 1) & 0xF) != packet_sequence_number) {
    1656           0 :             s->packet_loss = 1;
    1657           0 :             av_log(avctx, AV_LOG_ERROR,
    1658             :                    "Packet loss detected! seq %"PRIx8" vs %x\n",
    1659           0 :                    s->packet_sequence_number, packet_sequence_number);
    1660             :         }
    1661          24 :         s->packet_sequence_number = packet_sequence_number;
    1662             : 
    1663          24 :         if (num_bits_prev_frame > 0) {
    1664          21 :             int remaining_packet_bits = s->buf_bit_size - get_bits_count(gb);
    1665          21 :             if (num_bits_prev_frame >= remaining_packet_bits) {
    1666           0 :                 num_bits_prev_frame = remaining_packet_bits;
    1667           0 :                 s->packet_done = 1;
    1668             :             }
    1669             : 
    1670             :             /** append the previous frame data to the remaining data from the
    1671             :                 previous packet to create a full frame */
    1672          21 :             save_bits(s, gb, num_bits_prev_frame, 1);
    1673             :             ff_dlog(avctx, "accumulated %x bits of frame data\n",
    1674             :                     s->num_saved_bits - s->frame_offset);
    1675             : 
    1676             :             /** decode the cross packet frame if it is valid */
    1677          21 :             if (!s->packet_loss)
    1678          21 :                 decode_frame(s, data, got_frame_ptr);
    1679           3 :         } else if (s->num_saved_bits - s->frame_offset) {
    1680             :             ff_dlog(avctx, "ignoring %x previously saved bits\n",
    1681             :                     s->num_saved_bits - s->frame_offset);
    1682             :         }
    1683             : 
    1684          48 :         if (s->packet_loss) {
    1685             :             /** reset number of saved bits so that the decoder
    1686             :                 does not start to decode incomplete frames in the
    1687             :                 s->len_prefix == 0 case */
    1688           3 :             s->num_saved_bits = 0;
    1689           3 :             s->packet_loss = 0;
    1690             :         }
    1691             :     } else {
    1692             :         int frame_size;
    1693         259 :         s->buf_bit_size = (avpkt->size - s->next_packet_start) << 3;
    1694         259 :         init_get_bits(gb, avpkt->data, s->buf_bit_size);
    1695         259 :         skip_bits(gb, s->packet_offset);
    1696         518 :         if (s->len_prefix && remaining_bits(s, gb) > s->log2_frame_size &&
    1697         518 :             (frame_size = show_bits(gb, s->log2_frame_size)) &&
    1698         259 :             frame_size <= remaining_bits(s, gb)) {
    1699         236 :             save_bits(s, gb, frame_size, 0);
    1700         472 :             if (!s->packet_loss)
    1701         236 :                 s->packet_done = !decode_frame(s, data, got_frame_ptr);
    1702          23 :         } else if (!s->len_prefix
    1703           0 :                    && s->num_saved_bits > get_bits_count(&s->gb)) {
    1704             :             /** when the frames do not have a length prefix, we don't know
    1705             :                 the compressed length of the individual frames
    1706             :                 however, we know what part of a new packet belongs to the
    1707             :                 previous frame
    1708             :                 therefore we save the incoming packet first, then we append
    1709             :                 the "previous frame" data from the next packet so that
    1710             :                 we get a buffer that only contains full frames */
    1711           0 :             s->packet_done = !decode_frame(s, data, got_frame_ptr);
    1712             :         } else {
    1713          23 :             s->packet_done = 1;
    1714             :         }
    1715             :     }
    1716             : 
    1717         283 :     if (remaining_bits(s, gb) < 0) {
    1718           0 :         av_log(avctx, AV_LOG_ERROR, "Overread %d\n", -remaining_bits(s, gb));
    1719           0 :         s->packet_loss = 1;
    1720             :     }
    1721             : 
    1722         307 :     if (s->packet_done && !s->packet_loss &&
    1723          24 :         remaining_bits(s, gb) > 0) {
    1724             :         /** save the rest of the data so that it can be decoded
    1725             :             with the next packet */
    1726          24 :         save_bits(s, gb, remaining_bits(s, gb), 0);
    1727             :     }
    1728             : 
    1729         283 :     s->packet_offset = get_bits_count(gb) & 7;
    1730         283 :     if (s->packet_loss)
    1731           0 :         return AVERROR_INVALIDDATA;
    1732             : 
    1733         283 :     return get_bits_count(gb) >> 3;
    1734             : }
    1735             : 
    1736             : /**
    1737             :  *@brief Decode a single WMA packet.
    1738             :  *@param avctx codec context
    1739             :  *@param data the output buffer
    1740             :  *@param avpkt input packet
    1741             :  *@return number of bytes that were read from the input buffer
    1742             :  */
    1743         283 : static int wmapro_decode_packet(AVCodecContext *avctx, void *data,
    1744             :                                 int *got_frame_ptr, AVPacket *avpkt)
    1745             : {
    1746         283 :     WMAProDecodeCtx *s = avctx->priv_data;
    1747         283 :     AVFrame *frame = data;
    1748             :     int ret;
    1749             : 
    1750             :     /* get output buffer */
    1751         283 :     frame->nb_samples = s->samples_per_frame;
    1752         283 :     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
    1753           0 :         s->packet_loss = 1;
    1754           0 :         return 0;
    1755             :     }
    1756             : 
    1757         283 :     return decode_packet(avctx, s, data, got_frame_ptr, avpkt);
    1758             : }
    1759             : 
    1760           0 : static int xma_decode_packet(AVCodecContext *avctx, void *data,
    1761             :                              int *got_frame_ptr, AVPacket *avpkt)
    1762             : {
    1763           0 :     XMADecodeCtx *s = avctx->priv_data;
    1764           0 :     int got_stream_frame_ptr = 0;
    1765           0 :     AVFrame *frame = data;
    1766           0 :     int i, ret, offset = INT_MAX;
    1767             : 
    1768             :     /* decode current stream packet */
    1769           0 :     ret = decode_packet(avctx, &s->xma[s->current_stream], s->frames[s->current_stream],
    1770             :                         &got_stream_frame_ptr, avpkt);
    1771             : 
    1772             :     /* copy stream samples (1/2ch) to sample buffer (Nch) */
    1773           0 :     if (got_stream_frame_ptr) {
    1774           0 :         int start_ch = s->start_channel[s->current_stream];
    1775           0 :         memcpy(&s->samples[start_ch + 0][s->offset[s->current_stream] * 512],
    1776           0 :                s->frames[s->current_stream]->extended_data[0], 512 * 4);
    1777           0 :         if (s->xma[s->current_stream].nb_channels > 1)
    1778           0 :             memcpy(&s->samples[start_ch + 1][s->offset[s->current_stream] * 512],
    1779           0 :                    s->frames[s->current_stream]->extended_data[1], 512 * 4);
    1780           0 :         s->offset[s->current_stream]++;
    1781           0 :     } else if (ret < 0) {
    1782           0 :         memset(s->offset, 0, sizeof(s->offset));
    1783           0 :         s->current_stream = 0;
    1784           0 :         return ret;
    1785             :     }
    1786             : 
    1787             :     /* find next XMA packet's owner stream, and update.
    1788             :      * XMA streams find their packets following packet_skips
    1789             :      * (at start there is one packet per stream, then interleave non-linearly). */
    1790           0 :     if (s->xma[s->current_stream].packet_done ||
    1791           0 :         s->xma[s->current_stream].packet_loss) {
    1792             : 
    1793             :         /* select stream with 0 skip_packets (= uses next packet) */
    1794           0 :         if (s->xma[s->current_stream].skip_packets != 0) {
    1795             :             int min[2];
    1796             : 
    1797           0 :             min[0] = s->xma[0].skip_packets;
    1798           0 :             min[1] = i = 0;
    1799             : 
    1800           0 :             for (i = 1; i < s->num_streams; i++) {
    1801           0 :                 if (s->xma[i].skip_packets < min[0]) {
    1802           0 :                     min[0] = s->xma[i].skip_packets;
    1803           0 :                     min[1] = i;
    1804             :                 }
    1805             :             }
    1806             : 
    1807           0 :             s->current_stream = min[1];
    1808             :         }
    1809             : 
    1810             :         /* all other streams skip next packet */
    1811           0 :         for (i = 0; i < s->num_streams; i++) {
    1812           0 :             s->xma[i].skip_packets = FFMAX(0, s->xma[i].skip_packets - 1);
    1813             :         }
    1814             : 
    1815             :         /* copy samples from buffer to output if possible */
    1816           0 :         for (i = 0; i < s->num_streams; i++) {
    1817           0 :             offset = FFMIN(offset, s->offset[i]);
    1818             :         }
    1819           0 :         if (offset > 0) {
    1820             :             int bret;
    1821             : 
    1822           0 :             frame->nb_samples = 512 * offset;
    1823           0 :             if ((bret = ff_get_buffer(avctx, frame, 0)) < 0)
    1824           0 :                 return bret;
    1825             : 
    1826             :             /* copy samples buffer (Nch) to frame samples (Nch), move unconsumed samples */
    1827           0 :             for (i = 0; i < s->num_streams; i++) {
    1828           0 :                 int start_ch = s->start_channel[i];
    1829           0 :                 memcpy(frame->extended_data[start_ch + 0], s->samples[start_ch + 0], frame->nb_samples * 4);
    1830           0 :                 if (s->xma[i].nb_channels > 1)
    1831           0 :                     memcpy(frame->extended_data[start_ch + 1], s->samples[start_ch + 1], frame->nb_samples * 4);
    1832             : 
    1833           0 :                 s->offset[i] -= offset;
    1834           0 :                 if (s->offset[i]) {
    1835           0 :                     memmove(s->samples[start_ch + 0], s->samples[start_ch + 0] + frame->nb_samples, s->offset[i] * 4 * 512);
    1836           0 :                     if (s->xma[i].nb_channels > 1)
    1837           0 :                         memmove(s->samples[start_ch + 1], s->samples[start_ch + 1] + frame->nb_samples, s->offset[i] * 4 * 512);
    1838             :                 }
    1839             :             }
    1840             : 
    1841           0 :             *got_frame_ptr = 1;
    1842             :         }
    1843             :     }
    1844             : 
    1845           0 :     return ret;
    1846             : }
    1847             : 
    1848           0 : static av_cold int xma_decode_init(AVCodecContext *avctx)
    1849             : {
    1850           0 :     XMADecodeCtx *s = avctx->priv_data;
    1851           0 :     int i, ret, start_channels = 0;
    1852             : 
    1853           0 :     if (avctx->channels <= 0 || avctx->extradata_size == 0)
    1854           0 :         return AVERROR_INVALIDDATA;
    1855             : 
    1856             :     /* get stream config */
    1857           0 :     if (avctx->codec_id == AV_CODEC_ID_XMA2 && avctx->extradata_size == 34) { /* XMA2WAVEFORMATEX */
    1858           0 :         s->num_streams = (avctx->channels + 1) / 2;
    1859           0 :     } else if (avctx->codec_id == AV_CODEC_ID_XMA2 && avctx->extradata_size >= 2) { /* XMA2WAVEFORMAT */
    1860           0 :         s->num_streams = avctx->extradata[1];
    1861           0 :         if (avctx->extradata_size != (32 + ((avctx->extradata[0]==3)?0:8) + 4*s->num_streams)) {
    1862           0 :             av_log(avctx, AV_LOG_ERROR, "Incorrect XMA2 extradata size\n");
    1863           0 :             return AVERROR(EINVAL);
    1864             :         }
    1865           0 :     } else if (avctx->codec_id == AV_CODEC_ID_XMA1 && avctx->extradata_size >= 4) { /* XMAWAVEFORMAT */
    1866           0 :         s->num_streams = avctx->extradata[4];
    1867           0 :         if (avctx->extradata_size != (8 + 20*s->num_streams)) {
    1868           0 :             av_log(avctx, AV_LOG_ERROR, "Incorrect XMA1 extradata size\n");
    1869           0 :             return AVERROR(EINVAL);
    1870             :         }
    1871             :     } else {
    1872           0 :         av_log(avctx, AV_LOG_ERROR, "Incorrect XMA config\n");
    1873           0 :         return AVERROR(EINVAL);
    1874             :     }
    1875             : 
    1876             :     /* encoder supports up to 64 streams / 64*2 channels (would have to alloc arrays) */
    1877           0 :     if (avctx->channels > XMA_MAX_CHANNELS || s->num_streams > XMA_MAX_STREAMS) {
    1878           0 :         avpriv_request_sample(avctx, "More than %d channels in %d streams", XMA_MAX_CHANNELS, s->num_streams);
    1879           0 :         return AVERROR_PATCHWELCOME;
    1880             :     }
    1881             : 
    1882             :     /* init all streams (several streams of 1/2ch make Nch files) */
    1883           0 :     for (i = 0; i < s->num_streams; i++) {
    1884           0 :         ret = decode_init(&s->xma[i], avctx, i);
    1885           0 :         if (ret < 0)
    1886           0 :             return ret;
    1887           0 :         s->frames[i] = av_frame_alloc();
    1888           0 :         if (!s->frames[i])
    1889           0 :             return AVERROR(ENOMEM);
    1890           0 :         s->frames[i]->nb_samples = 512;
    1891           0 :         if ((ret = ff_get_buffer(avctx, s->frames[i], 0)) < 0) {
    1892           0 :             return AVERROR(ENOMEM);
    1893             :         }
    1894             : 
    1895           0 :         s->start_channel[i] = start_channels;
    1896           0 :         start_channels += s->xma[i].nb_channels;
    1897             :     }
    1898             : 
    1899           0 :     return ret;
    1900             : }
    1901             : 
    1902           0 : static av_cold int xma_decode_end(AVCodecContext *avctx)
    1903             : {
    1904           0 :     XMADecodeCtx *s = avctx->priv_data;
    1905             :     int i;
    1906             : 
    1907           0 :     for (i = 0; i < s->num_streams; i++) {
    1908           0 :         decode_end(&s->xma[i]);
    1909           0 :         av_frame_free(&s->frames[i]);
    1910             :     }
    1911             : 
    1912           0 :     return 0;
    1913             : }
    1914             : 
    1915           0 : static void flush(WMAProDecodeCtx *s)
    1916             : {
    1917             :     int i;
    1918             :     /** reset output buffer as a part of it is used during the windowing of a
    1919             :         new frame */
    1920           0 :     for (i = 0; i < s->nb_channels; i++)
    1921           0 :         memset(s->channel[i].out, 0, s->samples_per_frame *
    1922             :                sizeof(*s->channel[i].out));
    1923           0 :     s->packet_loss = 1;
    1924           0 :     s->skip_packets = 0;
    1925           0 : }
    1926             : 
    1927             : 
    1928             : /**
    1929             :  *@brief Clear decoder buffers (for seeking).
    1930             :  *@param avctx codec context
    1931             :  */
    1932           0 : static void wmapro_flush(AVCodecContext *avctx)
    1933             : {
    1934           0 :     WMAProDecodeCtx *s = avctx->priv_data;
    1935             : 
    1936           0 :     flush(s);
    1937           0 : }
    1938             : 
    1939           0 : static void xma_flush(AVCodecContext *avctx)
    1940             : {
    1941           0 :     XMADecodeCtx *s = avctx->priv_data;
    1942             :     int i;
    1943             : 
    1944           0 :     for (i = 0; i < s->num_streams; i++)
    1945           0 :         flush(&s->xma[i]);
    1946             : 
    1947           0 :     memset(s->offset, 0, sizeof(s->offset));
    1948           0 :     s->current_stream = 0;
    1949           0 : }
    1950             : 
    1951             : 
    1952             : /**
    1953             :  *@brief wmapro decoder
    1954             :  */
    1955             : AVCodec ff_wmapro_decoder = {
    1956             :     .name           = "wmapro",
    1957             :     .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Audio 9 Professional"),
    1958             :     .type           = AVMEDIA_TYPE_AUDIO,
    1959             :     .id             = AV_CODEC_ID_WMAPRO,
    1960             :     .priv_data_size = sizeof(WMAProDecodeCtx),
    1961             :     .init           = wmapro_decode_init,
    1962             :     .close          = wmapro_decode_end,
    1963             :     .decode         = wmapro_decode_packet,
    1964             :     .capabilities   = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DR1,
    1965             :     .flush          = wmapro_flush,
    1966             :     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
    1967             :                                                       AV_SAMPLE_FMT_NONE },
    1968             : };
    1969             : 
    1970             : AVCodec ff_xma1_decoder = {
    1971             :     .name           = "xma1",
    1972             :     .long_name      = NULL_IF_CONFIG_SMALL("Xbox Media Audio 1"),
    1973             :     .type           = AVMEDIA_TYPE_AUDIO,
    1974             :     .id             = AV_CODEC_ID_XMA1,
    1975             :     .priv_data_size = sizeof(XMADecodeCtx),
    1976             :     .init           = xma_decode_init,
    1977             :     .close          = xma_decode_end,
    1978             :     .decode         = xma_decode_packet,
    1979             :     .capabilities   = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DR1,
    1980             :     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
    1981             :                                                       AV_SAMPLE_FMT_NONE },
    1982             : };
    1983             : 
    1984             : AVCodec ff_xma2_decoder = {
    1985             :     .name           = "xma2",
    1986             :     .long_name      = NULL_IF_CONFIG_SMALL("Xbox Media Audio 2"),
    1987             :     .type           = AVMEDIA_TYPE_AUDIO,
    1988             :     .id             = AV_CODEC_ID_XMA2,
    1989             :     .priv_data_size = sizeof(XMADecodeCtx),
    1990             :     .init           = xma_decode_init,
    1991             :     .close          = xma_decode_end,
    1992             :     .decode         = xma_decode_packet,
    1993             :     .flush          = xma_flush,
    1994             :     .capabilities   = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DR1,
    1995             :     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
    1996             :                                                       AV_SAMPLE_FMT_NONE },
    1997             : };

Generated by: LCOV version 1.13