You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1926 lines
73KB

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