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.

1619 lines
63KB

  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 "avcodec.h"
  88. #include "internal.h"
  89. #include "get_bits.h"
  90. #include "put_bits.h"
  91. #include "wmaprodata.h"
  92. #include "dsputil.h"
  93. #include "wma.h"
  94. /** current decoder limitations */
  95. #define WMAPRO_MAX_CHANNELS 8 ///< max number of handled channels
  96. #define MAX_SUBFRAMES 32 ///< max number of subframes per channel
  97. #define MAX_BANDS 29 ///< max number of scale factor bands
  98. #define MAX_FRAMESIZE 32768 ///< maximum compressed frame size
  99. #define WMAPRO_BLOCK_MIN_BITS 6 ///< log2 of min block size
  100. #define WMAPRO_BLOCK_MAX_BITS 12 ///< log2 of max block size
  101. #define WMAPRO_BLOCK_MAX_SIZE (1 << WMAPRO_BLOCK_MAX_BITS) ///< maximum block size
  102. #define WMAPRO_BLOCK_SIZES (WMAPRO_BLOCK_MAX_BITS - WMAPRO_BLOCK_MIN_BITS + 1) ///< possible block sizes
  103. #define VLCBITS 9
  104. #define SCALEVLCBITS 8
  105. #define VEC4MAXDEPTH ((HUFF_VEC4_MAXBITS+VLCBITS-1)/VLCBITS)
  106. #define VEC2MAXDEPTH ((HUFF_VEC2_MAXBITS+VLCBITS-1)/VLCBITS)
  107. #define VEC1MAXDEPTH ((HUFF_VEC1_MAXBITS+VLCBITS-1)/VLCBITS)
  108. #define SCALEMAXDEPTH ((HUFF_SCALE_MAXBITS+SCALEVLCBITS-1)/SCALEVLCBITS)
  109. #define SCALERLMAXDEPTH ((HUFF_SCALE_RL_MAXBITS+VLCBITS-1)/VLCBITS)
  110. static VLC sf_vlc; ///< scale factor DPCM vlc
  111. static VLC sf_rl_vlc; ///< scale factor run length vlc
  112. static VLC vec4_vlc; ///< 4 coefficients per symbol
  113. static VLC vec2_vlc; ///< 2 coefficients per symbol
  114. static VLC vec1_vlc; ///< 1 coefficient per symbol
  115. static VLC coef_vlc[2]; ///< coefficient run length vlc codes
  116. static float sin64[33]; ///< sinus table for decorrelation
  117. /**
  118. * @brief frame specific decoder context for a single channel
  119. */
  120. typedef struct {
  121. int16_t prev_block_len; ///< length of the previous block
  122. uint8_t transmit_coefs;
  123. uint8_t num_subframes;
  124. uint16_t subframe_len[MAX_SUBFRAMES]; ///< subframe length in samples
  125. uint16_t subframe_offset[MAX_SUBFRAMES]; ///< subframe positions in the current frame
  126. uint8_t cur_subframe; ///< current subframe number
  127. uint16_t decoded_samples; ///< number of already processed samples
  128. uint8_t grouped; ///< channel is part of a group
  129. int quant_step; ///< quantization step for the current subframe
  130. int8_t reuse_sf; ///< share scale factors between subframes
  131. int8_t scale_factor_step; ///< scaling step for the current subframe
  132. int max_scale_factor; ///< maximum scale factor for the current subframe
  133. int saved_scale_factors[2][MAX_BANDS]; ///< resampled and (previously) transmitted scale factor values
  134. int8_t scale_factor_idx; ///< index for the transmitted scale factor values (used for resampling)
  135. int* scale_factors; ///< pointer to the scale factor values used for decoding
  136. uint8_t table_idx; ///< index in sf_offsets for the scale factor reference block
  137. float* coeffs; ///< pointer to the subframe decode buffer
  138. uint16_t num_vec_coeffs; ///< number of vector coded coefficients
  139. DECLARE_ALIGNED(16, float, out)[WMAPRO_BLOCK_MAX_SIZE + WMAPRO_BLOCK_MAX_SIZE / 2]; ///< output buffer
  140. } WMAProChannelCtx;
  141. /**
  142. * @brief channel group for channel transformations
  143. */
  144. typedef struct {
  145. uint8_t num_channels; ///< number of channels in the group
  146. int8_t transform; ///< transform on / off
  147. int8_t transform_band[MAX_BANDS]; ///< controls if the transform is enabled for a certain band
  148. float decorrelation_matrix[WMAPRO_MAX_CHANNELS*WMAPRO_MAX_CHANNELS];
  149. float* channel_data[WMAPRO_MAX_CHANNELS]; ///< transformation coefficients
  150. } WMAProChannelGrp;
  151. /**
  152. * @brief main decoder context
  153. */
  154. typedef struct WMAProDecodeCtx {
  155. /* generic decoder variables */
  156. AVCodecContext* avctx; ///< codec context for av_log
  157. DSPContext dsp; ///< accelerated DSP functions
  158. uint8_t frame_data[MAX_FRAMESIZE +
  159. FF_INPUT_BUFFER_PADDING_SIZE];///< compressed frame data
  160. PutBitContext pb; ///< context for filling the frame_data buffer
  161. FFTContext mdct_ctx[WMAPRO_BLOCK_SIZES]; ///< MDCT context per block size
  162. DECLARE_ALIGNED(16, float, tmp)[WMAPRO_BLOCK_MAX_SIZE]; ///< IMDCT output buffer
  163. float* windows[WMAPRO_BLOCK_SIZES]; ///< windows for the different block sizes
  164. /* frame size dependent frame information (set during initialization) */
  165. uint32_t decode_flags; ///< used compression features
  166. uint8_t len_prefix; ///< frame is prefixed with its length
  167. uint8_t dynamic_range_compression; ///< frame contains DRC data
  168. uint8_t bits_per_sample; ///< integer audio sample size for the unscaled IMDCT output (used to scale to [-1.0, 1.0])
  169. uint16_t samples_per_frame; ///< number of samples to output
  170. uint16_t log2_frame_size;
  171. int8_t num_channels; ///< number of channels in the stream (same as AVCodecContext.num_channels)
  172. int8_t lfe_channel; ///< lfe channel index
  173. uint8_t max_num_subframes;
  174. uint8_t subframe_len_bits; ///< number of bits used for the subframe length
  175. uint8_t max_subframe_len_bit; ///< flag indicating that the subframe is of maximum size when the first subframe length bit is 1
  176. uint16_t min_samples_per_subframe;
  177. int8_t num_sfb[WMAPRO_BLOCK_SIZES]; ///< scale factor bands per block size
  178. int16_t sfb_offsets[WMAPRO_BLOCK_SIZES][MAX_BANDS]; ///< scale factor band offsets (multiples of 4)
  179. int8_t sf_offsets[WMAPRO_BLOCK_SIZES][WMAPRO_BLOCK_SIZES][MAX_BANDS]; ///< scale factor resample matrix
  180. int16_t subwoofer_cutoffs[WMAPRO_BLOCK_SIZES]; ///< subwoofer cutoff values
  181. /* packet decode state */
  182. GetBitContext pgb; ///< bitstream reader context for the packet
  183. int next_packet_start; ///< start offset of the next wma packet in the demuxer packet
  184. uint8_t packet_offset; ///< frame offset in the packet
  185. uint8_t packet_sequence_number; ///< current packet number
  186. int num_saved_bits; ///< saved number of bits
  187. int frame_offset; ///< frame offset in the bit reservoir
  188. int subframe_offset; ///< subframe offset in the bit reservoir
  189. uint8_t packet_loss; ///< set in case of bitstream error
  190. uint8_t packet_done; ///< set when a packet is fully decoded
  191. /* frame decode state */
  192. uint32_t frame_num; ///< current frame number (not used for decoding)
  193. GetBitContext gb; ///< bitstream reader context
  194. int buf_bit_size; ///< buffer size in bits
  195. float* samples; ///< current samplebuffer pointer
  196. float* samples_end; ///< maximum samplebuffer pointer
  197. uint8_t drc_gain; ///< gain for the DRC tool
  198. int8_t skip_frame; ///< skip output step
  199. int8_t parsed_all_subframes; ///< all subframes decoded?
  200. /* subframe/block decode state */
  201. int16_t subframe_len; ///< current subframe length
  202. int8_t channels_for_cur_subframe; ///< number of channels that contain the subframe
  203. int8_t channel_indexes_for_cur_subframe[WMAPRO_MAX_CHANNELS];
  204. int8_t num_bands; ///< number of scale factor bands
  205. int8_t transmit_num_vec_coeffs; ///< number of vector coded coefficients is part of the bitstream
  206. int16_t* cur_sfb_offsets; ///< sfb offsets for the current block
  207. uint8_t table_idx; ///< index for the num_sfb, sfb_offsets, sf_offsets and subwoofer_cutoffs tables
  208. int8_t esc_len; ///< length of escaped coefficients
  209. uint8_t num_chgroups; ///< number of channel groups
  210. WMAProChannelGrp chgroup[WMAPRO_MAX_CHANNELS]; ///< channel group information
  211. WMAProChannelCtx channel[WMAPRO_MAX_CHANNELS]; ///< per channel data
  212. } WMAProDecodeCtx;
  213. /**
  214. *@brief helper function to print the most important members of the context
  215. *@param s context
  216. */
  217. static void av_cold dump_context(WMAProDecodeCtx *s)
  218. {
  219. #define PRINT(a, b) av_log(s->avctx, AV_LOG_DEBUG, " %s = %d\n", a, b);
  220. #define PRINT_HEX(a, b) av_log(s->avctx, AV_LOG_DEBUG, " %s = %x\n", a, b);
  221. PRINT("ed sample bit depth", s->bits_per_sample);
  222. PRINT_HEX("ed decode flags", s->decode_flags);
  223. PRINT("samples per frame", s->samples_per_frame);
  224. PRINT("log2 frame size", s->log2_frame_size);
  225. PRINT("max num subframes", s->max_num_subframes);
  226. PRINT("len prefix", s->len_prefix);
  227. PRINT("num channels", s->num_channels);
  228. }
  229. /**
  230. *@brief Uninitialize the decoder and free all resources.
  231. *@param avctx codec context
  232. *@return 0 on success, < 0 otherwise
  233. */
  234. static av_cold int decode_end(AVCodecContext *avctx)
  235. {
  236. WMAProDecodeCtx *s = avctx->priv_data;
  237. int i;
  238. for (i = 0; i < WMAPRO_BLOCK_SIZES; i++)
  239. ff_mdct_end(&s->mdct_ctx[i]);
  240. return 0;
  241. }
  242. /**
  243. *@brief Initialize the decoder.
  244. *@param avctx codec context
  245. *@return 0 on success, -1 otherwise
  246. */
  247. static av_cold int decode_init(AVCodecContext *avctx)
  248. {
  249. WMAProDecodeCtx *s = avctx->priv_data;
  250. uint8_t *edata_ptr = avctx->extradata;
  251. unsigned int channel_mask;
  252. int i;
  253. int log2_max_num_subframes;
  254. int num_possible_block_sizes;
  255. s->avctx = avctx;
  256. dsputil_init(&s->dsp, avctx);
  257. init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
  258. avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
  259. if (avctx->extradata_size >= 18) {
  260. s->decode_flags = AV_RL16(edata_ptr+14);
  261. channel_mask = AV_RL32(edata_ptr+2);
  262. s->bits_per_sample = AV_RL16(edata_ptr);
  263. /** dump the extradata */
  264. for (i = 0; i < avctx->extradata_size; i++)
  265. av_dlog(avctx, "[%x] ", avctx->extradata[i]);
  266. av_dlog(avctx, "\n");
  267. } else {
  268. av_log_ask_for_sample(avctx, "Unknown extradata size\n");
  269. return AVERROR_INVALIDDATA;
  270. }
  271. /** generic init */
  272. s->log2_frame_size = av_log2(avctx->block_align) + 4;
  273. /** frame info */
  274. s->skip_frame = 1; /* skip first frame */
  275. s->packet_loss = 1;
  276. s->len_prefix = (s->decode_flags & 0x40);
  277. /** get frame len */
  278. s->samples_per_frame = 1 << ff_wma_get_frame_len_bits(avctx->sample_rate,
  279. 3, s->decode_flags);
  280. /** init previous block len */
  281. for (i = 0; i < avctx->channels; i++)
  282. s->channel[i].prev_block_len = s->samples_per_frame;
  283. /** subframe info */
  284. log2_max_num_subframes = ((s->decode_flags & 0x38) >> 3);
  285. s->max_num_subframes = 1 << log2_max_num_subframes;
  286. if (s->max_num_subframes == 16 || s->max_num_subframes == 4)
  287. s->max_subframe_len_bit = 1;
  288. s->subframe_len_bits = av_log2(log2_max_num_subframes) + 1;
  289. num_possible_block_sizes = log2_max_num_subframes + 1;
  290. s->min_samples_per_subframe = s->samples_per_frame / s->max_num_subframes;
  291. s->dynamic_range_compression = (s->decode_flags & 0x80);
  292. if (s->max_num_subframes > MAX_SUBFRAMES) {
  293. av_log(avctx, AV_LOG_ERROR, "invalid number of subframes %i\n",
  294. s->max_num_subframes);
  295. return AVERROR_INVALIDDATA;
  296. }
  297. s->num_channels = avctx->channels;
  298. /** extract lfe channel position */
  299. s->lfe_channel = -1;
  300. if (channel_mask & 8) {
  301. unsigned int mask;
  302. for (mask = 1; mask < 16; mask <<= 1) {
  303. if (channel_mask & mask)
  304. ++s->lfe_channel;
  305. }
  306. }
  307. if (s->num_channels < 0) {
  308. av_log(avctx, AV_LOG_ERROR, "invalid number of channels %d\n", s->num_channels);
  309. return AVERROR_INVALIDDATA;
  310. } else if (s->num_channels > WMAPRO_MAX_CHANNELS) {
  311. av_log_ask_for_sample(avctx, "unsupported number of channels\n");
  312. return AVERROR_PATCHWELCOME;
  313. }
  314. INIT_VLC_STATIC(&sf_vlc, SCALEVLCBITS, HUFF_SCALE_SIZE,
  315. scale_huffbits, 1, 1,
  316. scale_huffcodes, 2, 2, 616);
  317. INIT_VLC_STATIC(&sf_rl_vlc, VLCBITS, HUFF_SCALE_RL_SIZE,
  318. scale_rl_huffbits, 1, 1,
  319. scale_rl_huffcodes, 4, 4, 1406);
  320. INIT_VLC_STATIC(&coef_vlc[0], VLCBITS, HUFF_COEF0_SIZE,
  321. coef0_huffbits, 1, 1,
  322. coef0_huffcodes, 4, 4, 2108);
  323. INIT_VLC_STATIC(&coef_vlc[1], VLCBITS, HUFF_COEF1_SIZE,
  324. coef1_huffbits, 1, 1,
  325. coef1_huffcodes, 4, 4, 3912);
  326. INIT_VLC_STATIC(&vec4_vlc, VLCBITS, HUFF_VEC4_SIZE,
  327. vec4_huffbits, 1, 1,
  328. vec4_huffcodes, 2, 2, 604);
  329. INIT_VLC_STATIC(&vec2_vlc, VLCBITS, HUFF_VEC2_SIZE,
  330. vec2_huffbits, 1, 1,
  331. vec2_huffcodes, 2, 2, 562);
  332. INIT_VLC_STATIC(&vec1_vlc, VLCBITS, HUFF_VEC1_SIZE,
  333. vec1_huffbits, 1, 1,
  334. vec1_huffcodes, 2, 2, 562);
  335. /** calculate number of scale factor bands and their offsets
  336. for every possible block size */
  337. for (i = 0; i < num_possible_block_sizes; i++) {
  338. int subframe_len = s->samples_per_frame >> i;
  339. int x;
  340. int band = 1;
  341. s->sfb_offsets[i][0] = 0;
  342. for (x = 0; x < MAX_BANDS-1 && s->sfb_offsets[i][band - 1] < subframe_len; x++) {
  343. int offset = (subframe_len * 2 * critical_freq[x])
  344. / s->avctx->sample_rate + 2;
  345. offset &= ~3;
  346. if (offset > s->sfb_offsets[i][band - 1])
  347. s->sfb_offsets[i][band++] = offset;
  348. }
  349. s->sfb_offsets[i][band - 1] = subframe_len;
  350. s->num_sfb[i] = band - 1;
  351. }
  352. /** Scale factors can be shared between blocks of different size
  353. as every block has a different scale factor band layout.
  354. The matrix sf_offsets is needed to find the correct scale factor.
  355. */
  356. for (i = 0; i < num_possible_block_sizes; i++) {
  357. int b;
  358. for (b = 0; b < s->num_sfb[i]; b++) {
  359. int x;
  360. int offset = ((s->sfb_offsets[i][b]
  361. + s->sfb_offsets[i][b + 1] - 1) << i) >> 1;
  362. for (x = 0; x < num_possible_block_sizes; x++) {
  363. int v = 0;
  364. while (s->sfb_offsets[x][v + 1] << x < offset)
  365. ++v;
  366. s->sf_offsets[i][x][b] = v;
  367. }
  368. }
  369. }
  370. /** init MDCT, FIXME: only init needed sizes */
  371. for (i = 0; i < WMAPRO_BLOCK_SIZES; i++)
  372. ff_mdct_init(&s->mdct_ctx[i], WMAPRO_BLOCK_MIN_BITS+1+i, 1,
  373. 1.0 / (1 << (WMAPRO_BLOCK_MIN_BITS + i - 1))
  374. / (1 << (s->bits_per_sample - 1)));
  375. /** init MDCT windows: simple sinus window */
  376. for (i = 0; i < WMAPRO_BLOCK_SIZES; i++) {
  377. const int win_idx = WMAPRO_BLOCK_MAX_BITS - i;
  378. ff_init_ff_sine_windows(win_idx);
  379. s->windows[WMAPRO_BLOCK_SIZES - i - 1] = ff_sine_windows[win_idx];
  380. }
  381. /** calculate subwoofer cutoff values */
  382. for (i = 0; i < num_possible_block_sizes; i++) {
  383. int block_size = s->samples_per_frame >> i;
  384. int cutoff = (440*block_size + 3 * (s->avctx->sample_rate >> 1) - 1)
  385. / s->avctx->sample_rate;
  386. s->subwoofer_cutoffs[i] = av_clip(cutoff, 4, block_size);
  387. }
  388. /** calculate sine values for the decorrelation matrix */
  389. for (i = 0; i < 33; i++)
  390. sin64[i] = sin(i*M_PI / 64.0);
  391. if (avctx->debug & FF_DEBUG_BITSTREAM)
  392. dump_context(s);
  393. avctx->channel_layout = channel_mask;
  394. return 0;
  395. }
  396. /**
  397. *@brief Decode the subframe length.
  398. *@param s context
  399. *@param offset sample offset in the frame
  400. *@return decoded subframe length on success, < 0 in case of an error
  401. */
  402. static int decode_subframe_length(WMAProDecodeCtx *s, int offset)
  403. {
  404. int frame_len_shift = 0;
  405. int subframe_len;
  406. /** no need to read from the bitstream when only one length is possible */
  407. if (offset == s->samples_per_frame - s->min_samples_per_subframe)
  408. return s->min_samples_per_subframe;
  409. /** 1 bit indicates if the subframe is of maximum length */
  410. if (s->max_subframe_len_bit) {
  411. if (get_bits1(&s->gb))
  412. frame_len_shift = 1 + get_bits(&s->gb, s->subframe_len_bits-1);
  413. } else
  414. frame_len_shift = get_bits(&s->gb, s->subframe_len_bits);
  415. subframe_len = s->samples_per_frame >> frame_len_shift;
  416. /** sanity check the length */
  417. if (subframe_len < s->min_samples_per_subframe ||
  418. subframe_len > s->samples_per_frame) {
  419. av_log(s->avctx, AV_LOG_ERROR, "broken frame: subframe_len %i\n",
  420. subframe_len);
  421. return AVERROR_INVALIDDATA;
  422. }
  423. return subframe_len;
  424. }
  425. /**
  426. *@brief Decode how the data in the frame is split into subframes.
  427. * Every WMA frame contains the encoded data for a fixed number of
  428. * samples per channel. The data for every channel might be split
  429. * into several subframes. This function will reconstruct the list of
  430. * subframes for every channel.
  431. *
  432. * If the subframes are not evenly split, the algorithm estimates the
  433. * channels with the lowest number of total samples.
  434. * Afterwards, for each of these channels a bit is read from the
  435. * bitstream that indicates if the channel contains a subframe with the
  436. * next subframe size that is going to be read from the bitstream or not.
  437. * If a channel contains such a subframe, the subframe size gets added to
  438. * the channel's subframe list.
  439. * The algorithm repeats these steps until the frame is properly divided
  440. * between the individual channels.
  441. *
  442. *@param s context
  443. *@return 0 on success, < 0 in case of an error
  444. */
  445. static int decode_tilehdr(WMAProDecodeCtx *s)
  446. {
  447. uint16_t num_samples[WMAPRO_MAX_CHANNELS]; /**< sum of samples for all currently known subframes of a channel */
  448. uint8_t contains_subframe[WMAPRO_MAX_CHANNELS]; /**< flag indicating if a channel contains the current subframe */
  449. int channels_for_cur_subframe = s->num_channels; /**< number of channels that contain the current subframe */
  450. int fixed_channel_layout = 0; /**< flag indicating that all channels use the same subframe offsets and sizes */
  451. int min_channel_len = 0; /**< smallest sum of samples (channels with this length will be processed first) */
  452. int c;
  453. /* Should never consume more than 3073 bits (256 iterations for the
  454. * while loop when always the minimum amount of 128 samples is substracted
  455. * from missing samples in the 8 channel case).
  456. * 1 + BLOCK_MAX_SIZE * MAX_CHANNELS / BLOCK_MIN_SIZE * (MAX_CHANNELS + 4)
  457. */
  458. /** reset tiling information */
  459. for (c = 0; c < s->num_channels; c++)
  460. s->channel[c].num_subframes = 0;
  461. memset(num_samples, 0, sizeof(num_samples));
  462. if (s->max_num_subframes == 1 || get_bits1(&s->gb))
  463. fixed_channel_layout = 1;
  464. /** loop until the frame data is split between the subframes */
  465. do {
  466. int subframe_len;
  467. /** check which channels contain the subframe */
  468. for (c = 0; c < s->num_channels; c++) {
  469. if (num_samples[c] == min_channel_len) {
  470. if (fixed_channel_layout || channels_for_cur_subframe == 1 ||
  471. (min_channel_len == s->samples_per_frame - s->min_samples_per_subframe))
  472. contains_subframe[c] = 1;
  473. else
  474. contains_subframe[c] = get_bits1(&s->gb);
  475. } else
  476. contains_subframe[c] = 0;
  477. }
  478. /** get subframe length, subframe_len == 0 is not allowed */
  479. if ((subframe_len = decode_subframe_length(s, min_channel_len)) <= 0)
  480. return AVERROR_INVALIDDATA;
  481. /** add subframes to the individual channels and find new min_channel_len */
  482. min_channel_len += subframe_len;
  483. for (c = 0; c < s->num_channels; c++) {
  484. WMAProChannelCtx* chan = &s->channel[c];
  485. if (contains_subframe[c]) {
  486. if (chan->num_subframes >= MAX_SUBFRAMES) {
  487. av_log(s->avctx, AV_LOG_ERROR,
  488. "broken frame: num subframes > 31\n");
  489. return AVERROR_INVALIDDATA;
  490. }
  491. chan->subframe_len[chan->num_subframes] = subframe_len;
  492. num_samples[c] += subframe_len;
  493. ++chan->num_subframes;
  494. if (num_samples[c] > s->samples_per_frame) {
  495. av_log(s->avctx, AV_LOG_ERROR, "broken frame: "
  496. "channel len > samples_per_frame\n");
  497. return AVERROR_INVALIDDATA;
  498. }
  499. } else if (num_samples[c] <= min_channel_len) {
  500. if (num_samples[c] < min_channel_len) {
  501. channels_for_cur_subframe = 0;
  502. min_channel_len = num_samples[c];
  503. }
  504. ++channels_for_cur_subframe;
  505. }
  506. }
  507. } while (min_channel_len < s->samples_per_frame);
  508. for (c = 0; c < s->num_channels; c++) {
  509. int i;
  510. int offset = 0;
  511. for (i = 0; i < s->channel[c].num_subframes; i++) {
  512. av_dlog(s->avctx, "frame[%i] channel[%i] subframe[%i]"
  513. " len %i\n", s->frame_num, c, i,
  514. s->channel[c].subframe_len[i]);
  515. s->channel[c].subframe_offset[i] = offset;
  516. offset += s->channel[c].subframe_len[i];
  517. }
  518. }
  519. return 0;
  520. }
  521. /**
  522. *@brief Calculate a decorrelation matrix from the bitstream parameters.
  523. *@param s codec context
  524. *@param chgroup channel group for which the matrix needs to be calculated
  525. */
  526. static void decode_decorrelation_matrix(WMAProDecodeCtx *s,
  527. WMAProChannelGrp *chgroup)
  528. {
  529. int i;
  530. int offset = 0;
  531. int8_t rotation_offset[WMAPRO_MAX_CHANNELS * WMAPRO_MAX_CHANNELS];
  532. memset(chgroup->decorrelation_matrix, 0, s->num_channels *
  533. s->num_channels * sizeof(*chgroup->decorrelation_matrix));
  534. for (i = 0; i < chgroup->num_channels * (chgroup->num_channels - 1) >> 1; i++)
  535. rotation_offset[i] = get_bits(&s->gb, 6);
  536. for (i = 0; i < chgroup->num_channels; i++)
  537. chgroup->decorrelation_matrix[chgroup->num_channels * i + i] =
  538. get_bits1(&s->gb) ? 1.0 : -1.0;
  539. for (i = 1; i < chgroup->num_channels; i++) {
  540. int x;
  541. for (x = 0; x < i; x++) {
  542. int y;
  543. for (y = 0; y < i + 1; y++) {
  544. float v1 = chgroup->decorrelation_matrix[x * chgroup->num_channels + y];
  545. float v2 = chgroup->decorrelation_matrix[i * chgroup->num_channels + y];
  546. int n = rotation_offset[offset + x];
  547. float sinv;
  548. float cosv;
  549. if (n < 32) {
  550. sinv = sin64[n];
  551. cosv = sin64[32 - n];
  552. } else {
  553. sinv = sin64[64 - n];
  554. cosv = -sin64[n - 32];
  555. }
  556. chgroup->decorrelation_matrix[y + x * chgroup->num_channels] =
  557. (v1 * sinv) - (v2 * cosv);
  558. chgroup->decorrelation_matrix[y + i * chgroup->num_channels] =
  559. (v1 * cosv) + (v2 * sinv);
  560. }
  561. }
  562. offset += i;
  563. }
  564. }
  565. /**
  566. *@brief Decode channel transformation parameters
  567. *@param s codec context
  568. *@return 0 in case of success, < 0 in case of bitstream errors
  569. */
  570. static int decode_channel_transform(WMAProDecodeCtx* s)
  571. {
  572. int i;
  573. /* should never consume more than 1921 bits for the 8 channel case
  574. * 1 + MAX_CHANNELS * (MAX_CHANNELS + 2 + 3 * MAX_CHANNELS * MAX_CHANNELS
  575. * + MAX_CHANNELS + MAX_BANDS + 1)
  576. */
  577. /** in the one channel case channel transforms are pointless */
  578. s->num_chgroups = 0;
  579. if (s->num_channels > 1) {
  580. int remaining_channels = s->channels_for_cur_subframe;
  581. if (get_bits1(&s->gb)) {
  582. av_log_ask_for_sample(s->avctx,
  583. "unsupported channel transform bit\n");
  584. return AVERROR_INVALIDDATA;
  585. }
  586. for (s->num_chgroups = 0; remaining_channels &&
  587. s->num_chgroups < s->channels_for_cur_subframe; s->num_chgroups++) {
  588. WMAProChannelGrp* chgroup = &s->chgroup[s->num_chgroups];
  589. float** channel_data = chgroup->channel_data;
  590. chgroup->num_channels = 0;
  591. chgroup->transform = 0;
  592. /** decode channel mask */
  593. if (remaining_channels > 2) {
  594. for (i = 0; i < s->channels_for_cur_subframe; i++) {
  595. int channel_idx = s->channel_indexes_for_cur_subframe[i];
  596. if (!s->channel[channel_idx].grouped
  597. && get_bits1(&s->gb)) {
  598. ++chgroup->num_channels;
  599. s->channel[channel_idx].grouped = 1;
  600. *channel_data++ = s->channel[channel_idx].coeffs;
  601. }
  602. }
  603. } else {
  604. chgroup->num_channels = remaining_channels;
  605. for (i = 0; i < s->channels_for_cur_subframe; i++) {
  606. int channel_idx = s->channel_indexes_for_cur_subframe[i];
  607. if (!s->channel[channel_idx].grouped)
  608. *channel_data++ = s->channel[channel_idx].coeffs;
  609. s->channel[channel_idx].grouped = 1;
  610. }
  611. }
  612. /** decode transform type */
  613. if (chgroup->num_channels == 2) {
  614. if (get_bits1(&s->gb)) {
  615. if (get_bits1(&s->gb)) {
  616. av_log_ask_for_sample(s->avctx,
  617. "unsupported channel transform type\n");
  618. }
  619. } else {
  620. chgroup->transform = 1;
  621. if (s->num_channels == 2) {
  622. chgroup->decorrelation_matrix[0] = 1.0;
  623. chgroup->decorrelation_matrix[1] = -1.0;
  624. chgroup->decorrelation_matrix[2] = 1.0;
  625. chgroup->decorrelation_matrix[3] = 1.0;
  626. } else {
  627. /** cos(pi/4) */
  628. chgroup->decorrelation_matrix[0] = 0.70703125;
  629. chgroup->decorrelation_matrix[1] = -0.70703125;
  630. chgroup->decorrelation_matrix[2] = 0.70703125;
  631. chgroup->decorrelation_matrix[3] = 0.70703125;
  632. }
  633. }
  634. } else if (chgroup->num_channels > 2) {
  635. if (get_bits1(&s->gb)) {
  636. chgroup->transform = 1;
  637. if (get_bits1(&s->gb)) {
  638. decode_decorrelation_matrix(s, chgroup);
  639. } else {
  640. /** FIXME: more than 6 coupled channels not supported */
  641. if (chgroup->num_channels > 6) {
  642. av_log_ask_for_sample(s->avctx,
  643. "coupled channels > 6\n");
  644. } else {
  645. memcpy(chgroup->decorrelation_matrix,
  646. default_decorrelation[chgroup->num_channels],
  647. chgroup->num_channels * chgroup->num_channels *
  648. sizeof(*chgroup->decorrelation_matrix));
  649. }
  650. }
  651. }
  652. }
  653. /** decode transform on / off */
  654. if (chgroup->transform) {
  655. if (!get_bits1(&s->gb)) {
  656. int i;
  657. /** transform can be enabled for individual bands */
  658. for (i = 0; i < s->num_bands; i++) {
  659. chgroup->transform_band[i] = get_bits1(&s->gb);
  660. }
  661. } else {
  662. memset(chgroup->transform_band, 1, s->num_bands);
  663. }
  664. }
  665. remaining_channels -= chgroup->num_channels;
  666. }
  667. }
  668. return 0;
  669. }
  670. /**
  671. *@brief Extract the coefficients from the bitstream.
  672. *@param s codec context
  673. *@param c current channel number
  674. *@return 0 on success, < 0 in case of bitstream errors
  675. */
  676. static int decode_coeffs(WMAProDecodeCtx *s, int c)
  677. {
  678. /* Integers 0..15 as single-precision floats. The table saves a
  679. costly int to float conversion, and storing the values as
  680. integers allows fast sign-flipping. */
  681. static const int fval_tab[16] = {
  682. 0x00000000, 0x3f800000, 0x40000000, 0x40400000,
  683. 0x40800000, 0x40a00000, 0x40c00000, 0x40e00000,
  684. 0x41000000, 0x41100000, 0x41200000, 0x41300000,
  685. 0x41400000, 0x41500000, 0x41600000, 0x41700000,
  686. };
  687. int vlctable;
  688. VLC* vlc;
  689. WMAProChannelCtx* ci = &s->channel[c];
  690. int rl_mode = 0;
  691. int cur_coeff = 0;
  692. int num_zeros = 0;
  693. const uint16_t* run;
  694. const float* level;
  695. av_dlog(s->avctx, "decode coefficients for channel %i\n", c);
  696. vlctable = get_bits1(&s->gb);
  697. vlc = &coef_vlc[vlctable];
  698. if (vlctable) {
  699. run = coef1_run;
  700. level = coef1_level;
  701. } else {
  702. run = coef0_run;
  703. level = coef0_level;
  704. }
  705. /** decode vector coefficients (consumes up to 167 bits per iteration for
  706. 4 vector coded large values) */
  707. while ((s->transmit_num_vec_coeffs || !rl_mode) &&
  708. (cur_coeff + 3 < ci->num_vec_coeffs)) {
  709. int vals[4];
  710. int i;
  711. unsigned int idx;
  712. idx = get_vlc2(&s->gb, vec4_vlc.table, VLCBITS, VEC4MAXDEPTH);
  713. if (idx == HUFF_VEC4_SIZE - 1) {
  714. for (i = 0; i < 4; i += 2) {
  715. idx = get_vlc2(&s->gb, vec2_vlc.table, VLCBITS, VEC2MAXDEPTH);
  716. if (idx == HUFF_VEC2_SIZE - 1) {
  717. int v0, v1;
  718. v0 = get_vlc2(&s->gb, vec1_vlc.table, VLCBITS, VEC1MAXDEPTH);
  719. if (v0 == HUFF_VEC1_SIZE - 1)
  720. v0 += ff_wma_get_large_val(&s->gb);
  721. v1 = get_vlc2(&s->gb, vec1_vlc.table, VLCBITS, VEC1MAXDEPTH);
  722. if (v1 == HUFF_VEC1_SIZE - 1)
  723. v1 += ff_wma_get_large_val(&s->gb);
  724. ((float*)vals)[i ] = v0;
  725. ((float*)vals)[i+1] = v1;
  726. } else {
  727. vals[i] = fval_tab[symbol_to_vec2[idx] >> 4 ];
  728. vals[i+1] = fval_tab[symbol_to_vec2[idx] & 0xF];
  729. }
  730. }
  731. } else {
  732. vals[0] = fval_tab[ symbol_to_vec4[idx] >> 12 ];
  733. vals[1] = fval_tab[(symbol_to_vec4[idx] >> 8) & 0xF];
  734. vals[2] = fval_tab[(symbol_to_vec4[idx] >> 4) & 0xF];
  735. vals[3] = fval_tab[ symbol_to_vec4[idx] & 0xF];
  736. }
  737. /** decode sign */
  738. for (i = 0; i < 4; i++) {
  739. if (vals[i]) {
  740. int sign = get_bits1(&s->gb) - 1;
  741. *(uint32_t*)&ci->coeffs[cur_coeff] = vals[i] ^ sign<<31;
  742. num_zeros = 0;
  743. } else {
  744. ci->coeffs[cur_coeff] = 0;
  745. /** switch to run level mode when subframe_len / 128 zeros
  746. were found in a row */
  747. rl_mode |= (++num_zeros > s->subframe_len >> 8);
  748. }
  749. ++cur_coeff;
  750. }
  751. }
  752. /** decode run level coded coefficients */
  753. if (cur_coeff < s->subframe_len) {
  754. memset(&ci->coeffs[cur_coeff], 0,
  755. sizeof(*ci->coeffs) * (s->subframe_len - cur_coeff));
  756. if (ff_wma_run_level_decode(s->avctx, &s->gb, vlc,
  757. level, run, 1, ci->coeffs,
  758. cur_coeff, s->subframe_len,
  759. s->subframe_len, s->esc_len, 0))
  760. return AVERROR_INVALIDDATA;
  761. }
  762. return 0;
  763. }
  764. /**
  765. *@brief Extract scale factors from the bitstream.
  766. *@param s codec context
  767. *@return 0 on success, < 0 in case of bitstream errors
  768. */
  769. static int decode_scale_factors(WMAProDecodeCtx* s)
  770. {
  771. int i;
  772. /** should never consume more than 5344 bits
  773. * MAX_CHANNELS * (1 + MAX_BANDS * 23)
  774. */
  775. for (i = 0; i < s->channels_for_cur_subframe; i++) {
  776. int c = s->channel_indexes_for_cur_subframe[i];
  777. int* sf;
  778. int* sf_end;
  779. s->channel[c].scale_factors = s->channel[c].saved_scale_factors[!s->channel[c].scale_factor_idx];
  780. sf_end = s->channel[c].scale_factors + s->num_bands;
  781. /** resample scale factors for the new block size
  782. * as the scale factors might need to be resampled several times
  783. * before some new values are transmitted, a backup of the last
  784. * transmitted scale factors is kept in saved_scale_factors
  785. */
  786. if (s->channel[c].reuse_sf) {
  787. const int8_t* sf_offsets = s->sf_offsets[s->table_idx][s->channel[c].table_idx];
  788. int b;
  789. for (b = 0; b < s->num_bands; b++)
  790. s->channel[c].scale_factors[b] =
  791. s->channel[c].saved_scale_factors[s->channel[c].scale_factor_idx][*sf_offsets++];
  792. }
  793. if (!s->channel[c].cur_subframe || get_bits1(&s->gb)) {
  794. if (!s->channel[c].reuse_sf) {
  795. int val;
  796. /** decode DPCM coded scale factors */
  797. s->channel[c].scale_factor_step = get_bits(&s->gb, 2) + 1;
  798. val = 45 / s->channel[c].scale_factor_step;
  799. for (sf = s->channel[c].scale_factors; sf < sf_end; sf++) {
  800. val += get_vlc2(&s->gb, sf_vlc.table, SCALEVLCBITS, SCALEMAXDEPTH) - 60;
  801. *sf = val;
  802. }
  803. } else {
  804. int i;
  805. /** run level decode differences to the resampled factors */
  806. for (i = 0; i < s->num_bands; i++) {
  807. int idx;
  808. int skip;
  809. int val;
  810. int sign;
  811. idx = get_vlc2(&s->gb, sf_rl_vlc.table, VLCBITS, SCALERLMAXDEPTH);
  812. if (!idx) {
  813. uint32_t code = get_bits(&s->gb, 14);
  814. val = code >> 6;
  815. sign = (code & 1) - 1;
  816. skip = (code & 0x3f) >> 1;
  817. } else if (idx == 1) {
  818. break;
  819. } else {
  820. skip = scale_rl_run[idx];
  821. val = scale_rl_level[idx];
  822. sign = get_bits1(&s->gb)-1;
  823. }
  824. i += skip;
  825. if (i >= s->num_bands) {
  826. av_log(s->avctx, AV_LOG_ERROR,
  827. "invalid scale factor coding\n");
  828. return AVERROR_INVALIDDATA;
  829. }
  830. s->channel[c].scale_factors[i] += (val ^ sign) - sign;
  831. }
  832. }
  833. /** swap buffers */
  834. s->channel[c].scale_factor_idx = !s->channel[c].scale_factor_idx;
  835. s->channel[c].table_idx = s->table_idx;
  836. s->channel[c].reuse_sf = 1;
  837. }
  838. /** calculate new scale factor maximum */
  839. s->channel[c].max_scale_factor = s->channel[c].scale_factors[0];
  840. for (sf = s->channel[c].scale_factors + 1; sf < sf_end; sf++) {
  841. s->channel[c].max_scale_factor =
  842. FFMAX(s->channel[c].max_scale_factor, *sf);
  843. }
  844. }
  845. return 0;
  846. }
  847. /**
  848. *@brief Reconstruct the individual channel data.
  849. *@param s codec context
  850. */
  851. static void inverse_channel_transform(WMAProDecodeCtx *s)
  852. {
  853. int i;
  854. for (i = 0; i < s->num_chgroups; i++) {
  855. if (s->chgroup[i].transform) {
  856. float data[WMAPRO_MAX_CHANNELS];
  857. const int num_channels = s->chgroup[i].num_channels;
  858. float** ch_data = s->chgroup[i].channel_data;
  859. float** ch_end = ch_data + num_channels;
  860. const int8_t* tb = s->chgroup[i].transform_band;
  861. int16_t* sfb;
  862. /** multichannel decorrelation */
  863. for (sfb = s->cur_sfb_offsets;
  864. sfb < s->cur_sfb_offsets + s->num_bands; sfb++) {
  865. int y;
  866. if (*tb++ == 1) {
  867. /** multiply values with the decorrelation_matrix */
  868. for (y = sfb[0]; y < FFMIN(sfb[1], s->subframe_len); y++) {
  869. const float* mat = s->chgroup[i].decorrelation_matrix;
  870. const float* data_end = data + num_channels;
  871. float* data_ptr = data;
  872. float** ch;
  873. for (ch = ch_data; ch < ch_end; ch++)
  874. *data_ptr++ = (*ch)[y];
  875. for (ch = ch_data; ch < ch_end; ch++) {
  876. float sum = 0;
  877. data_ptr = data;
  878. while (data_ptr < data_end)
  879. sum += *data_ptr++ * *mat++;
  880. (*ch)[y] = sum;
  881. }
  882. }
  883. } else if (s->num_channels == 2) {
  884. int len = FFMIN(sfb[1], s->subframe_len) - sfb[0];
  885. s->dsp.vector_fmul_scalar(ch_data[0] + sfb[0],
  886. ch_data[0] + sfb[0],
  887. 181.0 / 128, len);
  888. s->dsp.vector_fmul_scalar(ch_data[1] + sfb[0],
  889. ch_data[1] + sfb[0],
  890. 181.0 / 128, len);
  891. }
  892. }
  893. }
  894. }
  895. }
  896. /**
  897. *@brief Apply sine window and reconstruct the output buffer.
  898. *@param s codec context
  899. */
  900. static void wmapro_window(WMAProDecodeCtx *s)
  901. {
  902. int i;
  903. for (i = 0; i < s->channels_for_cur_subframe; i++) {
  904. int c = s->channel_indexes_for_cur_subframe[i];
  905. float* window;
  906. int winlen = s->channel[c].prev_block_len;
  907. float* start = s->channel[c].coeffs - (winlen >> 1);
  908. if (s->subframe_len < winlen) {
  909. start += (winlen - s->subframe_len) >> 1;
  910. winlen = s->subframe_len;
  911. }
  912. window = s->windows[av_log2(winlen) - WMAPRO_BLOCK_MIN_BITS];
  913. winlen >>= 1;
  914. s->dsp.vector_fmul_window(start, start, start + winlen,
  915. window, winlen);
  916. s->channel[c].prev_block_len = s->subframe_len;
  917. }
  918. }
  919. /**
  920. *@brief Decode a single subframe (block).
  921. *@param s codec context
  922. *@return 0 on success, < 0 when decoding failed
  923. */
  924. static int decode_subframe(WMAProDecodeCtx *s)
  925. {
  926. int offset = s->samples_per_frame;
  927. int subframe_len = s->samples_per_frame;
  928. int i;
  929. int total_samples = s->samples_per_frame * s->num_channels;
  930. int transmit_coeffs = 0;
  931. int cur_subwoofer_cutoff;
  932. s->subframe_offset = get_bits_count(&s->gb);
  933. /** reset channel context and find the next block offset and size
  934. == the next block of the channel with the smallest number of
  935. decoded samples
  936. */
  937. for (i = 0; i < s->num_channels; i++) {
  938. s->channel[i].grouped = 0;
  939. if (offset > s->channel[i].decoded_samples) {
  940. offset = s->channel[i].decoded_samples;
  941. subframe_len =
  942. s->channel[i].subframe_len[s->channel[i].cur_subframe];
  943. }
  944. }
  945. av_dlog(s->avctx,
  946. "processing subframe with offset %i len %i\n", offset, subframe_len);
  947. /** get a list of all channels that contain the estimated block */
  948. s->channels_for_cur_subframe = 0;
  949. for (i = 0; i < s->num_channels; i++) {
  950. const int cur_subframe = s->channel[i].cur_subframe;
  951. /** substract already processed samples */
  952. total_samples -= s->channel[i].decoded_samples;
  953. /** and count if there are multiple subframes that match our profile */
  954. if (offset == s->channel[i].decoded_samples &&
  955. subframe_len == s->channel[i].subframe_len[cur_subframe]) {
  956. total_samples -= s->channel[i].subframe_len[cur_subframe];
  957. s->channel[i].decoded_samples +=
  958. s->channel[i].subframe_len[cur_subframe];
  959. s->channel_indexes_for_cur_subframe[s->channels_for_cur_subframe] = i;
  960. ++s->channels_for_cur_subframe;
  961. }
  962. }
  963. /** check if the frame will be complete after processing the
  964. estimated block */
  965. if (!total_samples)
  966. s->parsed_all_subframes = 1;
  967. av_dlog(s->avctx, "subframe is part of %i channels\n",
  968. s->channels_for_cur_subframe);
  969. /** calculate number of scale factor bands and their offsets */
  970. s->table_idx = av_log2(s->samples_per_frame/subframe_len);
  971. s->num_bands = s->num_sfb[s->table_idx];
  972. s->cur_sfb_offsets = s->sfb_offsets[s->table_idx];
  973. cur_subwoofer_cutoff = s->subwoofer_cutoffs[s->table_idx];
  974. /** configure the decoder for the current subframe */
  975. for (i = 0; i < s->channels_for_cur_subframe; i++) {
  976. int c = s->channel_indexes_for_cur_subframe[i];
  977. s->channel[c].coeffs = &s->channel[c].out[(s->samples_per_frame >> 1)
  978. + offset];
  979. }
  980. s->subframe_len = subframe_len;
  981. s->esc_len = av_log2(s->subframe_len - 1) + 1;
  982. /** skip extended header if any */
  983. if (get_bits1(&s->gb)) {
  984. int num_fill_bits;
  985. if (!(num_fill_bits = get_bits(&s->gb, 2))) {
  986. int len = get_bits(&s->gb, 4);
  987. num_fill_bits = get_bits(&s->gb, len) + 1;
  988. }
  989. if (num_fill_bits >= 0) {
  990. if (get_bits_count(&s->gb) + num_fill_bits > s->num_saved_bits) {
  991. av_log(s->avctx, AV_LOG_ERROR, "invalid number of fill bits\n");
  992. return AVERROR_INVALIDDATA;
  993. }
  994. skip_bits_long(&s->gb, num_fill_bits);
  995. }
  996. }
  997. /** no idea for what the following bit is used */
  998. if (get_bits1(&s->gb)) {
  999. av_log_ask_for_sample(s->avctx, "reserved bit set\n");
  1000. return AVERROR_INVALIDDATA;
  1001. }
  1002. if (decode_channel_transform(s) < 0)
  1003. return AVERROR_INVALIDDATA;
  1004. for (i = 0; i < s->channels_for_cur_subframe; i++) {
  1005. int c = s->channel_indexes_for_cur_subframe[i];
  1006. if ((s->channel[c].transmit_coefs = get_bits1(&s->gb)))
  1007. transmit_coeffs = 1;
  1008. }
  1009. if (transmit_coeffs) {
  1010. int step;
  1011. int quant_step = 90 * s->bits_per_sample >> 4;
  1012. /** decode number of vector coded coefficients */
  1013. if ((s->transmit_num_vec_coeffs = get_bits1(&s->gb))) {
  1014. int num_bits = av_log2((s->subframe_len + 3)/4) + 1;
  1015. for (i = 0; i < s->channels_for_cur_subframe; i++) {
  1016. int c = s->channel_indexes_for_cur_subframe[i];
  1017. s->channel[c].num_vec_coeffs = get_bits(&s->gb, num_bits) << 2;
  1018. }
  1019. } else {
  1020. for (i = 0; i < s->channels_for_cur_subframe; i++) {
  1021. int c = s->channel_indexes_for_cur_subframe[i];
  1022. s->channel[c].num_vec_coeffs = s->subframe_len;
  1023. }
  1024. }
  1025. /** decode quantization step */
  1026. step = get_sbits(&s->gb, 6);
  1027. quant_step += step;
  1028. if (step == -32 || step == 31) {
  1029. const int sign = (step == 31) - 1;
  1030. int quant = 0;
  1031. while (get_bits_count(&s->gb) + 5 < s->num_saved_bits &&
  1032. (step = get_bits(&s->gb, 5)) == 31) {
  1033. quant += 31;
  1034. }
  1035. quant_step += ((quant + step) ^ sign) - sign;
  1036. }
  1037. if (quant_step < 0) {
  1038. av_log(s->avctx, AV_LOG_DEBUG, "negative quant step\n");
  1039. }
  1040. /** decode quantization step modifiers for every channel */
  1041. if (s->channels_for_cur_subframe == 1) {
  1042. s->channel[s->channel_indexes_for_cur_subframe[0]].quant_step = quant_step;
  1043. } else {
  1044. int modifier_len = get_bits(&s->gb, 3);
  1045. for (i = 0; i < s->channels_for_cur_subframe; i++) {
  1046. int c = s->channel_indexes_for_cur_subframe[i];
  1047. s->channel[c].quant_step = quant_step;
  1048. if (get_bits1(&s->gb)) {
  1049. if (modifier_len) {
  1050. s->channel[c].quant_step += get_bits(&s->gb, modifier_len) + 1;
  1051. } else
  1052. ++s->channel[c].quant_step;
  1053. }
  1054. }
  1055. }
  1056. /** decode scale factors */
  1057. if (decode_scale_factors(s) < 0)
  1058. return AVERROR_INVALIDDATA;
  1059. }
  1060. av_dlog(s->avctx, "BITSTREAM: subframe header length was %i\n",
  1061. get_bits_count(&s->gb) - s->subframe_offset);
  1062. /** parse coefficients */
  1063. for (i = 0; i < s->channels_for_cur_subframe; i++) {
  1064. int c = s->channel_indexes_for_cur_subframe[i];
  1065. if (s->channel[c].transmit_coefs &&
  1066. get_bits_count(&s->gb) < s->num_saved_bits) {
  1067. decode_coeffs(s, c);
  1068. } else
  1069. memset(s->channel[c].coeffs, 0,
  1070. sizeof(*s->channel[c].coeffs) * subframe_len);
  1071. }
  1072. av_dlog(s->avctx, "BITSTREAM: subframe length was %i\n",
  1073. get_bits_count(&s->gb) - s->subframe_offset);
  1074. if (transmit_coeffs) {
  1075. /** reconstruct the per channel data */
  1076. inverse_channel_transform(s);
  1077. for (i = 0; i < s->channels_for_cur_subframe; i++) {
  1078. int c = s->channel_indexes_for_cur_subframe[i];
  1079. const int* sf = s->channel[c].scale_factors;
  1080. int b;
  1081. if (c == s->lfe_channel)
  1082. memset(&s->tmp[cur_subwoofer_cutoff], 0, sizeof(*s->tmp) *
  1083. (subframe_len - cur_subwoofer_cutoff));
  1084. /** inverse quantization and rescaling */
  1085. for (b = 0; b < s->num_bands; b++) {
  1086. const int end = FFMIN(s->cur_sfb_offsets[b+1], s->subframe_len);
  1087. const int exp = s->channel[c].quant_step -
  1088. (s->channel[c].max_scale_factor - *sf++) *
  1089. s->channel[c].scale_factor_step;
  1090. const float quant = pow(10.0, exp / 20.0);
  1091. int start = s->cur_sfb_offsets[b];
  1092. s->dsp.vector_fmul_scalar(s->tmp + start,
  1093. s->channel[c].coeffs + start,
  1094. quant, end - start);
  1095. }
  1096. /** apply imdct (ff_imdct_half == DCTIV with reverse) */
  1097. ff_imdct_half(&s->mdct_ctx[av_log2(subframe_len) - WMAPRO_BLOCK_MIN_BITS],
  1098. s->channel[c].coeffs, s->tmp);
  1099. }
  1100. }
  1101. /** window and overlapp-add */
  1102. wmapro_window(s);
  1103. /** handled one subframe */
  1104. for (i = 0; i < s->channels_for_cur_subframe; i++) {
  1105. int c = s->channel_indexes_for_cur_subframe[i];
  1106. if (s->channel[c].cur_subframe >= s->channel[c].num_subframes) {
  1107. av_log(s->avctx, AV_LOG_ERROR, "broken subframe\n");
  1108. return AVERROR_INVALIDDATA;
  1109. }
  1110. ++s->channel[c].cur_subframe;
  1111. }
  1112. return 0;
  1113. }
  1114. /**
  1115. *@brief Decode one WMA frame.
  1116. *@param s codec context
  1117. *@return 0 if the trailer bit indicates that this is the last frame,
  1118. * 1 if there are additional frames
  1119. */
  1120. static int decode_frame(WMAProDecodeCtx *s)
  1121. {
  1122. GetBitContext* gb = &s->gb;
  1123. int more_frames = 0;
  1124. int len = 0;
  1125. int i;
  1126. /** check for potential output buffer overflow */
  1127. if (s->num_channels * s->samples_per_frame > s->samples_end - s->samples) {
  1128. /** return an error if no frame could be decoded at all */
  1129. av_log(s->avctx, AV_LOG_ERROR,
  1130. "not enough space for the output samples\n");
  1131. s->packet_loss = 1;
  1132. return 0;
  1133. }
  1134. /** get frame length */
  1135. if (s->len_prefix)
  1136. len = get_bits(gb, s->log2_frame_size);
  1137. av_dlog(s->avctx, "decoding frame with length %x\n", len);
  1138. /** decode tile information */
  1139. if (decode_tilehdr(s)) {
  1140. s->packet_loss = 1;
  1141. return 0;
  1142. }
  1143. /** read postproc transform */
  1144. if (s->num_channels > 1 && get_bits1(gb)) {
  1145. if (get_bits1(gb)) {
  1146. for (i = 0; i < s->num_channels * s->num_channels; i++)
  1147. skip_bits(gb, 4);
  1148. }
  1149. }
  1150. /** read drc info */
  1151. if (s->dynamic_range_compression) {
  1152. s->drc_gain = get_bits(gb, 8);
  1153. av_dlog(s->avctx, "drc_gain %i\n", s->drc_gain);
  1154. }
  1155. /** no idea what these are for, might be the number of samples
  1156. that need to be skipped at the beginning or end of a stream */
  1157. if (get_bits1(gb)) {
  1158. int skip;
  1159. /** usually true for the first frame */
  1160. if (get_bits1(gb)) {
  1161. skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
  1162. av_dlog(s->avctx, "start skip: %i\n", skip);
  1163. }
  1164. /** sometimes true for the last frame */
  1165. if (get_bits1(gb)) {
  1166. skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
  1167. av_dlog(s->avctx, "end skip: %i\n", skip);
  1168. }
  1169. }
  1170. av_dlog(s->avctx, "BITSTREAM: frame header length was %i\n",
  1171. get_bits_count(gb) - s->frame_offset);
  1172. /** reset subframe states */
  1173. s->parsed_all_subframes = 0;
  1174. for (i = 0; i < s->num_channels; i++) {
  1175. s->channel[i].decoded_samples = 0;
  1176. s->channel[i].cur_subframe = 0;
  1177. s->channel[i].reuse_sf = 0;
  1178. }
  1179. /** decode all subframes */
  1180. while (!s->parsed_all_subframes) {
  1181. if (decode_subframe(s) < 0) {
  1182. s->packet_loss = 1;
  1183. return 0;
  1184. }
  1185. }
  1186. /** interleave samples and write them to the output buffer */
  1187. for (i = 0; i < s->num_channels; i++) {
  1188. float* ptr = s->samples + i;
  1189. int incr = s->num_channels;
  1190. float* iptr = s->channel[i].out;
  1191. float* iend = iptr + s->samples_per_frame;
  1192. // FIXME should create/use a DSP function here
  1193. while (iptr < iend) {
  1194. *ptr = *iptr++;
  1195. ptr += incr;
  1196. }
  1197. /** reuse second half of the IMDCT output for the next frame */
  1198. memcpy(&s->channel[i].out[0],
  1199. &s->channel[i].out[s->samples_per_frame],
  1200. s->samples_per_frame * sizeof(*s->channel[i].out) >> 1);
  1201. }
  1202. if (s->skip_frame) {
  1203. s->skip_frame = 0;
  1204. } else
  1205. s->samples += s->num_channels * s->samples_per_frame;
  1206. if (s->len_prefix) {
  1207. if (len != (get_bits_count(gb) - s->frame_offset) + 2) {
  1208. /** FIXME: not sure if this is always an error */
  1209. av_log(s->avctx, AV_LOG_ERROR,
  1210. "frame[%i] would have to skip %i bits\n", s->frame_num,
  1211. len - (get_bits_count(gb) - s->frame_offset) - 1);
  1212. s->packet_loss = 1;
  1213. return 0;
  1214. }
  1215. /** skip the rest of the frame data */
  1216. skip_bits_long(gb, len - (get_bits_count(gb) - s->frame_offset) - 1);
  1217. } else {
  1218. while (get_bits_count(gb) < s->num_saved_bits && get_bits1(gb) == 0) {
  1219. }
  1220. }
  1221. /** decode trailer bit */
  1222. more_frames = get_bits1(gb);
  1223. ++s->frame_num;
  1224. return more_frames;
  1225. }
  1226. /**
  1227. *@brief Calculate remaining input buffer length.
  1228. *@param s codec context
  1229. *@param gb bitstream reader context
  1230. *@return remaining size in bits
  1231. */
  1232. static int remaining_bits(WMAProDecodeCtx *s, GetBitContext *gb)
  1233. {
  1234. return s->buf_bit_size - get_bits_count(gb);
  1235. }
  1236. /**
  1237. *@brief Fill the bit reservoir with a (partial) frame.
  1238. *@param s codec context
  1239. *@param gb bitstream reader context
  1240. *@param len length of the partial frame
  1241. *@param append decides wether to reset the buffer or not
  1242. */
  1243. static void save_bits(WMAProDecodeCtx *s, GetBitContext* gb, int len,
  1244. int append)
  1245. {
  1246. int buflen;
  1247. /** when the frame data does not need to be concatenated, the input buffer
  1248. is resetted and additional bits from the previous frame are copyed
  1249. and skipped later so that a fast byte copy is possible */
  1250. if (!append) {
  1251. s->frame_offset = get_bits_count(gb) & 7;
  1252. s->num_saved_bits = s->frame_offset;
  1253. init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
  1254. }
  1255. buflen = (s->num_saved_bits + len + 8) >> 3;
  1256. if (len <= 0 || buflen > MAX_FRAMESIZE) {
  1257. av_log_ask_for_sample(s->avctx, "input buffer too small\n");
  1258. s->packet_loss = 1;
  1259. return;
  1260. }
  1261. s->num_saved_bits += len;
  1262. if (!append) {
  1263. ff_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3),
  1264. s->num_saved_bits);
  1265. } else {
  1266. int align = 8 - (get_bits_count(gb) & 7);
  1267. align = FFMIN(align, len);
  1268. put_bits(&s->pb, align, get_bits(gb, align));
  1269. len -= align;
  1270. ff_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3), len);
  1271. }
  1272. skip_bits_long(gb, len);
  1273. {
  1274. PutBitContext tmp = s->pb;
  1275. flush_put_bits(&tmp);
  1276. }
  1277. init_get_bits(&s->gb, s->frame_data, s->num_saved_bits);
  1278. skip_bits(&s->gb, s->frame_offset);
  1279. }
  1280. /**
  1281. *@brief Decode a single WMA packet.
  1282. *@param avctx codec context
  1283. *@param data the output buffer
  1284. *@param data_size number of bytes that were written to the output buffer
  1285. *@param avpkt input packet
  1286. *@return number of bytes that were read from the input buffer
  1287. */
  1288. static int decode_packet(AVCodecContext *avctx,
  1289. void *data, int *data_size, AVPacket* avpkt)
  1290. {
  1291. WMAProDecodeCtx *s = avctx->priv_data;
  1292. GetBitContext* gb = &s->pgb;
  1293. const uint8_t* buf = avpkt->data;
  1294. int buf_size = avpkt->size;
  1295. int num_bits_prev_frame;
  1296. int packet_sequence_number;
  1297. s->samples = data;
  1298. s->samples_end = (float*)((int8_t*)data + *data_size);
  1299. *data_size = 0;
  1300. if (s->packet_done || s->packet_loss) {
  1301. s->packet_done = 0;
  1302. /** sanity check for the buffer length */
  1303. if (buf_size < avctx->block_align)
  1304. return 0;
  1305. s->next_packet_start = buf_size - avctx->block_align;
  1306. buf_size = avctx->block_align;
  1307. s->buf_bit_size = buf_size << 3;
  1308. /** parse packet header */
  1309. init_get_bits(gb, buf, s->buf_bit_size);
  1310. packet_sequence_number = get_bits(gb, 4);
  1311. skip_bits(gb, 2);
  1312. /** get number of bits that need to be added to the previous frame */
  1313. num_bits_prev_frame = get_bits(gb, s->log2_frame_size);
  1314. av_dlog(avctx, "packet[%d]: nbpf %x\n", avctx->frame_number,
  1315. num_bits_prev_frame);
  1316. /** check for packet loss */
  1317. if (!s->packet_loss &&
  1318. ((s->packet_sequence_number + 1) & 0xF) != packet_sequence_number) {
  1319. s->packet_loss = 1;
  1320. av_log(avctx, AV_LOG_ERROR, "Packet loss detected! seq %x vs %x\n",
  1321. s->packet_sequence_number, packet_sequence_number);
  1322. }
  1323. s->packet_sequence_number = packet_sequence_number;
  1324. if (num_bits_prev_frame > 0) {
  1325. int remaining_packet_bits = s->buf_bit_size - get_bits_count(gb);
  1326. if (num_bits_prev_frame >= remaining_packet_bits) {
  1327. num_bits_prev_frame = remaining_packet_bits;
  1328. s->packet_done = 1;
  1329. }
  1330. /** append the previous frame data to the remaining data from the
  1331. previous packet to create a full frame */
  1332. save_bits(s, gb, num_bits_prev_frame, 1);
  1333. av_dlog(avctx, "accumulated %x bits of frame data\n",
  1334. s->num_saved_bits - s->frame_offset);
  1335. /** decode the cross packet frame if it is valid */
  1336. if (!s->packet_loss)
  1337. decode_frame(s);
  1338. } else if (s->num_saved_bits - s->frame_offset) {
  1339. av_dlog(avctx, "ignoring %x previously saved bits\n",
  1340. s->num_saved_bits - s->frame_offset);
  1341. }
  1342. if (s->packet_loss) {
  1343. /** reset number of saved bits so that the decoder
  1344. does not start to decode incomplete frames in the
  1345. s->len_prefix == 0 case */
  1346. s->num_saved_bits = 0;
  1347. s->packet_loss = 0;
  1348. }
  1349. } else {
  1350. int frame_size;
  1351. s->buf_bit_size = (avpkt->size - s->next_packet_start) << 3;
  1352. init_get_bits(gb, avpkt->data, s->buf_bit_size);
  1353. skip_bits(gb, s->packet_offset);
  1354. if (s->len_prefix && remaining_bits(s, gb) > s->log2_frame_size &&
  1355. (frame_size = show_bits(gb, s->log2_frame_size)) &&
  1356. frame_size <= remaining_bits(s, gb)) {
  1357. save_bits(s, gb, frame_size, 0);
  1358. s->packet_done = !decode_frame(s);
  1359. } else if (!s->len_prefix
  1360. && s->num_saved_bits > get_bits_count(&s->gb)) {
  1361. /** when the frames do not have a length prefix, we don't know
  1362. the compressed length of the individual frames
  1363. however, we know what part of a new packet belongs to the
  1364. previous frame
  1365. therefore we save the incoming packet first, then we append
  1366. the "previous frame" data from the next packet so that
  1367. we get a buffer that only contains full frames */
  1368. s->packet_done = !decode_frame(s);
  1369. } else
  1370. s->packet_done = 1;
  1371. }
  1372. if (s->packet_done && !s->packet_loss &&
  1373. remaining_bits(s, gb) > 0) {
  1374. /** save the rest of the data so that it can be decoded
  1375. with the next packet */
  1376. save_bits(s, gb, remaining_bits(s, gb), 0);
  1377. }
  1378. *data_size = (int8_t *)s->samples - (int8_t *)data;
  1379. s->packet_offset = get_bits_count(gb) & 7;
  1380. return (s->packet_loss) ? AVERROR_INVALIDDATA : get_bits_count(gb) >> 3;
  1381. }
  1382. /**
  1383. *@brief Clear decoder buffers (for seeking).
  1384. *@param avctx codec context
  1385. */
  1386. static void flush(AVCodecContext *avctx)
  1387. {
  1388. WMAProDecodeCtx *s = avctx->priv_data;
  1389. int i;
  1390. /** reset output buffer as a part of it is used during the windowing of a
  1391. new frame */
  1392. for (i = 0; i < s->num_channels; i++)
  1393. memset(s->channel[i].out, 0, s->samples_per_frame *
  1394. sizeof(*s->channel[i].out));
  1395. s->packet_loss = 1;
  1396. }
  1397. /**
  1398. *@brief wmapro decoder
  1399. */
  1400. AVCodec ff_wmapro_decoder = {
  1401. "wmapro",
  1402. AVMEDIA_TYPE_AUDIO,
  1403. CODEC_ID_WMAPRO,
  1404. sizeof(WMAProDecodeCtx),
  1405. decode_init,
  1406. NULL,
  1407. decode_end,
  1408. decode_packet,
  1409. .capabilities = CODEC_CAP_SUBFRAMES,
  1410. .flush= flush,
  1411. .long_name = NULL_IF_CONFIG_SMALL("Windows Media Audio 9 Professional"),
  1412. };