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