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.

1565 lines
56KB

  1. /*
  2. * Wmall compatible decoder
  3. * Copyright (c) 2007 Baptiste Coudurier, Benjamin Larsson, Ulion
  4. * Copyright (c) 2008 - 2011 Sascha Sommer, Benjamin Larsson
  5. * Copyright (c) 2011 Andreas Öman
  6. *
  7. * This file is part of FFmpeg.
  8. *
  9. * FFmpeg is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2.1 of the License, or (at your option) any later version.
  13. *
  14. * FFmpeg is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with FFmpeg; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. */
  23. /**
  24. * @file
  25. * @brief wmall decoder implementation
  26. * Wmall is an MDCT based codec comparable to wma standard or AAC.
  27. * The decoding therefore consists of the following steps:
  28. * - bitstream decoding
  29. * - reconstruction of per-channel data
  30. * - rescaling and inverse quantization
  31. * - IMDCT
  32. * - windowing and overlapp-add
  33. *
  34. * The compressed wmall bitstream is split into individual packets.
  35. * Every such packet contains one or more wma frames.
  36. * The compressed frames may have a variable length and frames may
  37. * cross packet boundaries.
  38. * Common to all wmall frames is the number of samples that are stored in
  39. * a frame.
  40. * The number of samples and a few other decode flags are stored
  41. * as extradata that has to be passed to the decoder.
  42. *
  43. * The wmall frames themselves are again split into a variable number of
  44. * subframes. Every subframe contains the data for 2^N time domain samples
  45. * where N varies between 7 and 12.
  46. *
  47. * Example wmall bitstream (in samples):
  48. *
  49. * || packet 0 || packet 1 || packet 2 packets
  50. * ---------------------------------------------------
  51. * || frame 0 || frame 1 || frame 2 || frames
  52. * ---------------------------------------------------
  53. * || | | || | | | || || subframes of channel 0
  54. * ---------------------------------------------------
  55. * || | | || | | | || || subframes of channel 1
  56. * ---------------------------------------------------
  57. *
  58. * The frame layouts for the individual channels of a wma frame does not need
  59. * to be the same.
  60. *
  61. * However, if the offsets and lengths of several subframes of a frame are the
  62. * same, the subframes of the channels can be grouped.
  63. * Every group may then use special coding techniques like M/S stereo coding
  64. * to improve the compression ratio. These channel transformations do not
  65. * need to be applied to a whole subframe. Instead, they can also work on
  66. * individual scale factor bands (see below).
  67. * The coefficients that carry the audio signal in the frequency domain
  68. * are transmitted as huffman-coded vectors with 4, 2 and 1 elements.
  69. * In addition to that, the encoder can switch to a runlevel coding scheme
  70. * by transmitting subframe_length / 128 zero coefficients.
  71. *
  72. * Before the audio signal can be converted to the time domain, the
  73. * coefficients have to be rescaled and inverse quantized.
  74. * A subframe is therefore split into several scale factor bands that get
  75. * scaled individually.
  76. * Scale factors are submitted for every frame but they might be shared
  77. * between the subframes of a channel. Scale factors are initially DPCM-coded.
  78. * Once scale factors are shared, the differences are transmitted as runlevel
  79. * codes.
  80. * Every subframe length and offset combination in the frame layout shares a
  81. * common quantization factor that can be adjusted for every channel by a
  82. * modifier.
  83. * After the inverse quantization, the coefficients get processed by an IMDCT.
  84. * The resulting values are then windowed with a sine window and the first half
  85. * of the values are added to the second half of the output from the previous
  86. * subframe in order to reconstruct the output samples.
  87. */
  88. #include "avcodec.h"
  89. #include "internal.h"
  90. #include "get_bits.h"
  91. #include "put_bits.h"
  92. #include "dsputil.h"
  93. #include "wma.h"
  94. /** current decoder limitations */
  95. #define WMALL_MAX_CHANNELS 8 ///< max number of handled channels
  96. #define MAX_SUBFRAMES 32 ///< max number of subframes per channel
  97. #define MAX_BANDS 29 ///< max number of scale factor bands
  98. #define MAX_FRAMESIZE 32768 ///< maximum compressed frame size
  99. #define WMALL_BLOCK_MIN_BITS 6 ///< log2 of min block size
  100. #define WMALL_BLOCK_MAX_BITS 12 ///< log2 of max block size
  101. #define WMALL_BLOCK_MAX_SIZE (1 << WMALL_BLOCK_MAX_BITS) ///< maximum block size
  102. #define WMALL_BLOCK_SIZES (WMALL_BLOCK_MAX_BITS - WMALL_BLOCK_MIN_BITS + 1) ///< possible block sizes
  103. #define VLCBITS 9
  104. #define SCALEVLCBITS 8
  105. #define VEC4MAXDEPTH ((HUFF_VEC4_MAXBITS+VLCBITS-1)/VLCBITS)
  106. #define VEC2MAXDEPTH ((HUFF_VEC2_MAXBITS+VLCBITS-1)/VLCBITS)
  107. #define VEC1MAXDEPTH ((HUFF_VEC1_MAXBITS+VLCBITS-1)/VLCBITS)
  108. #define SCALEMAXDEPTH ((HUFF_SCALE_MAXBITS+SCALEVLCBITS-1)/SCALEVLCBITS)
  109. #define SCALERLMAXDEPTH ((HUFF_SCALE_RL_MAXBITS+VLCBITS-1)/VLCBITS)
  110. static float sin64[33]; ///< sinus table for decorrelation
  111. /**
  112. * @brief frame specific decoder context for a single channel
  113. */
  114. typedef struct {
  115. int16_t prev_block_len; ///< length of the previous block
  116. uint8_t transmit_coefs;
  117. uint8_t num_subframes;
  118. uint16_t subframe_len[MAX_SUBFRAMES]; ///< subframe length in samples
  119. uint16_t subframe_offset[MAX_SUBFRAMES]; ///< subframe positions in the current frame
  120. uint8_t cur_subframe; ///< current subframe number
  121. uint16_t decoded_samples; ///< number of already processed samples
  122. uint8_t grouped; ///< channel is part of a group
  123. int quant_step; ///< quantization step for the current subframe
  124. int8_t reuse_sf; ///< share scale factors between subframes
  125. int8_t scale_factor_step; ///< scaling step for the current subframe
  126. int max_scale_factor; ///< maximum scale factor for the current subframe
  127. int saved_scale_factors[2][MAX_BANDS]; ///< resampled and (previously) transmitted scale factor values
  128. int8_t scale_factor_idx; ///< index for the transmitted scale factor values (used for resampling)
  129. int* scale_factors; ///< pointer to the scale factor values used for decoding
  130. uint8_t table_idx; ///< index in sf_offsets for the scale factor reference block
  131. float* coeffs; ///< pointer to the subframe decode buffer
  132. uint16_t num_vec_coeffs; ///< number of vector coded coefficients
  133. DECLARE_ALIGNED(16, float, out)[WMALL_BLOCK_MAX_SIZE + WMALL_BLOCK_MAX_SIZE / 2]; ///< output buffer
  134. int transient_counter; ///< number of transient samples from the beginning of transient zone
  135. } WmallChannelCtx;
  136. /**
  137. * @brief channel group for channel transformations
  138. */
  139. typedef struct {
  140. uint8_t num_channels; ///< number of channels in the group
  141. int8_t transform; ///< transform on / off
  142. int8_t transform_band[MAX_BANDS]; ///< controls if the transform is enabled for a certain band
  143. float decorrelation_matrix[WMALL_MAX_CHANNELS*WMALL_MAX_CHANNELS];
  144. float* channel_data[WMALL_MAX_CHANNELS]; ///< transformation coefficients
  145. } WmallChannelGrp;
  146. /**
  147. * @brief main decoder context
  148. */
  149. typedef struct WmallDecodeCtx {
  150. /* generic decoder variables */
  151. AVCodecContext* avctx; ///< codec context for av_log
  152. DSPContext dsp; ///< accelerated DSP functions
  153. uint8_t frame_data[MAX_FRAMESIZE +
  154. FF_INPUT_BUFFER_PADDING_SIZE];///< compressed frame data
  155. PutBitContext pb; ///< context for filling the frame_data buffer
  156. FFTContext mdct_ctx[WMALL_BLOCK_SIZES]; ///< MDCT context per block size
  157. DECLARE_ALIGNED(16, float, tmp)[WMALL_BLOCK_MAX_SIZE]; ///< IMDCT output buffer
  158. float* windows[WMALL_BLOCK_SIZES]; ///< windows for the different block sizes
  159. /* frame size dependent frame information (set during initialization) */
  160. uint32_t decode_flags; ///< used compression features
  161. uint8_t len_prefix; ///< frame is prefixed with its length
  162. uint8_t dynamic_range_compression; ///< frame contains DRC data
  163. uint8_t bits_per_sample; ///< integer audio sample size for the unscaled IMDCT output (used to scale to [-1.0, 1.0])
  164. uint16_t samples_per_frame; ///< number of samples to output
  165. uint16_t log2_frame_size;
  166. int8_t num_channels; ///< number of channels in the stream (same as AVCodecContext.num_channels)
  167. int8_t lfe_channel; ///< lfe channel index
  168. uint8_t max_num_subframes;
  169. uint8_t subframe_len_bits; ///< number of bits used for the subframe length
  170. uint8_t max_subframe_len_bit; ///< flag indicating that the subframe is of maximum size when the first subframe length bit is 1
  171. uint16_t min_samples_per_subframe;
  172. int8_t num_sfb[WMALL_BLOCK_SIZES]; ///< scale factor bands per block size
  173. int16_t sfb_offsets[WMALL_BLOCK_SIZES][MAX_BANDS]; ///< scale factor band offsets (multiples of 4)
  174. int8_t sf_offsets[WMALL_BLOCK_SIZES][WMALL_BLOCK_SIZES][MAX_BANDS]; ///< scale factor resample matrix
  175. int16_t subwoofer_cutoffs[WMALL_BLOCK_SIZES]; ///< subwoofer cutoff values
  176. /* packet decode state */
  177. GetBitContext pgb; ///< bitstream reader context for the packet
  178. int next_packet_start; ///< start offset of the next wma packet in the demuxer packet
  179. uint8_t packet_offset; ///< frame offset in the packet
  180. uint8_t packet_sequence_number; ///< current packet number
  181. int num_saved_bits; ///< saved number of bits
  182. int frame_offset; ///< frame offset in the bit reservoir
  183. int subframe_offset; ///< subframe offset in the bit reservoir
  184. uint8_t packet_loss; ///< set in case of bitstream error
  185. uint8_t packet_done; ///< set when a packet is fully decoded
  186. /* frame decode state */
  187. uint32_t frame_num; ///< current frame number (not used for decoding)
  188. GetBitContext gb; ///< bitstream reader context
  189. int buf_bit_size; ///< buffer size in bits
  190. int16_t* samples_16; ///< current samplebuffer pointer (16-bit)
  191. int16_t* samples_16_end; ///< maximum samplebuffer pointer
  192. int16_t* samples_32; ///< current samplebuffer pointer (24-bit)
  193. int16_t* samples_32_end; ///< maximum samplebuffer pointer
  194. uint8_t drc_gain; ///< gain for the DRC tool
  195. int8_t skip_frame; ///< skip output step
  196. int8_t parsed_all_subframes; ///< all subframes decoded?
  197. /* subframe/block decode state */
  198. int16_t subframe_len; ///< current subframe length
  199. int8_t channels_for_cur_subframe; ///< number of channels that contain the subframe
  200. int8_t channel_indexes_for_cur_subframe[WMALL_MAX_CHANNELS];
  201. int8_t num_bands; ///< number of scale factor bands
  202. int8_t transmit_num_vec_coeffs; ///< number of vector coded coefficients is part of the bitstream
  203. int16_t* cur_sfb_offsets; ///< sfb offsets for the current block
  204. uint8_t table_idx; ///< index for the num_sfb, sfb_offsets, sf_offsets and subwoofer_cutoffs tables
  205. int8_t esc_len; ///< length of escaped coefficients
  206. uint8_t num_chgroups; ///< number of channel groups
  207. WmallChannelGrp chgroup[WMALL_MAX_CHANNELS]; ///< channel group information
  208. WmallChannelCtx channel[WMALL_MAX_CHANNELS]; ///< per channel data
  209. // WMA lossless
  210. uint8_t do_arith_coding;
  211. uint8_t do_ac_filter;
  212. uint8_t do_inter_ch_decorr;
  213. uint8_t do_mclms;
  214. uint8_t do_lpc;
  215. int8_t acfilter_order;
  216. int8_t acfilter_scaling;
  217. int64_t acfilter_coeffs[16];
  218. int acfilter_prevvalues[2][16];
  219. int8_t mclms_order;
  220. int8_t mclms_scaling;
  221. int16_t mclms_coeffs[128];
  222. int16_t mclms_coeffs_cur[4];
  223. int16_t mclms_prevvalues[64]; // FIXME: should be 32-bit / 16-bit depending on bit-depth
  224. int16_t mclms_updates[64];
  225. int mclms_recent;
  226. int movave_scaling;
  227. int quant_stepsize;
  228. struct {
  229. int order;
  230. int scaling;
  231. int coefsend;
  232. int bitsend;
  233. int16_t coefs[256];
  234. int16_t lms_prevvalues[512]; // FIXME: see above
  235. int16_t lms_updates[512]; // and here too
  236. int recent;
  237. } cdlms[2][9]; /* XXX: Here, 2 is the max. no. of channels allowed,
  238. 9 is the maximum no. of filters per channel.
  239. Question is, why 2 if WMALL_MAX_CHANNELS == 8 */
  240. int cdlms_ttl[2];
  241. int bV3RTM;
  242. int is_channel_coded[2]; // XXX: same question as above applies here too (and below)
  243. int update_speed[2];
  244. int transient[2];
  245. int transient_pos[2];
  246. int seekable_tile;
  247. int ave_sum[2];
  248. int channel_residues[2][2048];
  249. int lpc_coefs[2][40];
  250. int lpc_order;
  251. int lpc_scaling;
  252. int lpc_intbits;
  253. int channel_coeffs[2][2048]; // FIXME: should be 32-bit / 16-bit depending on bit-depth
  254. } WmallDecodeCtx;
  255. #undef dprintf
  256. #define dprintf(pctx, ...) av_log(pctx, AV_LOG_DEBUG, __VA_ARGS__)
  257. static int num_logged_tiles = 0;
  258. static int num_logged_subframes = 0;
  259. static int num_lms_update_call = 0;
  260. /**
  261. *@brief helper function to print the most important members of the context
  262. *@param s context
  263. */
  264. static void av_cold dump_context(WmallDecodeCtx *s)
  265. {
  266. #define PRINT(a, b) av_log(s->avctx, AV_LOG_DEBUG, " %s = %d\n", a, b);
  267. #define PRINT_HEX(a, b) av_log(s->avctx, AV_LOG_DEBUG, " %s = %x\n", a, b);
  268. PRINT("ed sample bit depth", s->bits_per_sample);
  269. PRINT_HEX("ed decode flags", s->decode_flags);
  270. PRINT("samples per frame", s->samples_per_frame);
  271. PRINT("log2 frame size", s->log2_frame_size);
  272. PRINT("max num subframes", s->max_num_subframes);
  273. PRINT("len prefix", s->len_prefix);
  274. PRINT("num channels", s->num_channels);
  275. }
  276. static void dump_int_buffer(uint8_t *buffer, int size, int length, int delimiter)
  277. {
  278. int i;
  279. for (i=0 ; i<length ; i++) {
  280. if (!(i%delimiter))
  281. av_log(0, 0, "\n[%d] ", i);
  282. av_log(0, 0, "%d, ", *(int16_t *)(buffer + i * size));
  283. }
  284. av_log(0, 0, "\n");
  285. }
  286. /**
  287. *@brief Uninitialize the decoder and free all resources.
  288. *@param avctx codec context
  289. *@return 0 on success, < 0 otherwise
  290. */
  291. static av_cold int decode_end(AVCodecContext *avctx)
  292. {
  293. WmallDecodeCtx *s = avctx->priv_data;
  294. int i;
  295. for (i = 0; i < WMALL_BLOCK_SIZES; i++)
  296. ff_mdct_end(&s->mdct_ctx[i]);
  297. return 0;
  298. }
  299. /**
  300. *@brief Initialize the decoder.
  301. *@param avctx codec context
  302. *@return 0 on success, -1 otherwise
  303. */
  304. static av_cold int decode_init(AVCodecContext *avctx)
  305. {
  306. WmallDecodeCtx *s = avctx->priv_data;
  307. uint8_t *edata_ptr = avctx->extradata;
  308. unsigned int channel_mask;
  309. int i;
  310. int log2_max_num_subframes;
  311. int num_possible_block_sizes;
  312. s->avctx = avctx;
  313. dsputil_init(&s->dsp, avctx);
  314. init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
  315. if (avctx->extradata_size >= 18) {
  316. s->decode_flags = AV_RL16(edata_ptr+14);
  317. channel_mask = AV_RL32(edata_ptr+2);
  318. s->bits_per_sample = AV_RL16(edata_ptr);
  319. if (s->bits_per_sample == 16)
  320. avctx->sample_fmt = AV_SAMPLE_FMT_S16;
  321. else if (s->bits_per_sample == 24)
  322. avctx->sample_fmt = AV_SAMPLE_FMT_S32;
  323. else {
  324. av_log(avctx, AV_LOG_ERROR, "Unknown bit-depth: %d\n",
  325. s->bits_per_sample);
  326. return AVERROR_INVALIDDATA;
  327. }
  328. /** dump the extradata */
  329. for (i = 0; i < avctx->extradata_size; i++)
  330. dprintf(avctx, "[%x] ", avctx->extradata[i]);
  331. dprintf(avctx, "\n");
  332. } else {
  333. av_log_ask_for_sample(avctx, "Unknown extradata size\n");
  334. return AVERROR_INVALIDDATA;
  335. }
  336. /** generic init */
  337. s->log2_frame_size = av_log2(avctx->block_align) + 4;
  338. /** frame info */
  339. s->skip_frame = 1; /* skip first frame */
  340. s->packet_loss = 1;
  341. s->len_prefix = (s->decode_flags & 0x40);
  342. /** get frame len */
  343. s->samples_per_frame = 1 << ff_wma_get_frame_len_bits(avctx->sample_rate,
  344. 3, s->decode_flags);
  345. /** init previous block len */
  346. for (i = 0; i < avctx->channels; i++)
  347. s->channel[i].prev_block_len = s->samples_per_frame;
  348. /** subframe info */
  349. log2_max_num_subframes = ((s->decode_flags & 0x38) >> 3);
  350. s->max_num_subframes = 1 << log2_max_num_subframes;
  351. s->max_subframe_len_bit = 0;
  352. s->subframe_len_bits = av_log2(log2_max_num_subframes) + 1;
  353. num_possible_block_sizes = log2_max_num_subframes + 1;
  354. s->min_samples_per_subframe = s->samples_per_frame / s->max_num_subframes;
  355. s->dynamic_range_compression = (s->decode_flags & 0x80);
  356. s->bV3RTM = s->decode_flags & 0x100;
  357. if (s->max_num_subframes > MAX_SUBFRAMES) {
  358. av_log(avctx, AV_LOG_ERROR, "invalid number of subframes %i\n",
  359. s->max_num_subframes);
  360. return AVERROR_INVALIDDATA;
  361. }
  362. s->num_channels = avctx->channels;
  363. /** extract lfe channel position */
  364. s->lfe_channel = -1;
  365. if (channel_mask & 8) {
  366. unsigned int mask;
  367. for (mask = 1; mask < 16; mask <<= 1) {
  368. if (channel_mask & mask)
  369. ++s->lfe_channel;
  370. }
  371. }
  372. if (s->num_channels < 0) {
  373. av_log(avctx, AV_LOG_ERROR, "invalid number of channels %d\n", s->num_channels);
  374. return AVERROR_INVALIDDATA;
  375. } else if (s->num_channels > WMALL_MAX_CHANNELS) {
  376. av_log_ask_for_sample(avctx, "unsupported number of channels\n");
  377. return AVERROR_PATCHWELCOME;
  378. }
  379. avctx->channel_layout = channel_mask;
  380. return 0;
  381. }
  382. /**
  383. *@brief Decode the subframe length.
  384. *@param s context
  385. *@param offset sample offset in the frame
  386. *@return decoded subframe length on success, < 0 in case of an error
  387. */
  388. static int decode_subframe_length(WmallDecodeCtx *s, int offset)
  389. {
  390. int frame_len_ratio;
  391. int subframe_len, len;
  392. /** no need to read from the bitstream when only one length is possible */
  393. if (offset == s->samples_per_frame - s->min_samples_per_subframe)
  394. return s->min_samples_per_subframe;
  395. len = av_log2(s->max_num_subframes - 1) + 1;
  396. frame_len_ratio = get_bits(&s->gb, len);
  397. subframe_len = s->min_samples_per_subframe * (frame_len_ratio + 1);
  398. /** sanity check the length */
  399. if (subframe_len < s->min_samples_per_subframe ||
  400. subframe_len > s->samples_per_frame) {
  401. av_log(s->avctx, AV_LOG_ERROR, "broken frame: subframe_len %i\n",
  402. subframe_len);
  403. return AVERROR_INVALIDDATA;
  404. }
  405. return subframe_len;
  406. }
  407. /**
  408. *@brief Decode how the data in the frame is split into subframes.
  409. * Every WMA frame contains the encoded data for a fixed number of
  410. * samples per channel. The data for every channel might be split
  411. * into several subframes. This function will reconstruct the list of
  412. * subframes for every channel.
  413. *
  414. * If the subframes are not evenly split, the algorithm estimates the
  415. * channels with the lowest number of total samples.
  416. * Afterwards, for each of these channels a bit is read from the
  417. * bitstream that indicates if the channel contains a subframe with the
  418. * next subframe size that is going to be read from the bitstream or not.
  419. * If a channel contains such a subframe, the subframe size gets added to
  420. * the channel's subframe list.
  421. * The algorithm repeats these steps until the frame is properly divided
  422. * between the individual channels.
  423. *
  424. *@param s context
  425. *@return 0 on success, < 0 in case of an error
  426. */
  427. static int decode_tilehdr(WmallDecodeCtx *s)
  428. {
  429. uint16_t num_samples[WMALL_MAX_CHANNELS]; /**< sum of samples for all currently known subframes of a channel */
  430. uint8_t contains_subframe[WMALL_MAX_CHANNELS]; /**< flag indicating if a channel contains the current subframe */
  431. int channels_for_cur_subframe = s->num_channels; /**< number of channels that contain the current subframe */
  432. int fixed_channel_layout = 0; /**< flag indicating that all channels use the same subfra2me offsets and sizes */
  433. int min_channel_len = 0; /**< smallest sum of samples (channels with this length will be processed first) */
  434. int c;
  435. /* Should never consume more than 3073 bits (256 iterations for the
  436. * while loop when always the minimum amount of 128 samples is substracted
  437. * from missing samples in the 8 channel case).
  438. * 1 + BLOCK_MAX_SIZE * MAX_CHANNELS / BLOCK_MIN_SIZE * (MAX_CHANNELS + 4)
  439. */
  440. /** reset tiling information */
  441. for (c = 0; c < s->num_channels; c++)
  442. s->channel[c].num_subframes = 0;
  443. memset(num_samples, 0, sizeof(num_samples));
  444. if (s->max_num_subframes == 1 || get_bits1(&s->gb))
  445. fixed_channel_layout = 1;
  446. /** loop until the frame data is split between the subframes */
  447. do {
  448. int subframe_len;
  449. /** check which channels contain the subframe */
  450. for (c = 0; c < s->num_channels; c++) {
  451. if (num_samples[c] == min_channel_len) {
  452. if (fixed_channel_layout || channels_for_cur_subframe == 1 ||
  453. (min_channel_len == s->samples_per_frame - s->min_samples_per_subframe)) {
  454. contains_subframe[c] = 1;
  455. }
  456. else {
  457. contains_subframe[c] = get_bits1(&s->gb);
  458. }
  459. } else
  460. contains_subframe[c] = 0;
  461. }
  462. /** get subframe length, subframe_len == 0 is not allowed */
  463. if ((subframe_len = decode_subframe_length(s, min_channel_len)) <= 0)
  464. return AVERROR_INVALIDDATA;
  465. /** add subframes to the individual channels and find new min_channel_len */
  466. min_channel_len += subframe_len;
  467. for (c = 0; c < s->num_channels; c++) {
  468. WmallChannelCtx* chan = &s->channel[c];
  469. if (contains_subframe[c]) {
  470. if (chan->num_subframes >= MAX_SUBFRAMES) {
  471. av_log(s->avctx, AV_LOG_ERROR,
  472. "broken frame: num subframes > 31\n");
  473. return AVERROR_INVALIDDATA;
  474. }
  475. chan->subframe_len[chan->num_subframes] = subframe_len;
  476. num_samples[c] += subframe_len;
  477. ++chan->num_subframes;
  478. if (num_samples[c] > s->samples_per_frame) {
  479. av_log(s->avctx, AV_LOG_ERROR, "broken frame: "
  480. "channel len(%d) > samples_per_frame(%d)\n",
  481. num_samples[c], s->samples_per_frame);
  482. return AVERROR_INVALIDDATA;
  483. }
  484. } else if (num_samples[c] <= min_channel_len) {
  485. if (num_samples[c] < min_channel_len) {
  486. channels_for_cur_subframe = 0;
  487. min_channel_len = num_samples[c];
  488. }
  489. ++channels_for_cur_subframe;
  490. }
  491. }
  492. } while (min_channel_len < s->samples_per_frame);
  493. for (c = 0; c < s->num_channels; c++) {
  494. int i;
  495. int offset = 0;
  496. for (i = 0; i < s->channel[c].num_subframes; i++) {
  497. s->channel[c].subframe_offset[i] = offset;
  498. offset += s->channel[c].subframe_len[i];
  499. }
  500. }
  501. return 0;
  502. }
  503. static int my_log2(unsigned int i)
  504. {
  505. unsigned int iLog2 = 0;
  506. while ((i >> iLog2) > 1)
  507. iLog2++;
  508. return iLog2;
  509. }
  510. /**
  511. *
  512. */
  513. static void decode_ac_filter(WmallDecodeCtx *s)
  514. {
  515. int i;
  516. s->acfilter_order = get_bits(&s->gb, 4) + 1;
  517. s->acfilter_scaling = get_bits(&s->gb, 4);
  518. for(i = 0; i < s->acfilter_order; i++) {
  519. s->acfilter_coeffs[i] = get_bits(&s->gb, s->acfilter_scaling) + 1;
  520. }
  521. }
  522. /**
  523. *
  524. */
  525. static void decode_mclms(WmallDecodeCtx *s)
  526. {
  527. s->mclms_order = (get_bits(&s->gb, 4) + 1) * 2;
  528. s->mclms_scaling = get_bits(&s->gb, 4);
  529. if(get_bits1(&s->gb)) {
  530. // mclms_send_coef
  531. int i;
  532. int send_coef_bits;
  533. int cbits = av_log2(s->mclms_scaling + 1);
  534. assert(cbits == my_log2(s->mclms_scaling + 1));
  535. if(1 << cbits < s->mclms_scaling + 1)
  536. cbits++;
  537. send_coef_bits = (cbits ? get_bits(&s->gb, cbits) : 0) + 2;
  538. for(i = 0; i < s->mclms_order * s->num_channels * s->num_channels; i++) {
  539. s->mclms_coeffs[i] = get_bits(&s->gb, send_coef_bits);
  540. }
  541. for(i = 0; i < s->num_channels; i++) {
  542. int c;
  543. for(c = 0; c < i; c++) {
  544. s->mclms_coeffs_cur[i * s->num_channels + c] = get_bits(&s->gb, send_coef_bits);
  545. }
  546. }
  547. }
  548. }
  549. /**
  550. *
  551. */
  552. static void decode_cdlms(WmallDecodeCtx *s)
  553. {
  554. int c, i;
  555. int cdlms_send_coef = get_bits1(&s->gb);
  556. for(c = 0; c < s->num_channels; c++) {
  557. s->cdlms_ttl[c] = get_bits(&s->gb, 3) + 1;
  558. for(i = 0; i < s->cdlms_ttl[c]; i++) {
  559. s->cdlms[c][i].order = (get_bits(&s->gb, 7) + 1) * 8;
  560. }
  561. for(i = 0; i < s->cdlms_ttl[c]; i++) {
  562. s->cdlms[c][i].scaling = get_bits(&s->gb, 4);
  563. }
  564. if(cdlms_send_coef) {
  565. for(i = 0; i < s->cdlms_ttl[c]; i++) {
  566. int cbits, shift_l, shift_r, j;
  567. cbits = av_log2(s->cdlms[c][i].order);
  568. if(1 << cbits < s->cdlms[c][i].order)
  569. cbits++;
  570. s->cdlms[c][i].coefsend = get_bits(&s->gb, cbits) + 1;
  571. cbits = av_log2(s->cdlms[c][i].scaling + 1);
  572. if(1 << cbits < s->cdlms[c][i].scaling + 1)
  573. cbits++;
  574. s->cdlms[c][i].bitsend = get_bits(&s->gb, cbits) + 2;
  575. shift_l = 32 - s->cdlms[c][i].bitsend;
  576. shift_r = 32 - 2 - s->cdlms[c][i].scaling;
  577. for(j = 0; j < s->cdlms[c][i].coefsend; j++) {
  578. s->cdlms[c][i].coefs[j] =
  579. (get_bits(&s->gb, s->cdlms[c][i].bitsend) << shift_l) >> shift_r;
  580. }
  581. }
  582. }
  583. }
  584. }
  585. /**
  586. *
  587. */
  588. static int decode_channel_residues(WmallDecodeCtx *s, int ch, int tile_size)
  589. {
  590. int i = 0;
  591. unsigned int ave_mean;
  592. s->transient[ch] = get_bits1(&s->gb);
  593. if(s->transient[ch]) {
  594. s->transient_pos[ch] = get_bits(&s->gb, av_log2(tile_size));
  595. if (s->transient_pos[ch])
  596. s->transient[ch] = 0;
  597. s->channel[ch].transient_counter =
  598. FFMAX(s->channel[ch].transient_counter, s->samples_per_frame / 2);
  599. } else if (s->channel[ch].transient_counter)
  600. s->transient[ch] = 1;
  601. if(s->seekable_tile) {
  602. ave_mean = get_bits(&s->gb, s->bits_per_sample);
  603. s->ave_sum[ch] = ave_mean << (s->movave_scaling + 1);
  604. // s->ave_sum[ch] *= 2;
  605. }
  606. if(s->seekable_tile) {
  607. if(s->do_inter_ch_decorr)
  608. s->channel_residues[ch][0] = get_sbits(&s->gb, s->bits_per_sample + 1);
  609. else
  610. s->channel_residues[ch][0] = get_sbits(&s->gb, s->bits_per_sample);
  611. i++;
  612. }
  613. //av_log(0, 0, "%8d: ", num_logged_tiles++);
  614. for(; i < tile_size; i++) {
  615. int quo = 0, rem, rem_bits, residue;
  616. while(get_bits1(&s->gb))
  617. quo++;
  618. if(quo >= 32)
  619. quo += get_bits_long(&s->gb, get_bits(&s->gb, 5) + 1);
  620. ave_mean = (s->ave_sum[ch] + (1 << s->movave_scaling)) >> (s->movave_scaling + 1);
  621. rem_bits = av_ceil_log2(ave_mean);
  622. rem = rem_bits ? get_bits(&s->gb, rem_bits) : 0;
  623. residue = (quo << rem_bits) + rem;
  624. s->ave_sum[ch] = residue + s->ave_sum[ch] - (s->ave_sum[ch] >> s->movave_scaling);
  625. if(residue & 1)
  626. residue = -(residue >> 1) - 1;
  627. else
  628. residue = residue >> 1;
  629. s->channel_residues[ch][i] = residue;
  630. }
  631. //dump_int_buffer(s->channel_residues[ch], 4, tile_size, 16);
  632. return 0;
  633. }
  634. /**
  635. *
  636. */
  637. static void
  638. decode_lpc(WmallDecodeCtx *s)
  639. {
  640. int ch, i, cbits;
  641. s->lpc_order = get_bits(&s->gb, 5) + 1;
  642. s->lpc_scaling = get_bits(&s->gb, 4);
  643. s->lpc_intbits = get_bits(&s->gb, 3) + 1;
  644. cbits = s->lpc_scaling + s->lpc_intbits;
  645. for(ch = 0; ch < s->num_channels; ch++) {
  646. for(i = 0; i < s->lpc_order; i++) {
  647. s->lpc_coefs[ch][i] = get_sbits(&s->gb, cbits);
  648. }
  649. }
  650. }
  651. static void clear_codec_buffers(WmallDecodeCtx *s)
  652. {
  653. int ich, ilms;
  654. memset(s->acfilter_coeffs , 0, 16 * sizeof(int));
  655. memset(s->acfilter_prevvalues, 0, 16 * 2 * sizeof(int)); // may be wrong
  656. memset(s->lpc_coefs , 0, 40 * 2 * sizeof(int));
  657. memset(s->mclms_coeffs , 0, 128 * sizeof(int16_t));
  658. memset(s->mclms_coeffs_cur, 0, 4 * sizeof(int16_t));
  659. memset(s->mclms_prevvalues, 0, 64 * sizeof(int));
  660. memset(s->mclms_updates , 0, 64 * sizeof(int16_t));
  661. for (ich = 0; ich < s->num_channels; ich++) {
  662. for (ilms = 0; ilms < s->cdlms_ttl[ich]; ilms++) {
  663. memset(s->cdlms[ich][ilms].coefs , 0, 256 * sizeof(int16_t));
  664. memset(s->cdlms[ich][ilms].lms_prevvalues, 0, 512 * sizeof(int16_t));
  665. memset(s->cdlms[ich][ilms].lms_updates , 0, 512 * sizeof(int16_t));
  666. }
  667. s->ave_sum[ich] = 0;
  668. }
  669. }
  670. /**
  671. *@brief Resets filter parameters and transient area at new seekable tile
  672. */
  673. static void reset_codec(WmallDecodeCtx *s)
  674. {
  675. int ich, ilms;
  676. s->mclms_recent = s->mclms_order * s->num_channels;
  677. for (ich = 0; ich < s->num_channels; ich++) {
  678. for (ilms = 0; ilms < s->cdlms_ttl[ich]; ilms++)
  679. s->cdlms[ich][ilms].recent = s->cdlms[ich][ilms].order;
  680. /* first sample of a seekable subframe is considered as the starting of
  681. a transient area which is samples_per_frame samples long */
  682. s->channel[ich].transient_counter = s->samples_per_frame;
  683. s->transient[ich] = 1;
  684. s->transient_pos[ich] = 0;
  685. }
  686. }
  687. static void mclms_update(WmallDecodeCtx *s, int icoef, int *pred)
  688. {
  689. int i, j, ich;
  690. int pred_error;
  691. int order = s->mclms_order;
  692. int num_channels = s->num_channels;
  693. int range = 1 << (s->bits_per_sample - 1);
  694. int bps = s->bits_per_sample > 16 ? 4 : 2; // bytes per sample
  695. for (ich = 0; ich < num_channels; ich++) {
  696. pred_error = s->channel_residues[ich][icoef] - pred[ich];
  697. if (pred_error > 0) {
  698. for (i = 0; i < order * num_channels; i++)
  699. s->mclms_coeffs[i + ich * order * num_channels] +=
  700. s->mclms_updates[s->mclms_recent + i];
  701. for (j = 0; j < ich; j++) {
  702. if (s->channel_residues[j][icoef] > 0)
  703. s->mclms_coeffs_cur[ich * num_channels + j] += 1;
  704. else if (s->channel_residues[j][icoef] < 0)
  705. s->mclms_coeffs_cur[ich * num_channels + j] -= 1;
  706. }
  707. } else if (pred_error < 0) {
  708. for (i = 0; i < order * num_channels; i++)
  709. s->mclms_coeffs[i + ich * order * num_channels] -=
  710. s->mclms_updates[s->mclms_recent + i];
  711. for (j = 0; j < ich; j++) {
  712. if (s->channel_residues[j][icoef] > 0)
  713. s->mclms_coeffs_cur[ich * num_channels + j] -= 1;
  714. else if (s->channel_residues[j][icoef] < 0)
  715. s->mclms_coeffs_cur[ich * num_channels + j] += 1;
  716. }
  717. }
  718. }
  719. for (ich = num_channels - 1; ich >= 0; ich--) {
  720. s->mclms_recent--;
  721. s->mclms_prevvalues[s->mclms_recent] = s->channel_residues[ich][icoef];
  722. if (s->channel_residues[ich][icoef] > range - 1)
  723. s->mclms_prevvalues[s->mclms_recent] = range - 1;
  724. else if (s->channel_residues[ich][icoef] < -range)
  725. s->mclms_prevvalues[s->mclms_recent] = -range;
  726. s->mclms_updates[s->mclms_recent] = 0;
  727. if (s->channel_residues[ich][icoef] > 0)
  728. s->mclms_updates[s->mclms_recent] = 1;
  729. else if (s->channel_residues[ich][icoef] < 0)
  730. s->mclms_updates[s->mclms_recent] = -1;
  731. }
  732. if (s->mclms_recent == 0) {
  733. memcpy(&s->mclms_prevvalues[order * num_channels],
  734. s->mclms_prevvalues,
  735. bps * order * num_channels);
  736. memcpy(&s->mclms_updates[order * num_channels],
  737. s->mclms_updates,
  738. bps * order * num_channels);
  739. s->mclms_recent = num_channels * order;
  740. }
  741. }
  742. static void mclms_predict(WmallDecodeCtx *s, int icoef, int *pred)
  743. {
  744. int ich, i;
  745. int order = s->mclms_order;
  746. int num_channels = s->num_channels;
  747. for (ich = 0; ich < num_channels; ich++) {
  748. if (!s->is_channel_coded[ich])
  749. continue;
  750. pred[ich] = 0;
  751. for (i = 0; i < order * num_channels; i++)
  752. pred[ich] += s->mclms_prevvalues[i + s->mclms_recent] *
  753. s->mclms_coeffs[i + order * num_channels * ich];
  754. for (i = 0; i < ich; i++)
  755. pred[ich] += s->channel_residues[i][icoef] *
  756. s->mclms_coeffs_cur[i + num_channels * ich];
  757. pred[ich] += 1 << s->mclms_scaling - 1;
  758. pred[ich] >>= s->mclms_scaling;
  759. s->channel_residues[ich][icoef] += pred[ich];
  760. }
  761. }
  762. static void revert_mclms(WmallDecodeCtx *s, int tile_size)
  763. {
  764. int icoef, pred[s->num_channels];
  765. for (icoef = 0; icoef < tile_size; icoef++) {
  766. mclms_predict(s, icoef, pred);
  767. mclms_update(s, icoef, pred);
  768. }
  769. }
  770. static int lms_predict(WmallDecodeCtx *s, int ich, int ilms)
  771. {
  772. int pred = 0;
  773. int icoef;
  774. int recent = s->cdlms[ich][ilms].recent;
  775. for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
  776. pred += s->cdlms[ich][ilms].coefs[icoef] *
  777. s->cdlms[ich][ilms].lms_prevvalues[icoef + recent];
  778. //pred += (1 << (s->cdlms[ich][ilms].scaling - 1));
  779. /* XXX: Table 29 has:
  780. iPred >= cdlms[iCh][ilms].scaling;
  781. seems to me like a missing > */
  782. //pred >>= s->cdlms[ich][ilms].scaling;
  783. return pred;
  784. }
  785. static void lms_update(WmallDecodeCtx *s, int ich, int ilms, int input, int residue)
  786. {
  787. int icoef;
  788. int recent = s->cdlms[ich][ilms].recent;
  789. int range = 1 << s->bits_per_sample - 1;
  790. int bps = s->bits_per_sample > 16 ? 4 : 2; // bytes per sample
  791. if (residue < 0) {
  792. for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
  793. s->cdlms[ich][ilms].coefs[icoef] -=
  794. s->cdlms[ich][ilms].lms_updates[icoef + recent];
  795. } else if (residue > 0) {
  796. for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
  797. s->cdlms[ich][ilms].coefs[icoef] +=
  798. s->cdlms[ich][ilms].lms_updates[icoef + recent]; /* spec mistakenly
  799. dropped the recent */
  800. }
  801. if (recent)
  802. recent--;
  803. else {
  804. /* XXX: This memcpy()s will probably fail if a fixed 32-bit buffer is used.
  805. follow kshishkov's suggestion of using a union. */
  806. memcpy(&s->cdlms[ich][ilms].lms_prevvalues[s->cdlms[ich][ilms].order],
  807. s->cdlms[ich][ilms].lms_prevvalues,
  808. bps * s->cdlms[ich][ilms].order);
  809. memcpy(&s->cdlms[ich][ilms].lms_updates[s->cdlms[ich][ilms].order],
  810. s->cdlms[ich][ilms].lms_updates,
  811. bps * s->cdlms[ich][ilms].order);
  812. recent = s->cdlms[ich][ilms].order - 1;
  813. }
  814. s->cdlms[ich][ilms].lms_prevvalues[recent] = av_clip(input, -range, range - 1);
  815. if (!input)
  816. s->cdlms[ich][ilms].lms_updates[recent] = 0;
  817. else if (input < 0)
  818. s->cdlms[ich][ilms].lms_updates[recent] = -s->update_speed[ich];
  819. else
  820. s->cdlms[ich][ilms].lms_updates[recent] = s->update_speed[ich];
  821. /* XXX: spec says:
  822. cdlms[iCh][ilms].updates[iRecent + cdlms[iCh][ilms].order >> 4] >>= 2;
  823. lms_updates[iCh][ilms][iRecent + cdlms[iCh][ilms].order >> 3] >>= 1;
  824. Questions is - are cdlms[iCh][ilms].updates[] and lms_updates[][][] two
  825. seperate buffers? Here I've assumed that the two are same which makes
  826. more sense to me.
  827. */
  828. s->cdlms[ich][ilms].lms_updates[recent + (s->cdlms[ich][ilms].order >> 4)] >>= 2;
  829. s->cdlms[ich][ilms].lms_updates[recent + (s->cdlms[ich][ilms].order >> 3)] >>= 1;
  830. s->cdlms[ich][ilms].recent = recent;
  831. }
  832. static void use_high_update_speed(WmallDecodeCtx *s, int ich)
  833. {
  834. int ilms, recent, icoef;
  835. for (ilms = s->cdlms_ttl[ich] - 1; ilms >= 0; ilms--) {
  836. recent = s->cdlms[ich][ilms].recent;
  837. if (s->update_speed[ich] == 16)
  838. continue;
  839. if (s->bV3RTM) {
  840. for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
  841. s->cdlms[ich][ilms].lms_updates[icoef + recent] *= 2;
  842. } else {
  843. for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
  844. s->cdlms[ich][ilms].lms_updates[icoef] *= 2;
  845. }
  846. }
  847. s->update_speed[ich] = 16;
  848. }
  849. static void use_normal_update_speed(WmallDecodeCtx *s, int ich)
  850. {
  851. int ilms, recent, icoef;
  852. for (ilms = s->cdlms_ttl[ich] - 1; ilms >= 0; ilms--) {
  853. recent = s->cdlms[ich][ilms].recent;
  854. if (s->update_speed[ich] == 8)
  855. continue;
  856. if (s->bV3RTM) {
  857. for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
  858. s->cdlms[ich][ilms].lms_updates[icoef + recent] /= 2;
  859. } else {
  860. for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)
  861. s->cdlms[ich][ilms].lms_updates[icoef] /= 2;
  862. }
  863. }
  864. s->update_speed[ich] = 8;
  865. }
  866. static void revert_cdlms(WmallDecodeCtx *s, int ch, int coef_begin, int coef_end)
  867. {
  868. int icoef;
  869. int pred;
  870. int ilms, num_lms;
  871. int residue, input;
  872. num_lms = s->cdlms_ttl[ch];
  873. for (ilms = num_lms - 1; ilms >= 0; ilms--) {
  874. //s->cdlms[ch][ilms].recent = s->cdlms[ch][ilms].order;
  875. for (icoef = coef_begin; icoef < coef_end; icoef++) {
  876. pred = 1 << (s->cdlms[ch][ilms].scaling - 1);
  877. residue = s->channel_residues[ch][icoef];
  878. pred += lms_predict(s, ch, ilms);
  879. input = residue + (pred >> s->cdlms[ch][ilms].scaling);
  880. lms_update(s, ch, ilms, input, residue);
  881. s->channel_residues[ch][icoef] = input;
  882. }
  883. }
  884. }
  885. static void revert_inter_ch_decorr(WmallDecodeCtx *s, int tile_size)
  886. {
  887. int icoef;
  888. if (s->num_channels != 2)
  889. return;
  890. else {
  891. for (icoef = 0; icoef < tile_size; icoef++) {
  892. s->channel_residues[0][icoef] -= s->channel_residues[1][icoef] >> 1;
  893. s->channel_residues[1][icoef] += s->channel_residues[0][icoef];
  894. }
  895. }
  896. }
  897. static void revert_acfilter(WmallDecodeCtx *s, int tile_size)
  898. {
  899. int ich, icoef;
  900. int pred;
  901. int i, j;
  902. int64_t *filter_coeffs = s->acfilter_coeffs;
  903. int scaling = s->acfilter_scaling;
  904. int order = s->acfilter_order;
  905. for (ich = 0; ich < s->num_channels; ich++) {
  906. int *prevvalues = s->acfilter_prevvalues[ich];
  907. for (i = 0; i < order; i++) {
  908. pred = 0;
  909. for (j = 0; j < order; j++) {
  910. if (i <= j)
  911. pred += filter_coeffs[j] * prevvalues[j - i];
  912. else
  913. pred += s->channel_residues[ich][i - j - 1] * filter_coeffs[j];
  914. }
  915. pred >>= scaling;
  916. s->channel_residues[ich][i] += pred;
  917. }
  918. for (i = order; i < tile_size; i++) {
  919. pred = 0;
  920. for (j = 0; j < order; j++)
  921. pred += s->channel_residues[ich][i - j - 1] * filter_coeffs[j];
  922. pred >>= scaling;
  923. s->channel_residues[ich][i] += pred;
  924. }
  925. for (j = 0; j < order; j++)
  926. prevvalues[j] = s->channel_residues[ich][tile_size - j - 1];
  927. }
  928. }
  929. /**
  930. *@brief Decode a single subframe (block).
  931. *@param s codec context
  932. *@return 0 on success, < 0 when decoding failed
  933. */
  934. static int decode_subframe(WmallDecodeCtx *s)
  935. {
  936. int offset = s->samples_per_frame;
  937. int subframe_len = s->samples_per_frame;
  938. int i, j;
  939. int total_samples = s->samples_per_frame * s->num_channels;
  940. int rawpcm_tile;
  941. int padding_zeroes;
  942. s->subframe_offset = get_bits_count(&s->gb);
  943. /** reset channel context and find the next block offset and size
  944. == the next block of the channel with the smallest number of
  945. decoded samples
  946. */
  947. for (i = 0; i < s->num_channels; i++) {
  948. s->channel[i].grouped = 0;
  949. if (offset > s->channel[i].decoded_samples) {
  950. offset = s->channel[i].decoded_samples;
  951. subframe_len =
  952. s->channel[i].subframe_len[s->channel[i].cur_subframe];
  953. }
  954. }
  955. /** get a list of all channels that contain the estimated block */
  956. s->channels_for_cur_subframe = 0;
  957. for (i = 0; i < s->num_channels; i++) {
  958. const int cur_subframe = s->channel[i].cur_subframe;
  959. /** substract already processed samples */
  960. total_samples -= s->channel[i].decoded_samples;
  961. /** and count if there are multiple subframes that match our profile */
  962. if (offset == s->channel[i].decoded_samples &&
  963. subframe_len == s->channel[i].subframe_len[cur_subframe]) {
  964. total_samples -= s->channel[i].subframe_len[cur_subframe];
  965. s->channel[i].decoded_samples +=
  966. s->channel[i].subframe_len[cur_subframe];
  967. s->channel_indexes_for_cur_subframe[s->channels_for_cur_subframe] = i;
  968. ++s->channels_for_cur_subframe;
  969. }
  970. }
  971. /** check if the frame will be complete after processing the
  972. estimated block */
  973. if (!total_samples)
  974. s->parsed_all_subframes = 1;
  975. s->seekable_tile = get_bits1(&s->gb);
  976. if(s->seekable_tile) {
  977. clear_codec_buffers(s);
  978. s->do_arith_coding = get_bits1(&s->gb);
  979. if(s->do_arith_coding) {
  980. dprintf(s->avctx, "do_arith_coding == 1");
  981. abort();
  982. }
  983. s->do_ac_filter = get_bits1(&s->gb);
  984. s->do_inter_ch_decorr = get_bits1(&s->gb);
  985. s->do_mclms = get_bits1(&s->gb);
  986. if(s->do_ac_filter)
  987. decode_ac_filter(s);
  988. if(s->do_mclms)
  989. decode_mclms(s);
  990. decode_cdlms(s);
  991. s->movave_scaling = get_bits(&s->gb, 3);
  992. s->quant_stepsize = get_bits(&s->gb, 8) + 1;
  993. reset_codec(s);
  994. }
  995. rawpcm_tile = get_bits1(&s->gb);
  996. for(i = 0; i < s->num_channels; i++) {
  997. s->is_channel_coded[i] = 1;
  998. }
  999. if(!rawpcm_tile) {
  1000. for(i = 0; i < s->num_channels; i++) {
  1001. s->is_channel_coded[i] = get_bits1(&s->gb);
  1002. }
  1003. if(s->bV3RTM) {
  1004. // LPC
  1005. s->do_lpc = get_bits1(&s->gb);
  1006. if(s->do_lpc) {
  1007. decode_lpc(s);
  1008. }
  1009. } else {
  1010. s->do_lpc = 0;
  1011. }
  1012. }
  1013. if(get_bits1(&s->gb)) {
  1014. padding_zeroes = get_bits(&s->gb, 5);
  1015. } else {
  1016. padding_zeroes = 0;
  1017. }
  1018. if(rawpcm_tile) {
  1019. int bits = s->bits_per_sample - padding_zeroes;
  1020. dprintf(s->avctx, "RAWPCM %d bits per sample. total %d bits, remain=%d\n", bits,
  1021. bits * s->num_channels * subframe_len, get_bits_count(&s->gb));
  1022. for(i = 0; i < s->num_channels; i++) {
  1023. for(j = 0; j < subframe_len; j++) {
  1024. s->channel_coeffs[i][j] = get_sbits(&s->gb, bits);
  1025. // dprintf(s->avctx, "PCM[%d][%d] = 0x%04x\n", i, j, s->channel_coeffs[i][j]);
  1026. }
  1027. }
  1028. } else {
  1029. for(i = 0; i < s->num_channels; i++)
  1030. if(s->is_channel_coded[i]) {
  1031. decode_channel_residues(s, i, subframe_len);
  1032. if (s->seekable_tile)
  1033. use_high_update_speed(s, i);
  1034. else
  1035. use_normal_update_speed(s, i);
  1036. revert_cdlms(s, i, 0, subframe_len);
  1037. }
  1038. }
  1039. if (s->do_mclms)
  1040. revert_mclms(s, subframe_len);
  1041. if (s->do_inter_ch_decorr)
  1042. revert_inter_ch_decorr(s, subframe_len);
  1043. if(s->do_ac_filter)
  1044. revert_acfilter(s, subframe_len);
  1045. /* Dequantize */
  1046. if (s->quant_stepsize != 1)
  1047. for (i = 0; i < s->num_channels; i++)
  1048. for (j = 0; j < subframe_len; j++)
  1049. s->channel_residues[i][j] *= s->quant_stepsize;
  1050. // Write to proper output buffer depending on bit-depth
  1051. for (i = 0; i < subframe_len; i++)
  1052. for (j = 0; j < s->num_channels; j++) {
  1053. if (s->bits_per_sample == 16)
  1054. *s->samples_16++ = (int16_t) s->channel_residues[j][i];
  1055. else
  1056. *s->samples_32++ = s->channel_residues[j][i];
  1057. }
  1058. /** handled one subframe */
  1059. for (i = 0; i < s->channels_for_cur_subframe; i++) {
  1060. int c = s->channel_indexes_for_cur_subframe[i];
  1061. if (s->channel[c].cur_subframe >= s->channel[c].num_subframes) {
  1062. av_log(s->avctx, AV_LOG_ERROR, "broken subframe\n");
  1063. return AVERROR_INVALIDDATA;
  1064. }
  1065. ++s->channel[c].cur_subframe;
  1066. }
  1067. num_logged_subframes++;
  1068. return 0;
  1069. }
  1070. /**
  1071. *@brief Decode one WMA frame.
  1072. *@param s codec context
  1073. *@return 0 if the trailer bit indicates that this is the last frame,
  1074. * 1 if there are additional frames
  1075. */
  1076. static int decode_frame(WmallDecodeCtx *s)
  1077. {
  1078. GetBitContext* gb = &s->gb;
  1079. int more_frames = 0;
  1080. int len = 0;
  1081. int i;
  1082. int buffer_len;
  1083. /** check for potential output buffer overflow */
  1084. if (s->bits_per_sample == 16)
  1085. buffer_len = s->samples_16_end - s->samples_16;
  1086. else
  1087. buffer_len = s->samples_32_end - s->samples_32;
  1088. if (s->num_channels * s->samples_per_frame > buffer_len) {
  1089. /** return an error if no frame could be decoded at all */
  1090. av_log(s->avctx, AV_LOG_ERROR,
  1091. "not enough space for the output samples\n");
  1092. s->packet_loss = 1;
  1093. return 0;
  1094. }
  1095. /** get frame length */
  1096. if (s->len_prefix)
  1097. len = get_bits(gb, s->log2_frame_size);
  1098. /** decode tile information */
  1099. if (decode_tilehdr(s)) {
  1100. s->packet_loss = 1;
  1101. return 0;
  1102. }
  1103. /** read drc info */
  1104. if (s->dynamic_range_compression) {
  1105. s->drc_gain = get_bits(gb, 8);
  1106. }
  1107. /** no idea what these are for, might be the number of samples
  1108. that need to be skipped at the beginning or end of a stream */
  1109. if (get_bits1(gb)) {
  1110. int skip;
  1111. /** usually true for the first frame */
  1112. if (get_bits1(gb)) {
  1113. skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
  1114. dprintf(s->avctx, "start skip: %i\n", skip);
  1115. }
  1116. /** sometimes true for the last frame */
  1117. if (get_bits1(gb)) {
  1118. skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
  1119. dprintf(s->avctx, "end skip: %i\n", skip);
  1120. }
  1121. }
  1122. /** reset subframe states */
  1123. s->parsed_all_subframes = 0;
  1124. for (i = 0; i < s->num_channels; i++) {
  1125. s->channel[i].decoded_samples = 0;
  1126. s->channel[i].cur_subframe = 0;
  1127. s->channel[i].reuse_sf = 0;
  1128. }
  1129. /** decode all subframes */
  1130. while (!s->parsed_all_subframes) {
  1131. if (decode_subframe(s) < 0) {
  1132. s->packet_loss = 1;
  1133. return 0;
  1134. }
  1135. }
  1136. dprintf(s->avctx, "Frame done\n");
  1137. if (s->skip_frame) {
  1138. s->skip_frame = 0;
  1139. }
  1140. if (s->len_prefix) {
  1141. if (len != (get_bits_count(gb) - s->frame_offset) + 2) {
  1142. /** FIXME: not sure if this is always an error */
  1143. av_log(s->avctx, AV_LOG_ERROR,
  1144. "frame[%i] would have to skip %i bits\n", s->frame_num,
  1145. len - (get_bits_count(gb) - s->frame_offset) - 1);
  1146. s->packet_loss = 1;
  1147. return 0;
  1148. }
  1149. /** skip the rest of the frame data */
  1150. skip_bits_long(gb, len - (get_bits_count(gb) - s->frame_offset) - 1);
  1151. } else {
  1152. /*
  1153. while (get_bits_count(gb) < s->num_saved_bits && get_bits1(gb) == 0) {
  1154. dprintf(s->avctx, "skip1\n");
  1155. }
  1156. */
  1157. }
  1158. /** decode trailer bit */
  1159. more_frames = get_bits1(gb);
  1160. ++s->frame_num;
  1161. return more_frames;
  1162. }
  1163. /**
  1164. *@brief Calculate remaining input buffer length.
  1165. *@param s codec context
  1166. *@param gb bitstream reader context
  1167. *@return remaining size in bits
  1168. */
  1169. static int remaining_bits(WmallDecodeCtx *s, GetBitContext *gb)
  1170. {
  1171. return s->buf_bit_size - get_bits_count(gb);
  1172. }
  1173. /**
  1174. *@brief Fill the bit reservoir with a (partial) frame.
  1175. *@param s codec context
  1176. *@param gb bitstream reader context
  1177. *@param len length of the partial frame
  1178. *@param append decides wether to reset the buffer or not
  1179. */
  1180. static void save_bits(WmallDecodeCtx *s, GetBitContext* gb, int len,
  1181. int append)
  1182. {
  1183. int buflen;
  1184. /** when the frame data does not need to be concatenated, the input buffer
  1185. is resetted and additional bits from the previous frame are copyed
  1186. and skipped later so that a fast byte copy is possible */
  1187. if (!append) {
  1188. s->frame_offset = get_bits_count(gb) & 7;
  1189. s->num_saved_bits = s->frame_offset;
  1190. init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
  1191. }
  1192. buflen = (s->num_saved_bits + len + 8) >> 3;
  1193. if (len <= 0 || buflen > MAX_FRAMESIZE) {
  1194. av_log_ask_for_sample(s->avctx, "input buffer too small\n");
  1195. s->packet_loss = 1;
  1196. return;
  1197. }
  1198. s->num_saved_bits += len;
  1199. if (!append) {
  1200. avpriv_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3),
  1201. s->num_saved_bits);
  1202. } else {
  1203. int align = 8 - (get_bits_count(gb) & 7);
  1204. align = FFMIN(align, len);
  1205. put_bits(&s->pb, align, get_bits(gb, align));
  1206. len -= align;
  1207. avpriv_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3), len);
  1208. }
  1209. skip_bits_long(gb, len);
  1210. {
  1211. PutBitContext tmp = s->pb;
  1212. flush_put_bits(&tmp);
  1213. }
  1214. init_get_bits(&s->gb, s->frame_data, s->num_saved_bits);
  1215. skip_bits(&s->gb, s->frame_offset);
  1216. }
  1217. /**
  1218. *@brief Decode a single WMA packet.
  1219. *@param avctx codec context
  1220. *@param data the output buffer
  1221. *@param data_size number of bytes that were written to the output buffer
  1222. *@param avpkt input packet
  1223. *@return number of bytes that were read from the input buffer
  1224. */
  1225. static int decode_packet(AVCodecContext *avctx,
  1226. void *data, int *data_size, AVPacket* avpkt)
  1227. {
  1228. WmallDecodeCtx *s = avctx->priv_data;
  1229. GetBitContext* gb = &s->pgb;
  1230. const uint8_t* buf = avpkt->data;
  1231. int buf_size = avpkt->size;
  1232. int num_bits_prev_frame;
  1233. int packet_sequence_number;
  1234. if (s->bits_per_sample == 16) {
  1235. s->samples_16 = (int16_t *) data;
  1236. s->samples_16_end = (int16_t *) ((int8_t*)data + *data_size);
  1237. } else {
  1238. s->samples_32 = (void *) data;
  1239. s->samples_32_end = (void *) ((int8_t*)data + *data_size);
  1240. }
  1241. *data_size = 0;
  1242. if (s->packet_done || s->packet_loss) {
  1243. int seekable_frame_in_packet, spliced_packet;
  1244. s->packet_done = 0;
  1245. /** sanity check for the buffer length */
  1246. if (buf_size < avctx->block_align)
  1247. return 0;
  1248. s->next_packet_start = buf_size - avctx->block_align;
  1249. buf_size = avctx->block_align;
  1250. s->buf_bit_size = buf_size << 3;
  1251. /** parse packet header */
  1252. init_get_bits(gb, buf, s->buf_bit_size);
  1253. packet_sequence_number = get_bits(gb, 4);
  1254. seekable_frame_in_packet = get_bits1(gb);
  1255. spliced_packet = get_bits1(gb);
  1256. /** get number of bits that need to be added to the previous frame */
  1257. num_bits_prev_frame = get_bits(gb, s->log2_frame_size);
  1258. /** check for packet loss */
  1259. if (!s->packet_loss &&
  1260. ((s->packet_sequence_number + 1) & 0xF) != packet_sequence_number) {
  1261. s->packet_loss = 1;
  1262. av_log(avctx, AV_LOG_ERROR, "Packet loss detected! seq %x vs %x\n",
  1263. s->packet_sequence_number, packet_sequence_number);
  1264. }
  1265. s->packet_sequence_number = packet_sequence_number;
  1266. if (num_bits_prev_frame > 0) {
  1267. int remaining_packet_bits = s->buf_bit_size - get_bits_count(gb);
  1268. if (num_bits_prev_frame >= remaining_packet_bits) {
  1269. num_bits_prev_frame = remaining_packet_bits;
  1270. s->packet_done = 1;
  1271. }
  1272. /** append the previous frame data to the remaining data from the
  1273. previous packet to create a full frame */
  1274. save_bits(s, gb, num_bits_prev_frame, 1);
  1275. /** decode the cross packet frame if it is valid */
  1276. if (!s->packet_loss)
  1277. decode_frame(s);
  1278. } else if (s->num_saved_bits - s->frame_offset) {
  1279. dprintf(avctx, "ignoring %x previously saved bits\n",
  1280. s->num_saved_bits - s->frame_offset);
  1281. }
  1282. if (s->packet_loss) {
  1283. /** reset number of saved bits so that the decoder
  1284. does not start to decode incomplete frames in the
  1285. s->len_prefix == 0 case */
  1286. s->num_saved_bits = 0;
  1287. s->packet_loss = 0;
  1288. }
  1289. } else {
  1290. int frame_size;
  1291. s->buf_bit_size = (avpkt->size - s->next_packet_start) << 3;
  1292. init_get_bits(gb, avpkt->data, s->buf_bit_size);
  1293. skip_bits(gb, s->packet_offset);
  1294. if (s->len_prefix && remaining_bits(s, gb) > s->log2_frame_size &&
  1295. (frame_size = show_bits(gb, s->log2_frame_size)) &&
  1296. frame_size <= remaining_bits(s, gb)) {
  1297. save_bits(s, gb, frame_size, 0);
  1298. s->packet_done = !decode_frame(s);
  1299. } else if (!s->len_prefix
  1300. && s->num_saved_bits > get_bits_count(&s->gb)) {
  1301. /** when the frames do not have a length prefix, we don't know
  1302. the compressed length of the individual frames
  1303. however, we know what part of a new packet belongs to the
  1304. previous frame
  1305. therefore we save the incoming packet first, then we append
  1306. the "previous frame" data from the next packet so that
  1307. we get a buffer that only contains full frames */
  1308. s->packet_done = !decode_frame(s);
  1309. } else {
  1310. s->packet_done = 1;
  1311. }
  1312. }
  1313. if (s->packet_done && !s->packet_loss &&
  1314. remaining_bits(s, gb) > 0) {
  1315. /** save the rest of the data so that it can be decoded
  1316. with the next packet */
  1317. save_bits(s, gb, remaining_bits(s, gb), 0);
  1318. }
  1319. if (s->bits_per_sample == 16)
  1320. *data_size = (int8_t *)s->samples_16 - (int8_t *)data;
  1321. else
  1322. *data_size = (int8_t *)s->samples_32 - (int8_t *)data;
  1323. s->packet_offset = get_bits_count(gb) & 7;
  1324. return (s->packet_loss) ? AVERROR_INVALIDDATA : get_bits_count(gb) >> 3;
  1325. }
  1326. /**
  1327. *@brief Clear decoder buffers (for seeking).
  1328. *@param avctx codec context
  1329. */
  1330. static void flush(AVCodecContext *avctx)
  1331. {
  1332. WmallDecodeCtx *s = avctx->priv_data;
  1333. int i;
  1334. /** reset output buffer as a part of it is used during the windowing of a
  1335. new frame */
  1336. for (i = 0; i < s->num_channels; i++)
  1337. memset(s->channel[i].out, 0, s->samples_per_frame *
  1338. sizeof(*s->channel[i].out));
  1339. s->packet_loss = 1;
  1340. }
  1341. /**
  1342. *@brief wmall decoder
  1343. */
  1344. AVCodec ff_wmalossless_decoder = {
  1345. "wmalossless",
  1346. AVMEDIA_TYPE_AUDIO,
  1347. CODEC_ID_WMALOSSLESS,
  1348. sizeof(WmallDecodeCtx),
  1349. decode_init,
  1350. NULL,
  1351. decode_end,
  1352. decode_packet,
  1353. .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_EXPERIMENTAL,
  1354. .flush= flush,
  1355. .long_name = NULL_IF_CONFIG_SMALL("Windows Media Audio 9 Lossless"),
  1356. };