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.

1171 lines
42KB

  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. } WmallChannelCtx;
  135. /**
  136. * @brief channel group for channel transformations
  137. */
  138. typedef struct {
  139. uint8_t num_channels; ///< number of channels in the group
  140. int8_t transform; ///< transform on / off
  141. int8_t transform_band[MAX_BANDS]; ///< controls if the transform is enabled for a certain band
  142. float decorrelation_matrix[WMALL_MAX_CHANNELS*WMALL_MAX_CHANNELS];
  143. float* channel_data[WMALL_MAX_CHANNELS]; ///< transformation coefficients
  144. } WmallChannelGrp;
  145. /**
  146. * @brief main decoder context
  147. */
  148. typedef struct WmallDecodeCtx {
  149. /* generic decoder variables */
  150. AVCodecContext* avctx; ///< codec context for av_log
  151. DSPContext dsp; ///< accelerated DSP functions
  152. uint8_t frame_data[MAX_FRAMESIZE +
  153. FF_INPUT_BUFFER_PADDING_SIZE];///< compressed frame data
  154. PutBitContext pb; ///< context for filling the frame_data buffer
  155. FFTContext mdct_ctx[WMALL_BLOCK_SIZES]; ///< MDCT context per block size
  156. DECLARE_ALIGNED(16, float, tmp)[WMALL_BLOCK_MAX_SIZE]; ///< IMDCT output buffer
  157. float* windows[WMALL_BLOCK_SIZES]; ///< windows for the different block sizes
  158. /* frame size dependent frame information (set during initialization) */
  159. uint32_t decode_flags; ///< used compression features
  160. uint8_t len_prefix; ///< frame is prefixed with its length
  161. uint8_t dynamic_range_compression; ///< frame contains DRC data
  162. uint8_t bits_per_sample; ///< integer audio sample size for the unscaled IMDCT output (used to scale to [-1.0, 1.0])
  163. uint16_t samples_per_frame; ///< number of samples to output
  164. uint16_t log2_frame_size;
  165. int8_t num_channels; ///< number of channels in the stream (same as AVCodecContext.num_channels)
  166. int8_t lfe_channel; ///< lfe channel index
  167. uint8_t max_num_subframes;
  168. uint8_t subframe_len_bits; ///< number of bits used for the subframe length
  169. uint8_t max_subframe_len_bit; ///< flag indicating that the subframe is of maximum size when the first subframe length bit is 1
  170. uint16_t min_samples_per_subframe;
  171. int8_t num_sfb[WMALL_BLOCK_SIZES]; ///< scale factor bands per block size
  172. int16_t sfb_offsets[WMALL_BLOCK_SIZES][MAX_BANDS]; ///< scale factor band offsets (multiples of 4)
  173. int8_t sf_offsets[WMALL_BLOCK_SIZES][WMALL_BLOCK_SIZES][MAX_BANDS]; ///< scale factor resample matrix
  174. int16_t subwoofer_cutoffs[WMALL_BLOCK_SIZES]; ///< subwoofer cutoff values
  175. /* packet decode state */
  176. GetBitContext pgb; ///< bitstream reader context for the packet
  177. int next_packet_start; ///< start offset of the next wma packet in the demuxer packet
  178. uint8_t packet_offset; ///< frame offset in the packet
  179. uint8_t packet_sequence_number; ///< current packet number
  180. int num_saved_bits; ///< saved number of bits
  181. int frame_offset; ///< frame offset in the bit reservoir
  182. int subframe_offset; ///< subframe offset in the bit reservoir
  183. uint8_t packet_loss; ///< set in case of bitstream error
  184. uint8_t packet_done; ///< set when a packet is fully decoded
  185. /* frame decode state */
  186. uint32_t frame_num; ///< current frame number (not used for decoding)
  187. GetBitContext gb; ///< bitstream reader context
  188. int buf_bit_size; ///< buffer size in bits
  189. float* samples; ///< current samplebuffer pointer
  190. float* samples_end; ///< maximum samplebuffer pointer
  191. uint8_t drc_gain; ///< gain for the DRC tool
  192. int8_t skip_frame; ///< skip output step
  193. int8_t parsed_all_subframes; ///< all subframes decoded?
  194. /* subframe/block decode state */
  195. int16_t subframe_len; ///< current subframe length
  196. int8_t channels_for_cur_subframe; ///< number of channels that contain the subframe
  197. int8_t channel_indexes_for_cur_subframe[WMALL_MAX_CHANNELS];
  198. int8_t num_bands; ///< number of scale factor bands
  199. int8_t transmit_num_vec_coeffs; ///< number of vector coded coefficients is part of the bitstream
  200. int16_t* cur_sfb_offsets; ///< sfb offsets for the current block
  201. uint8_t table_idx; ///< index for the num_sfb, sfb_offsets, sf_offsets and subwoofer_cutoffs tables
  202. int8_t esc_len; ///< length of escaped coefficients
  203. uint8_t num_chgroups; ///< number of channel groups
  204. WmallChannelGrp chgroup[WMALL_MAX_CHANNELS]; ///< channel group information
  205. WmallChannelCtx channel[WMALL_MAX_CHANNELS]; ///< per channel data
  206. // WMA lossless
  207. uint8_t do_arith_coding;
  208. uint8_t do_ac_filter;
  209. uint8_t do_inter_ch_decorr;
  210. uint8_t do_mclms;
  211. uint8_t do_lpc;
  212. int8_t acfilter_order;
  213. int8_t acfilter_scaling;
  214. int acfilter_coeffs[16];
  215. int8_t mclms_order;
  216. int8_t mclms_scaling;
  217. int16_t mclms_coeffs[128];
  218. int16_t mclms_coeffs_cur[4];
  219. int movave_scaling;
  220. int quant_stepsize;
  221. struct {
  222. int order;
  223. int scaling;
  224. int coefsend;
  225. int bitsend;
  226. int16_t coefs[256];
  227. } cdlms[2][9];
  228. int cdlms_ttl[2];
  229. int bV3RTM;
  230. int is_channel_coded[2];
  231. int transient[2];
  232. int transient_pos[2];
  233. int seekable_tile;
  234. int ave_sum[2];
  235. int channel_residues[2][2048];
  236. int lpc_coefs[2][40];
  237. int lpc_order;
  238. int lpc_scaling;
  239. int lpc_intbits;
  240. int channel_coeffs[2][2048];
  241. } WmallDecodeCtx;
  242. #undef dprintf
  243. #define dprintf(pctx, ...) av_log(pctx, AV_LOG_DEBUG, __VA_ARGS__)
  244. /**
  245. *@brief helper function to print the most important members of the context
  246. *@param s context
  247. */
  248. static void av_cold dump_context(WmallDecodeCtx *s)
  249. {
  250. #define PRINT(a, b) av_log(s->avctx, AV_LOG_DEBUG, " %s = %d\n", a, b);
  251. #define PRINT_HEX(a, b) av_log(s->avctx, AV_LOG_DEBUG, " %s = %x\n", a, b);
  252. PRINT("ed sample bit depth", s->bits_per_sample);
  253. PRINT_HEX("ed decode flags", s->decode_flags);
  254. PRINT("samples per frame", s->samples_per_frame);
  255. PRINT("log2 frame size", s->log2_frame_size);
  256. PRINT("max num subframes", s->max_num_subframes);
  257. PRINT("len prefix", s->len_prefix);
  258. PRINT("num channels", s->num_channels);
  259. }
  260. /**
  261. *@brief Uninitialize the decoder and free all resources.
  262. *@param avctx codec context
  263. *@return 0 on success, < 0 otherwise
  264. */
  265. static av_cold int decode_end(AVCodecContext *avctx)
  266. {
  267. WmallDecodeCtx *s = avctx->priv_data;
  268. int i;
  269. for (i = 0; i < WMALL_BLOCK_SIZES; i++)
  270. ff_mdct_end(&s->mdct_ctx[i]);
  271. return 0;
  272. }
  273. /**
  274. *@brief Initialize the decoder.
  275. *@param avctx codec context
  276. *@return 0 on success, -1 otherwise
  277. */
  278. static av_cold int decode_init(AVCodecContext *avctx)
  279. {
  280. WmallDecodeCtx *s = avctx->priv_data;
  281. uint8_t *edata_ptr = avctx->extradata;
  282. unsigned int channel_mask;
  283. int i;
  284. int log2_max_num_subframes;
  285. int num_possible_block_sizes;
  286. s->avctx = avctx;
  287. dsputil_init(&s->dsp, avctx);
  288. init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
  289. avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
  290. if (avctx->extradata_size >= 18) {
  291. s->decode_flags = AV_RL16(edata_ptr+14);
  292. channel_mask = AV_RL32(edata_ptr+2);
  293. s->bits_per_sample = AV_RL16(edata_ptr);
  294. /** dump the extradata */
  295. for (i = 0; i < avctx->extradata_size; i++)
  296. dprintf(avctx, "[%x] ", avctx->extradata[i]);
  297. dprintf(avctx, "\n");
  298. } else {
  299. av_log_ask_for_sample(avctx, "Unknown extradata size\n");
  300. return AVERROR_INVALIDDATA;
  301. }
  302. /** generic init */
  303. s->log2_frame_size = av_log2(avctx->block_align) + 4;
  304. /** frame info */
  305. s->skip_frame = 1; /* skip first frame */
  306. s->packet_loss = 1;
  307. s->len_prefix = (s->decode_flags & 0x40);
  308. /** get frame len */
  309. s->samples_per_frame = 1 << ff_wma_get_frame_len_bits(avctx->sample_rate,
  310. 3, s->decode_flags);
  311. /** init previous block len */
  312. for (i = 0; i < avctx->channels; i++)
  313. s->channel[i].prev_block_len = s->samples_per_frame;
  314. /** subframe info */
  315. log2_max_num_subframes = ((s->decode_flags & 0x38) >> 3);
  316. s->max_num_subframes = 1 << log2_max_num_subframes;
  317. s->max_subframe_len_bit = 0;
  318. s->subframe_len_bits = av_log2(log2_max_num_subframes) + 1;
  319. num_possible_block_sizes = log2_max_num_subframes + 1;
  320. s->min_samples_per_subframe = s->samples_per_frame / s->max_num_subframes;
  321. s->dynamic_range_compression = (s->decode_flags & 0x80);
  322. s->bV3RTM = s->decode_flags & 0x100;
  323. if (s->max_num_subframes > MAX_SUBFRAMES) {
  324. av_log(avctx, AV_LOG_ERROR, "invalid number of subframes %i\n",
  325. s->max_num_subframes);
  326. return AVERROR_INVALIDDATA;
  327. }
  328. s->num_channels = avctx->channels;
  329. /** extract lfe channel position */
  330. s->lfe_channel = -1;
  331. if (channel_mask & 8) {
  332. unsigned int mask;
  333. for (mask = 1; mask < 16; mask <<= 1) {
  334. if (channel_mask & mask)
  335. ++s->lfe_channel;
  336. }
  337. }
  338. if (s->num_channels < 0) {
  339. av_log(avctx, AV_LOG_ERROR, "invalid number of channels %d\n", s->num_channels);
  340. return AVERROR_INVALIDDATA;
  341. } else if (s->num_channels > WMALL_MAX_CHANNELS) {
  342. av_log_ask_for_sample(avctx, "unsupported number of channels\n");
  343. return AVERROR_PATCHWELCOME;
  344. }
  345. avctx->channel_layout = channel_mask;
  346. return 0;
  347. }
  348. /**
  349. *@brief Decode the subframe length.
  350. *@param s context
  351. *@param offset sample offset in the frame
  352. *@return decoded subframe length on success, < 0 in case of an error
  353. */
  354. static int decode_subframe_length(WmallDecodeCtx *s, int offset)
  355. {
  356. int frame_len_ratio;
  357. int subframe_len, len;
  358. /** no need to read from the bitstream when only one length is possible */
  359. if (offset == s->samples_per_frame - s->min_samples_per_subframe)
  360. return s->min_samples_per_subframe;
  361. len = av_log2(s->max_num_subframes - 1) + 1;
  362. frame_len_ratio = get_bits(&s->gb, len);
  363. subframe_len = s->min_samples_per_subframe * (frame_len_ratio + 1);
  364. /** sanity check the length */
  365. if (subframe_len < s->min_samples_per_subframe ||
  366. subframe_len > s->samples_per_frame) {
  367. av_log(s->avctx, AV_LOG_ERROR, "broken frame: subframe_len %i\n",
  368. subframe_len);
  369. return AVERROR_INVALIDDATA;
  370. }
  371. return subframe_len;
  372. }
  373. /**
  374. *@brief Decode how the data in the frame is split into subframes.
  375. * Every WMA frame contains the encoded data for a fixed number of
  376. * samples per channel. The data for every channel might be split
  377. * into several subframes. This function will reconstruct the list of
  378. * subframes for every channel.
  379. *
  380. * If the subframes are not evenly split, the algorithm estimates the
  381. * channels with the lowest number of total samples.
  382. * Afterwards, for each of these channels a bit is read from the
  383. * bitstream that indicates if the channel contains a subframe with the
  384. * next subframe size that is going to be read from the bitstream or not.
  385. * If a channel contains such a subframe, the subframe size gets added to
  386. * the channel's subframe list.
  387. * The algorithm repeats these steps until the frame is properly divided
  388. * between the individual channels.
  389. *
  390. *@param s context
  391. *@return 0 on success, < 0 in case of an error
  392. */
  393. static int decode_tilehdr(WmallDecodeCtx *s)
  394. {
  395. uint16_t num_samples[WMALL_MAX_CHANNELS]; /**< sum of samples for all currently known subframes of a channel */
  396. uint8_t contains_subframe[WMALL_MAX_CHANNELS]; /**< flag indicating if a channel contains the current subframe */
  397. int channels_for_cur_subframe = s->num_channels; /**< number of channels that contain the current subframe */
  398. int fixed_channel_layout = 0; /**< flag indicating that all channels use the same subfra2me offsets and sizes */
  399. int min_channel_len = 0; /**< smallest sum of samples (channels with this length will be processed first) */
  400. int c;
  401. /* Should never consume more than 3073 bits (256 iterations for the
  402. * while loop when always the minimum amount of 128 samples is substracted
  403. * from missing samples in the 8 channel case).
  404. * 1 + BLOCK_MAX_SIZE * MAX_CHANNELS / BLOCK_MIN_SIZE * (MAX_CHANNELS + 4)
  405. */
  406. /** reset tiling information */
  407. for (c = 0; c < s->num_channels; c++)
  408. s->channel[c].num_subframes = 0;
  409. memset(num_samples, 0, sizeof(num_samples));
  410. if (s->max_num_subframes == 1 || get_bits1(&s->gb))
  411. fixed_channel_layout = 1;
  412. /** loop until the frame data is split between the subframes */
  413. do {
  414. int subframe_len;
  415. /** check which channels contain the subframe */
  416. for (c = 0; c < s->num_channels; c++) {
  417. if (num_samples[c] == min_channel_len) {
  418. if (fixed_channel_layout || channels_for_cur_subframe == 1 ||
  419. (min_channel_len == s->samples_per_frame - s->min_samples_per_subframe)) {
  420. contains_subframe[c] = 1;
  421. }
  422. else {
  423. contains_subframe[c] = get_bits1(&s->gb);
  424. }
  425. } else
  426. contains_subframe[c] = 0;
  427. }
  428. /** get subframe length, subframe_len == 0 is not allowed */
  429. if ((subframe_len = decode_subframe_length(s, min_channel_len)) <= 0)
  430. return AVERROR_INVALIDDATA;
  431. /** add subframes to the individual channels and find new min_channel_len */
  432. min_channel_len += subframe_len;
  433. for (c = 0; c < s->num_channels; c++) {
  434. WmallChannelCtx* chan = &s->channel[c];
  435. if (contains_subframe[c]) {
  436. if (chan->num_subframes >= MAX_SUBFRAMES) {
  437. av_log(s->avctx, AV_LOG_ERROR,
  438. "broken frame: num subframes > 31\n");
  439. return AVERROR_INVALIDDATA;
  440. }
  441. chan->subframe_len[chan->num_subframes] = subframe_len;
  442. num_samples[c] += subframe_len;
  443. ++chan->num_subframes;
  444. if (num_samples[c] > s->samples_per_frame) {
  445. av_log(s->avctx, AV_LOG_ERROR, "broken frame: "
  446. "channel len(%d) > samples_per_frame(%d)\n",
  447. num_samples[c], s->samples_per_frame);
  448. return AVERROR_INVALIDDATA;
  449. }
  450. } else if (num_samples[c] <= min_channel_len) {
  451. if (num_samples[c] < min_channel_len) {
  452. channels_for_cur_subframe = 0;
  453. min_channel_len = num_samples[c];
  454. }
  455. ++channels_for_cur_subframe;
  456. }
  457. }
  458. } while (min_channel_len < s->samples_per_frame);
  459. for (c = 0; c < s->num_channels; c++) {
  460. int i;
  461. int offset = 0;
  462. for (i = 0; i < s->channel[c].num_subframes; i++) {
  463. s->channel[c].subframe_offset[i] = offset;
  464. offset += s->channel[c].subframe_len[i];
  465. }
  466. }
  467. return 0;
  468. }
  469. static int my_log2(unsigned int i)
  470. {
  471. unsigned int iLog2 = 0;
  472. while ((i >> iLog2) > 1)
  473. iLog2++;
  474. return iLog2;
  475. }
  476. /**
  477. *
  478. */
  479. static void decode_ac_filter(WmallDecodeCtx *s)
  480. {
  481. int i;
  482. s->acfilter_order = get_bits(&s->gb, 4) + 1;
  483. s->acfilter_scaling = get_bits(&s->gb, 4);
  484. for(i = 0; i < s->acfilter_order; i++) {
  485. s->acfilter_coeffs[i] = get_bits(&s->gb, s->acfilter_scaling) + 1;
  486. }
  487. }
  488. /**
  489. *
  490. */
  491. static void decode_mclms(WmallDecodeCtx *s)
  492. {
  493. s->mclms_order = (get_bits(&s->gb, 4) + 1) * 2;
  494. s->mclms_scaling = get_bits(&s->gb, 4);
  495. if(get_bits1(&s->gb)) {
  496. // mclms_send_coef
  497. int i;
  498. int send_coef_bits;
  499. int cbits = av_log2(s->mclms_scaling + 1);
  500. assert(cbits == my_log2(s->mclms_scaling + 1));
  501. if(1 << cbits < s->mclms_scaling + 1)
  502. cbits++;
  503. send_coef_bits = (cbits ? get_bits(&s->gb, cbits) : 0) + 2;
  504. for(i = 0; i < s->mclms_order * s->num_channels * s->num_channels; i++) {
  505. s->mclms_coeffs[i] = get_bits(&s->gb, send_coef_bits);
  506. }
  507. for(i = 0; i < s->num_channels; i++) {
  508. int c;
  509. for(c = 0; c < i; c++) {
  510. s->mclms_coeffs_cur[i * s->num_channels + c] = get_bits(&s->gb, send_coef_bits);
  511. }
  512. }
  513. }
  514. }
  515. /**
  516. *
  517. */
  518. static void decode_cdlms(WmallDecodeCtx *s)
  519. {
  520. int c, i;
  521. int cdlms_send_coef = get_bits1(&s->gb);
  522. for(c = 0; c < s->num_channels; c++) {
  523. s->cdlms_ttl[c] = get_bits(&s->gb, 3) + 1;
  524. for(i = 0; i < s->cdlms_ttl[c]; i++) {
  525. s->cdlms[c][i].order = (get_bits(&s->gb, 7) + 1) * 8;
  526. }
  527. for(i = 0; i < s->cdlms_ttl[c]; i++) {
  528. s->cdlms[c][i].scaling = get_bits(&s->gb, 4);
  529. }
  530. if(cdlms_send_coef) {
  531. for(i = 0; i < s->cdlms_ttl[c]; i++) {
  532. int cbits, shift_l, shift_r, j;
  533. cbits = av_log2(s->cdlms[c][i].order);
  534. if(1 << cbits < s->cdlms[c][i].order)
  535. cbits++;
  536. s->cdlms[c][i].coefsend = get_bits(&s->gb, cbits) + 1;
  537. cbits = av_log2(s->cdlms[c][i].scaling + 1);
  538. if(1 << cbits < s->cdlms[c][i].scaling + 1)
  539. cbits++;
  540. s->cdlms[c][i].bitsend = get_bits(&s->gb, cbits) + 2;
  541. shift_l = 32 - s->cdlms[c][i].bitsend;
  542. shift_r = 32 - 2 - s->cdlms[c][i].scaling;
  543. for(j = 0; j < s->cdlms[c][i].coefsend; j++) {
  544. s->cdlms[c][i].coefs[j] =
  545. (get_bits(&s->gb, s->cdlms[c][i].bitsend) << shift_l) >> shift_r;
  546. }
  547. }
  548. }
  549. }
  550. }
  551. /**
  552. *
  553. */
  554. static int decode_channel_residues(WmallDecodeCtx *s, int ch, int tile_size)
  555. {
  556. int i = 0;
  557. unsigned int ave_mean;
  558. s->transient[ch] = get_bits1(&s->gb);
  559. if(s->transient[ch])
  560. s->transient_pos[ch] = get_bits(&s->gb, av_log2(tile_size));
  561. if(s->seekable_tile) {
  562. ave_mean = get_bits(&s->gb, s->bits_per_sample);
  563. s->ave_sum[ch] = ave_mean << (s->movave_scaling + 1);
  564. // s->ave_sum[ch] *= 2;
  565. }
  566. if(s->seekable_tile) {
  567. if(s->do_inter_ch_decorr)
  568. s->channel_residues[ch][0] = get_sbits(&s->gb, s->bits_per_sample + 1);
  569. else
  570. s->channel_residues[ch][0] = get_sbits(&s->gb, s->bits_per_sample);
  571. i++;
  572. }
  573. for(; i < tile_size; i++) {
  574. int quo = 0, rem, rem_bits, residue;
  575. while(get_bits1(&s->gb))
  576. quo++;
  577. if(quo >= 32)
  578. quo += get_bits_long(&s->gb, get_bits(&s->gb, 5) + 1);
  579. ave_mean = (s->ave_sum[ch] + (1 << s->movave_scaling)) >> (s->movave_scaling + 1);
  580. rem_bits = av_ceil_log2(ave_mean);
  581. rem = rem_bits ? get_bits(&s->gb, rem_bits) : 0;
  582. residue = (quo << rem_bits) + rem;
  583. s->ave_sum[ch] = residue + s->ave_sum[ch] - (s->ave_sum[ch] >> s->movave_scaling);
  584. if(residue & 1)
  585. residue = -(residue >> 1) - 1;
  586. else
  587. residue = residue >> 1;
  588. s->channel_residues[ch][i] = residue;
  589. // dprintf(s->avctx, "%5d: %5d %10d %12d %12d %5d %-16d %04x\n",i, quo, ave_mean, s->ave_sum[ch], rem, rem_bits, s->channel_residues[ch][i], show_bits(&s->gb, 16));
  590. }
  591. return 0;
  592. }
  593. /**
  594. *
  595. */
  596. static void
  597. decode_lpc(WmallDecodeCtx *s)
  598. {
  599. int ch, i, cbits;
  600. s->lpc_order = get_bits(&s->gb, 5) + 1;
  601. s->lpc_scaling = get_bits(&s->gb, 4);
  602. s->lpc_intbits = get_bits(&s->gb, 3) + 1;
  603. cbits = s->lpc_scaling + s->lpc_intbits;
  604. for(ch = 0; ch < s->num_channels; ch++) {
  605. for(i = 0; i < s->lpc_order; i++) {
  606. s->lpc_coefs[ch][i] = get_sbits(&s->gb, cbits);
  607. }
  608. }
  609. }
  610. /**
  611. *@brief Decode a single subframe (block).
  612. *@param s codec context
  613. *@return 0 on success, < 0 when decoding failed
  614. */
  615. static int decode_subframe(WmallDecodeCtx *s)
  616. {
  617. int offset = s->samples_per_frame;
  618. int subframe_len = s->samples_per_frame;
  619. int i;
  620. int total_samples = s->samples_per_frame * s->num_channels;
  621. int rawpcm_tile;
  622. int padding_zeroes;
  623. s->subframe_offset = get_bits_count(&s->gb);
  624. /** reset channel context and find the next block offset and size
  625. == the next block of the channel with the smallest number of
  626. decoded samples
  627. */
  628. for (i = 0; i < s->num_channels; i++) {
  629. s->channel[i].grouped = 0;
  630. if (offset > s->channel[i].decoded_samples) {
  631. offset = s->channel[i].decoded_samples;
  632. subframe_len =
  633. s->channel[i].subframe_len[s->channel[i].cur_subframe];
  634. }
  635. }
  636. /** get a list of all channels that contain the estimated block */
  637. s->channels_for_cur_subframe = 0;
  638. for (i = 0; i < s->num_channels; i++) {
  639. const int cur_subframe = s->channel[i].cur_subframe;
  640. /** substract already processed samples */
  641. total_samples -= s->channel[i].decoded_samples;
  642. /** and count if there are multiple subframes that match our profile */
  643. if (offset == s->channel[i].decoded_samples &&
  644. subframe_len == s->channel[i].subframe_len[cur_subframe]) {
  645. total_samples -= s->channel[i].subframe_len[cur_subframe];
  646. s->channel[i].decoded_samples +=
  647. s->channel[i].subframe_len[cur_subframe];
  648. s->channel_indexes_for_cur_subframe[s->channels_for_cur_subframe] = i;
  649. ++s->channels_for_cur_subframe;
  650. }
  651. }
  652. /** check if the frame will be complete after processing the
  653. estimated block */
  654. if (!total_samples)
  655. s->parsed_all_subframes = 1;
  656. s->seekable_tile = get_bits1(&s->gb);
  657. if(s->seekable_tile) {
  658. s->do_arith_coding = get_bits1(&s->gb);
  659. if(s->do_arith_coding) {
  660. dprintf(s->avctx, "do_arith_coding == 1");
  661. abort();
  662. }
  663. s->do_ac_filter = get_bits1(&s->gb);
  664. s->do_inter_ch_decorr = get_bits1(&s->gb);
  665. s->do_mclms = get_bits1(&s->gb);
  666. if(s->do_ac_filter)
  667. decode_ac_filter(s);
  668. if(s->do_mclms)
  669. decode_mclms(s);
  670. decode_cdlms(s);
  671. s->movave_scaling = get_bits(&s->gb, 3);
  672. s->quant_stepsize = get_bits(&s->gb, 8) + 1;
  673. }
  674. rawpcm_tile = get_bits1(&s->gb);
  675. for(i = 0; i < s->num_channels; i++) {
  676. s->is_channel_coded[i] = 1;
  677. }
  678. if(!rawpcm_tile) {
  679. for(i = 0; i < s->num_channels; i++) {
  680. s->is_channel_coded[i] = get_bits1(&s->gb);
  681. }
  682. if(s->bV3RTM) {
  683. // LPC
  684. s->do_lpc = get_bits1(&s->gb);
  685. if(s->do_lpc) {
  686. decode_lpc(s);
  687. }
  688. } else {
  689. s->do_lpc = 0;
  690. }
  691. }
  692. if(get_bits1(&s->gb)) {
  693. padding_zeroes = get_bits(&s->gb, 5);
  694. } else {
  695. padding_zeroes = 0;
  696. }
  697. if(rawpcm_tile) {
  698. int bits = s->bits_per_sample - padding_zeroes;
  699. int j;
  700. dprintf(s->avctx, "RAWPCM %d bits per sample. total %d bits, remain=%d\n", bits,
  701. bits * s->num_channels * subframe_len, get_bits_count(&s->gb));
  702. for(i = 0; i < s->num_channels; i++) {
  703. for(j = 0; j < subframe_len; j++) {
  704. s->channel_coeffs[i][j] = get_sbits(&s->gb, bits);
  705. // dprintf(s->avctx, "PCM[%d][%d] = 0x%04x\n", i, j, s->channel_coeffs[i][j]);
  706. }
  707. }
  708. } else {
  709. for(i = 0; i < s->num_channels; i++)
  710. if(s->is_channel_coded[i])
  711. decode_channel_residues(s, i, subframe_len);
  712. }
  713. /** handled one subframe */
  714. for (i = 0; i < s->channels_for_cur_subframe; i++) {
  715. int c = s->channel_indexes_for_cur_subframe[i];
  716. if (s->channel[c].cur_subframe >= s->channel[c].num_subframes) {
  717. av_log(s->avctx, AV_LOG_ERROR, "broken subframe\n");
  718. return AVERROR_INVALIDDATA;
  719. }
  720. ++s->channel[c].cur_subframe;
  721. }
  722. return 0;
  723. }
  724. /**
  725. *@brief Decode one WMA frame.
  726. *@param s codec context
  727. *@return 0 if the trailer bit indicates that this is the last frame,
  728. * 1 if there are additional frames
  729. */
  730. static int decode_frame(WmallDecodeCtx *s)
  731. {
  732. GetBitContext* gb = &s->gb;
  733. int more_frames = 0;
  734. int len = 0;
  735. int i;
  736. /** check for potential output buffer overflow */
  737. if (s->num_channels * s->samples_per_frame > s->samples_end - s->samples) {
  738. /** return an error if no frame could be decoded at all */
  739. av_log(s->avctx, AV_LOG_ERROR,
  740. "not enough space for the output samples\n");
  741. s->packet_loss = 1;
  742. return 0;
  743. }
  744. /** get frame length */
  745. if (s->len_prefix)
  746. len = get_bits(gb, s->log2_frame_size);
  747. /** decode tile information */
  748. if (decode_tilehdr(s)) {
  749. s->packet_loss = 1;
  750. return 0;
  751. }
  752. /** read drc info */
  753. if (s->dynamic_range_compression) {
  754. s->drc_gain = get_bits(gb, 8);
  755. }
  756. /** no idea what these are for, might be the number of samples
  757. that need to be skipped at the beginning or end of a stream */
  758. if (get_bits1(gb)) {
  759. int skip;
  760. /** usually true for the first frame */
  761. if (get_bits1(gb)) {
  762. skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
  763. dprintf(s->avctx, "start skip: %i\n", skip);
  764. }
  765. /** sometimes true for the last frame */
  766. if (get_bits1(gb)) {
  767. skip = get_bits(gb, av_log2(s->samples_per_frame * 2));
  768. dprintf(s->avctx, "end skip: %i\n", skip);
  769. }
  770. }
  771. /** reset subframe states */
  772. s->parsed_all_subframes = 0;
  773. for (i = 0; i < s->num_channels; i++) {
  774. s->channel[i].decoded_samples = 0;
  775. s->channel[i].cur_subframe = 0;
  776. s->channel[i].reuse_sf = 0;
  777. }
  778. /** decode all subframes */
  779. while (!s->parsed_all_subframes) {
  780. if (decode_subframe(s) < 0) {
  781. s->packet_loss = 1;
  782. return 0;
  783. }
  784. }
  785. dprintf(s->avctx, "Frame done\n");
  786. if (s->skip_frame) {
  787. s->skip_frame = 0;
  788. } else
  789. s->samples += s->num_channels * s->samples_per_frame;
  790. if (s->len_prefix) {
  791. if (len != (get_bits_count(gb) - s->frame_offset) + 2) {
  792. /** FIXME: not sure if this is always an error */
  793. av_log(s->avctx, AV_LOG_ERROR,
  794. "frame[%i] would have to skip %i bits\n", s->frame_num,
  795. len - (get_bits_count(gb) - s->frame_offset) - 1);
  796. s->packet_loss = 1;
  797. return 0;
  798. }
  799. /** skip the rest of the frame data */
  800. skip_bits_long(gb, len - (get_bits_count(gb) - s->frame_offset) - 1);
  801. } else {
  802. /*
  803. while (get_bits_count(gb) < s->num_saved_bits && get_bits1(gb) == 0) {
  804. dprintf(s->avctx, "skip1\n");
  805. }
  806. */
  807. }
  808. /** decode trailer bit */
  809. more_frames = get_bits1(gb);
  810. ++s->frame_num;
  811. return more_frames;
  812. }
  813. /**
  814. *@brief Calculate remaining input buffer length.
  815. *@param s codec context
  816. *@param gb bitstream reader context
  817. *@return remaining size in bits
  818. */
  819. static int remaining_bits(WmallDecodeCtx *s, GetBitContext *gb)
  820. {
  821. return s->buf_bit_size - get_bits_count(gb);
  822. }
  823. /**
  824. *@brief Fill the bit reservoir with a (partial) frame.
  825. *@param s codec context
  826. *@param gb bitstream reader context
  827. *@param len length of the partial frame
  828. *@param append decides wether to reset the buffer or not
  829. */
  830. static void save_bits(WmallDecodeCtx *s, GetBitContext* gb, int len,
  831. int append)
  832. {
  833. int buflen;
  834. /** when the frame data does not need to be concatenated, the input buffer
  835. is resetted and additional bits from the previous frame are copyed
  836. and skipped later so that a fast byte copy is possible */
  837. if (!append) {
  838. s->frame_offset = get_bits_count(gb) & 7;
  839. s->num_saved_bits = s->frame_offset;
  840. init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);
  841. }
  842. buflen = (s->num_saved_bits + len + 8) >> 3;
  843. if (len <= 0 || buflen > MAX_FRAMESIZE) {
  844. av_log_ask_for_sample(s->avctx, "input buffer too small\n");
  845. s->packet_loss = 1;
  846. return;
  847. }
  848. s->num_saved_bits += len;
  849. if (!append) {
  850. avpriv_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3),
  851. s->num_saved_bits);
  852. } else {
  853. int align = 8 - (get_bits_count(gb) & 7);
  854. align = FFMIN(align, len);
  855. put_bits(&s->pb, align, get_bits(gb, align));
  856. len -= align;
  857. avpriv_copy_bits(&s->pb, gb->buffer + (get_bits_count(gb) >> 3), len);
  858. }
  859. skip_bits_long(gb, len);
  860. {
  861. PutBitContext tmp = s->pb;
  862. flush_put_bits(&tmp);
  863. }
  864. init_get_bits(&s->gb, s->frame_data, s->num_saved_bits);
  865. skip_bits(&s->gb, s->frame_offset);
  866. }
  867. /**
  868. *@brief Decode a single WMA packet.
  869. *@param avctx codec context
  870. *@param data the output buffer
  871. *@param data_size number of bytes that were written to the output buffer
  872. *@param avpkt input packet
  873. *@return number of bytes that were read from the input buffer
  874. */
  875. static int decode_packet(AVCodecContext *avctx,
  876. void *data, int *data_size, AVPacket* avpkt)
  877. {
  878. WmallDecodeCtx *s = avctx->priv_data;
  879. GetBitContext* gb = &s->pgb;
  880. const uint8_t* buf = avpkt->data;
  881. int buf_size = avpkt->size;
  882. int num_bits_prev_frame;
  883. int packet_sequence_number;
  884. s->samples = data;
  885. s->samples_end = (float*)((int8_t*)data + *data_size);
  886. *data_size = 0;
  887. if (s->packet_done || s->packet_loss) {
  888. s->packet_done = 0;
  889. /** sanity check for the buffer length */
  890. if (buf_size < avctx->block_align)
  891. return 0;
  892. s->next_packet_start = buf_size - avctx->block_align;
  893. buf_size = avctx->block_align;
  894. s->buf_bit_size = buf_size << 3;
  895. /** parse packet header */
  896. init_get_bits(gb, buf, s->buf_bit_size);
  897. packet_sequence_number = get_bits(gb, 4);
  898. int seekable_frame_in_packet = get_bits1(gb);
  899. int spliced_packet = get_bits1(gb);
  900. /** get number of bits that need to be added to the previous frame */
  901. num_bits_prev_frame = get_bits(gb, s->log2_frame_size);
  902. /** check for packet loss */
  903. if (!s->packet_loss &&
  904. ((s->packet_sequence_number + 1) & 0xF) != packet_sequence_number) {
  905. s->packet_loss = 1;
  906. av_log(avctx, AV_LOG_ERROR, "Packet loss detected! seq %x vs %x\n",
  907. s->packet_sequence_number, packet_sequence_number);
  908. }
  909. s->packet_sequence_number = packet_sequence_number;
  910. if (num_bits_prev_frame > 0) {
  911. int remaining_packet_bits = s->buf_bit_size - get_bits_count(gb);
  912. if (num_bits_prev_frame >= remaining_packet_bits) {
  913. num_bits_prev_frame = remaining_packet_bits;
  914. s->packet_done = 1;
  915. }
  916. /** append the previous frame data to the remaining data from the
  917. previous packet to create a full frame */
  918. save_bits(s, gb, num_bits_prev_frame, 1);
  919. /** decode the cross packet frame if it is valid */
  920. if (!s->packet_loss)
  921. decode_frame(s);
  922. } else if (s->num_saved_bits - s->frame_offset) {
  923. dprintf(avctx, "ignoring %x previously saved bits\n",
  924. s->num_saved_bits - s->frame_offset);
  925. }
  926. if (s->packet_loss) {
  927. /** reset number of saved bits so that the decoder
  928. does not start to decode incomplete frames in the
  929. s->len_prefix == 0 case */
  930. s->num_saved_bits = 0;
  931. s->packet_loss = 0;
  932. }
  933. } else {
  934. int frame_size;
  935. s->buf_bit_size = (avpkt->size - s->next_packet_start) << 3;
  936. init_get_bits(gb, avpkt->data, s->buf_bit_size);
  937. skip_bits(gb, s->packet_offset);
  938. if (s->len_prefix && remaining_bits(s, gb) > s->log2_frame_size &&
  939. (frame_size = show_bits(gb, s->log2_frame_size)) &&
  940. frame_size <= remaining_bits(s, gb)) {
  941. save_bits(s, gb, frame_size, 0);
  942. s->packet_done = !decode_frame(s);
  943. } else if (!s->len_prefix
  944. && s->num_saved_bits > get_bits_count(&s->gb)) {
  945. /** when the frames do not have a length prefix, we don't know
  946. the compressed length of the individual frames
  947. however, we know what part of a new packet belongs to the
  948. previous frame
  949. therefore we save the incoming packet first, then we append
  950. the "previous frame" data from the next packet so that
  951. we get a buffer that only contains full frames */
  952. s->packet_done = !decode_frame(s);
  953. } else {
  954. s->packet_done = 1;
  955. }
  956. }
  957. if (s->packet_done && !s->packet_loss &&
  958. remaining_bits(s, gb) > 0) {
  959. /** save the rest of the data so that it can be decoded
  960. with the next packet */
  961. save_bits(s, gb, remaining_bits(s, gb), 0);
  962. }
  963. *data_size = 0; // (int8_t *)s->samples - (int8_t *)data;
  964. s->packet_offset = get_bits_count(gb) & 7;
  965. return (s->packet_loss) ? AVERROR_INVALIDDATA : get_bits_count(gb) >> 3;
  966. }
  967. /**
  968. *@brief Clear decoder buffers (for seeking).
  969. *@param avctx codec context
  970. */
  971. static void flush(AVCodecContext *avctx)
  972. {
  973. WmallDecodeCtx *s = avctx->priv_data;
  974. int i;
  975. /** reset output buffer as a part of it is used during the windowing of a
  976. new frame */
  977. for (i = 0; i < s->num_channels; i++)
  978. memset(s->channel[i].out, 0, s->samples_per_frame *
  979. sizeof(*s->channel[i].out));
  980. s->packet_loss = 1;
  981. }
  982. /**
  983. *@brief wmall decoder
  984. */
  985. AVCodec ff_wmalossless_decoder = {
  986. "wmalossless",
  987. AVMEDIA_TYPE_AUDIO,
  988. CODEC_ID_WMALOSSLESS,
  989. sizeof(WmallDecodeCtx),
  990. decode_init,
  991. NULL,
  992. decode_end,
  993. decode_packet,
  994. .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_EXPERIMENTAL,
  995. .flush= flush,
  996. .long_name = NULL_IF_CONFIG_SMALL("Windows Media Audio 9 Lossless"),
  997. };