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.

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