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.

2027 lines
77KB

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