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.

2034 lines
80KB

  1. /*
  2. * Windows Media Audio Voice decoder.
  3. * Copyright (c) 2009 Ronald S. Bultje
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * @brief Windows Media Audio Voice compatible decoder
  24. * @author Ronald S. Bultje <rsbultje@gmail.com>
  25. */
  26. #include <math.h>
  27. #include "avcodec.h"
  28. #include "get_bits.h"
  29. #include "put_bits.h"
  30. #include "wmavoice_data.h"
  31. #include "celp_math.h"
  32. #include "celp_filters.h"
  33. #include "acelp_vectors.h"
  34. #include "acelp_filters.h"
  35. #include "lsp.h"
  36. #include "libavutil/lzo.h"
  37. #include "avfft.h"
  38. #include "fft.h"
  39. #define MAX_BLOCKS 8 ///< maximum number of blocks per frame
  40. #define MAX_LSPS 16 ///< maximum filter order
  41. #define MAX_LSPS_ALIGN16 16 ///< same as #MAX_LSPS; needs to be multiple
  42. ///< of 16 for ASM input buffer alignment
  43. #define MAX_FRAMES 3 ///< maximum number of frames per superframe
  44. #define MAX_FRAMESIZE 160 ///< maximum number of samples per frame
  45. #define MAX_SIGNAL_HISTORY 416 ///< maximum excitation signal history
  46. #define MAX_SFRAMESIZE (MAX_FRAMESIZE * MAX_FRAMES)
  47. ///< maximum number of samples per superframe
  48. #define SFRAME_CACHE_MAXSIZE 256 ///< maximum cache size for frame data that
  49. ///< was split over two packets
  50. #define VLC_NBITS 6 ///< number of bits to read per VLC iteration
  51. /**
  52. * Frame type VLC coding.
  53. */
  54. static VLC frame_type_vlc;
  55. /**
  56. * Adaptive codebook types.
  57. */
  58. enum {
  59. ACB_TYPE_NONE = 0, ///< no adaptive codebook (only hardcoded fixed)
  60. ACB_TYPE_ASYMMETRIC = 1, ///< adaptive codebook with per-frame pitch, which
  61. ///< we interpolate to get a per-sample pitch.
  62. ///< Signal is generated using an asymmetric sinc
  63. ///< window function
  64. ///< @note see #wmavoice_ipol1_coeffs
  65. ACB_TYPE_HAMMING = 2 ///< Per-block pitch with signal generation using
  66. ///< a Hamming sinc window function
  67. ///< @note see #wmavoice_ipol2_coeffs
  68. };
  69. /**
  70. * Fixed codebook types.
  71. */
  72. enum {
  73. FCB_TYPE_SILENCE = 0, ///< comfort noise during silence
  74. ///< generated from a hardcoded (fixed) codebook
  75. ///< with per-frame (low) gain values
  76. FCB_TYPE_HARDCODED = 1, ///< hardcoded (fixed) codebook with per-block
  77. ///< gain values
  78. FCB_TYPE_AW_PULSES = 2, ///< Pitch-adaptive window (AW) pulse signals,
  79. ///< used in particular for low-bitrate streams
  80. FCB_TYPE_EXC_PULSES = 3, ///< Innovation (fixed) codebook pulse sets in
  81. ///< combinations of either single pulses or
  82. ///< pulse pairs
  83. };
  84. /**
  85. * Description of frame types.
  86. */
  87. static const struct frame_type_desc {
  88. uint8_t n_blocks; ///< amount of blocks per frame (each block
  89. ///< (contains 160/#n_blocks samples)
  90. uint8_t log_n_blocks; ///< log2(#n_blocks)
  91. uint8_t acb_type; ///< Adaptive codebook type (ACB_TYPE_*)
  92. uint8_t fcb_type; ///< Fixed codebook type (FCB_TYPE_*)
  93. uint8_t dbl_pulses; ///< how many pulse vectors have pulse pairs
  94. ///< (rather than just one single pulse)
  95. ///< only if #fcb_type == #FCB_TYPE_EXC_PULSES
  96. uint16_t frame_size; ///< the amount of bits that make up the block
  97. ///< data (per frame)
  98. } frame_descs[17] = {
  99. { 1, 0, ACB_TYPE_NONE, FCB_TYPE_SILENCE, 0, 0 },
  100. { 2, 1, ACB_TYPE_NONE, FCB_TYPE_HARDCODED, 0, 28 },
  101. { 2, 1, ACB_TYPE_ASYMMETRIC, FCB_TYPE_AW_PULSES, 0, 46 },
  102. { 2, 1, ACB_TYPE_ASYMMETRIC, FCB_TYPE_EXC_PULSES, 2, 80 },
  103. { 2, 1, ACB_TYPE_ASYMMETRIC, FCB_TYPE_EXC_PULSES, 5, 104 },
  104. { 4, 2, ACB_TYPE_ASYMMETRIC, FCB_TYPE_EXC_PULSES, 0, 108 },
  105. { 4, 2, ACB_TYPE_ASYMMETRIC, FCB_TYPE_EXC_PULSES, 2, 132 },
  106. { 4, 2, ACB_TYPE_ASYMMETRIC, FCB_TYPE_EXC_PULSES, 5, 168 },
  107. { 2, 1, ACB_TYPE_HAMMING, FCB_TYPE_EXC_PULSES, 0, 64 },
  108. { 2, 1, ACB_TYPE_HAMMING, FCB_TYPE_EXC_PULSES, 2, 80 },
  109. { 2, 1, ACB_TYPE_HAMMING, FCB_TYPE_EXC_PULSES, 5, 104 },
  110. { 4, 2, ACB_TYPE_HAMMING, FCB_TYPE_EXC_PULSES, 0, 108 },
  111. { 4, 2, ACB_TYPE_HAMMING, FCB_TYPE_EXC_PULSES, 2, 132 },
  112. { 4, 2, ACB_TYPE_HAMMING, FCB_TYPE_EXC_PULSES, 5, 168 },
  113. { 8, 3, ACB_TYPE_HAMMING, FCB_TYPE_EXC_PULSES, 0, 176 },
  114. { 8, 3, ACB_TYPE_HAMMING, FCB_TYPE_EXC_PULSES, 2, 208 },
  115. { 8, 3, ACB_TYPE_HAMMING, FCB_TYPE_EXC_PULSES, 5, 256 }
  116. };
  117. /**
  118. * WMA Voice decoding context.
  119. */
  120. typedef struct {
  121. /**
  122. * @defgroup struct_global Global values
  123. * Global values, specified in the stream header / extradata or used
  124. * all over.
  125. * @{
  126. */
  127. GetBitContext gb; ///< packet bitreader. During decoder init,
  128. ///< it contains the extradata from the
  129. ///< demuxer. During decoding, it contains
  130. ///< packet data.
  131. int8_t vbm_tree[25]; ///< converts VLC codes to frame type
  132. int spillover_bitsize; ///< number of bits used to specify
  133. ///< #spillover_nbits in the packet header
  134. ///< = ceil(log2(ctx->block_align << 3))
  135. int history_nsamples; ///< number of samples in history for signal
  136. ///< prediction (through ACB)
  137. /* postfilter specific values */
  138. int do_apf; ///< whether to apply the averaged
  139. ///< projection filter (APF)
  140. int denoise_strength; ///< strength of denoising in Wiener filter
  141. ///< [0-11]
  142. int denoise_tilt_corr; ///< Whether to apply tilt correction to the
  143. ///< Wiener filter coefficients (postfilter)
  144. int dc_level; ///< Predicted amount of DC noise, based
  145. ///< on which a DC removal filter is used
  146. int lsps; ///< number of LSPs per frame [10 or 16]
  147. int lsp_q_mode; ///< defines quantizer defaults [0, 1]
  148. int lsp_def_mode; ///< defines different sets of LSP defaults
  149. ///< [0, 1]
  150. int frame_lsp_bitsize; ///< size (in bits) of LSPs, when encoded
  151. ///< per-frame (independent coding)
  152. int sframe_lsp_bitsize; ///< size (in bits) of LSPs, when encoded
  153. ///< per superframe (residual coding)
  154. int min_pitch_val; ///< base value for pitch parsing code
  155. int max_pitch_val; ///< max value + 1 for pitch parsing
  156. int pitch_nbits; ///< number of bits used to specify the
  157. ///< pitch value in the frame header
  158. int block_pitch_nbits; ///< number of bits used to specify the
  159. ///< first block's pitch value
  160. int block_pitch_range; ///< range of the block pitch
  161. int block_delta_pitch_nbits; ///< number of bits used to specify the
  162. ///< delta pitch between this and the last
  163. ///< block's pitch value, used in all but
  164. ///< first block
  165. int block_delta_pitch_hrange; ///< 1/2 range of the delta (full range is
  166. ///< from -this to +this-1)
  167. uint16_t block_conv_table[4]; ///< boundaries for block pitch unit/scale
  168. ///< conversion
  169. /**
  170. * @}
  171. * @defgroup struct_packet Packet values
  172. * Packet values, specified in the packet header or related to a packet.
  173. * A packet is considered to be a single unit of data provided to this
  174. * decoder by the demuxer.
  175. * @{
  176. */
  177. int spillover_nbits; ///< number of bits of the previous packet's
  178. ///< last superframe preceeding this
  179. ///< packet's first full superframe (useful
  180. ///< for re-synchronization also)
  181. int has_residual_lsps; ///< if set, superframes contain one set of
  182. ///< LSPs that cover all frames, encoded as
  183. ///< independent and residual LSPs; if not
  184. ///< set, each frame contains its own, fully
  185. ///< independent, LSPs
  186. int skip_bits_next; ///< number of bits to skip at the next call
  187. ///< to #wmavoice_decode_packet() (since
  188. ///< they're part of the previous superframe)
  189. uint8_t sframe_cache[SFRAME_CACHE_MAXSIZE + FF_INPUT_BUFFER_PADDING_SIZE];
  190. ///< cache for superframe data split over
  191. ///< multiple packets
  192. int sframe_cache_size; ///< set to >0 if we have data from an
  193. ///< (incomplete) superframe from a previous
  194. ///< packet that spilled over in the current
  195. ///< packet; specifies the amount of bits in
  196. ///< #sframe_cache
  197. PutBitContext pb; ///< bitstream writer for #sframe_cache
  198. /**
  199. * @}
  200. * @defgroup struct_frame Frame and superframe values
  201. * Superframe and frame data - these can change from frame to frame,
  202. * although some of them do in that case serve as a cache / history for
  203. * the next frame or superframe.
  204. * @{
  205. */
  206. double prev_lsps[MAX_LSPS]; ///< LSPs of the last frame of the previous
  207. ///< superframe
  208. int last_pitch_val; ///< pitch value of the previous frame
  209. int last_acb_type; ///< frame type [0-2] of the previous frame
  210. int pitch_diff_sh16; ///< ((cur_pitch_val - #last_pitch_val)
  211. ///< << 16) / #MAX_FRAMESIZE
  212. float silence_gain; ///< set for use in blocks if #ACB_TYPE_NONE
  213. int aw_idx_is_ext; ///< whether the AW index was encoded in
  214. ///< 8 bits (instead of 6)
  215. int aw_pulse_range; ///< the range over which #aw_pulse_set1()
  216. ///< can apply the pulse, relative to the
  217. ///< value in aw_first_pulse_off. The exact
  218. ///< position of the first AW-pulse is within
  219. ///< [pulse_off, pulse_off + this], and
  220. ///< depends on bitstream values; [16 or 24]
  221. int aw_n_pulses[2]; ///< number of AW-pulses in each block; note
  222. ///< that this number can be negative (in
  223. ///< which case it basically means "zero")
  224. int aw_first_pulse_off[2]; ///< index of first sample to which to
  225. ///< apply AW-pulses, or -0xff if unset
  226. int aw_next_pulse_off_cache; ///< the position (relative to start of the
  227. ///< second block) at which pulses should
  228. ///< start to be positioned, serves as a
  229. ///< cache for pitch-adaptive window pulses
  230. ///< between blocks
  231. int frame_cntr; ///< current frame index [0 - 0xFFFE]; is
  232. ///< only used for comfort noise in #pRNG()
  233. float gain_pred_err[6]; ///< cache for gain prediction
  234. float excitation_history[MAX_SIGNAL_HISTORY];
  235. ///< cache of the signal of previous
  236. ///< superframes, used as a history for
  237. ///< signal generation
  238. float synth_history[MAX_LSPS]; ///< see #excitation_history
  239. /**
  240. * @}
  241. * @defgroup post_filter Postfilter values
  242. * Variables used for postfilter implementation, mostly history for
  243. * smoothing and so on, and context variables for FFT/iFFT.
  244. * @{
  245. */
  246. RDFTContext rdft, irdft; ///< contexts for FFT-calculation in the
  247. ///< postfilter (for denoise filter)
  248. DCTContext dct, dst; ///< contexts for phase shift (in Hilbert
  249. ///< transform, part of postfilter)
  250. float sin[511], cos[511]; ///< 8-bit cosine/sine windows over [-pi,pi]
  251. ///< range
  252. float postfilter_agc; ///< gain control memory, used in
  253. ///< #adaptive_gain_control()
  254. float dcf_mem[2]; ///< DC filter history
  255. float zero_exc_pf[MAX_SIGNAL_HISTORY + MAX_SFRAMESIZE];
  256. ///< zero filter output (i.e. excitation)
  257. ///< by postfilter
  258. float denoise_filter_cache[MAX_FRAMESIZE];
  259. int denoise_filter_cache_size; ///< samples in #denoise_filter_cache
  260. DECLARE_ALIGNED(16, float, tilted_lpcs_pf)[0x80];
  261. ///< aligned buffer for LPC tilting
  262. DECLARE_ALIGNED(16, float, denoise_coeffs_pf)[0x80];
  263. ///< aligned buffer for denoise coefficients
  264. DECLARE_ALIGNED(16, float, synth_filter_out_buf)[0x80 + MAX_LSPS_ALIGN16];
  265. ///< aligned buffer for postfilter speech
  266. ///< synthesis
  267. /**
  268. * @}
  269. */
  270. } WMAVoiceContext;
  271. /**
  272. * Set up the variable bit mode (VBM) tree from container extradata.
  273. * @param gb bit I/O context.
  274. * The bit context (s->gb) should be loaded with byte 23-46 of the
  275. * container extradata (i.e. the ones containing the VBM tree).
  276. * @param vbm_tree pointer to array to which the decoded VBM tree will be
  277. * written.
  278. * @return 0 on success, <0 on error.
  279. */
  280. static av_cold int decode_vbmtree(GetBitContext *gb, int8_t vbm_tree[25])
  281. {
  282. static const uint8_t bits[] = {
  283. 2, 2, 2, 4, 4, 4,
  284. 6, 6, 6, 8, 8, 8,
  285. 10, 10, 10, 12, 12, 12,
  286. 14, 14, 14, 14
  287. };
  288. static const uint16_t codes[] = {
  289. 0x0000, 0x0001, 0x0002, // 00/01/10
  290. 0x000c, 0x000d, 0x000e, // 11+00/01/10
  291. 0x003c, 0x003d, 0x003e, // 1111+00/01/10
  292. 0x00fc, 0x00fd, 0x00fe, // 111111+00/01/10
  293. 0x03fc, 0x03fd, 0x03fe, // 11111111+00/01/10
  294. 0x0ffc, 0x0ffd, 0x0ffe, // 1111111111+00/01/10
  295. 0x3ffc, 0x3ffd, 0x3ffe, 0x3fff // 111111111111+xx
  296. };
  297. int cntr[8], n, res;
  298. memset(vbm_tree, 0xff, sizeof(vbm_tree));
  299. memset(cntr, 0, sizeof(cntr));
  300. for (n = 0; n < 17; n++) {
  301. res = get_bits(gb, 3);
  302. if (cntr[res] > 3) // should be >= 3 + (res == 7))
  303. return -1;
  304. vbm_tree[res * 3 + cntr[res]++] = n;
  305. }
  306. INIT_VLC_STATIC(&frame_type_vlc, VLC_NBITS, sizeof(bits),
  307. bits, 1, 1, codes, 2, 2, 132);
  308. return 0;
  309. }
  310. /**
  311. * Set up decoder with parameters from demuxer (extradata etc.).
  312. */
  313. static av_cold int wmavoice_decode_init(AVCodecContext *ctx)
  314. {
  315. int n, flags, pitch_range, lsp16_flag;
  316. WMAVoiceContext *s = ctx->priv_data;
  317. /**
  318. * Extradata layout:
  319. * - byte 0-18: WMAPro-in-WMAVoice extradata (see wmaprodec.c),
  320. * - byte 19-22: flags field (annoyingly in LE; see below for known
  321. * values),
  322. * - byte 23-46: variable bitmode tree (really just 17 * 3 bits,
  323. * rest is 0).
  324. */
  325. if (ctx->extradata_size != 46) {
  326. av_log(ctx, AV_LOG_ERROR,
  327. "Invalid extradata size %d (should be 46)\n",
  328. ctx->extradata_size);
  329. return -1;
  330. }
  331. flags = AV_RL32(ctx->extradata + 18);
  332. s->spillover_bitsize = 3 + av_ceil_log2(ctx->block_align);
  333. s->do_apf = flags & 0x1;
  334. if (s->do_apf) {
  335. ff_rdft_init(&s->rdft, 7, DFT_R2C);
  336. ff_rdft_init(&s->irdft, 7, IDFT_C2R);
  337. ff_dct_init(&s->dct, 6, DCT_I);
  338. ff_dct_init(&s->dst, 6, DST_I);
  339. ff_sine_window_init(s->cos, 256);
  340. memcpy(&s->sin[255], s->cos, 256 * sizeof(s->cos[0]));
  341. for (n = 0; n < 255; n++) {
  342. s->sin[n] = -s->sin[510 - n];
  343. s->cos[510 - n] = s->cos[n];
  344. }
  345. }
  346. s->denoise_strength = (flags >> 2) & 0xF;
  347. if (s->denoise_strength >= 12) {
  348. av_log(ctx, AV_LOG_ERROR,
  349. "Invalid denoise filter strength %d (max=11)\n",
  350. s->denoise_strength);
  351. return -1;
  352. }
  353. s->denoise_tilt_corr = !!(flags & 0x40);
  354. s->dc_level = (flags >> 7) & 0xF;
  355. s->lsp_q_mode = !!(flags & 0x2000);
  356. s->lsp_def_mode = !!(flags & 0x4000);
  357. lsp16_flag = flags & 0x1000;
  358. if (lsp16_flag) {
  359. s->lsps = 16;
  360. s->frame_lsp_bitsize = 34;
  361. s->sframe_lsp_bitsize = 60;
  362. } else {
  363. s->lsps = 10;
  364. s->frame_lsp_bitsize = 24;
  365. s->sframe_lsp_bitsize = 48;
  366. }
  367. for (n = 0; n < s->lsps; n++)
  368. s->prev_lsps[n] = M_PI * (n + 1.0) / (s->lsps + 1.0);
  369. init_get_bits(&s->gb, ctx->extradata + 22, (ctx->extradata_size - 22) << 3);
  370. if (decode_vbmtree(&s->gb, s->vbm_tree) < 0) {
  371. av_log(ctx, AV_LOG_ERROR, "Invalid VBM tree; broken extradata?\n");
  372. return -1;
  373. }
  374. s->min_pitch_val = ((ctx->sample_rate << 8) / 400 + 50) >> 8;
  375. s->max_pitch_val = ((ctx->sample_rate << 8) * 37 / 2000 + 50) >> 8;
  376. pitch_range = s->max_pitch_val - s->min_pitch_val;
  377. s->pitch_nbits = av_ceil_log2(pitch_range);
  378. s->last_pitch_val = 40;
  379. s->last_acb_type = ACB_TYPE_NONE;
  380. s->history_nsamples = s->max_pitch_val + 8;
  381. if (s->min_pitch_val < 1 || s->history_nsamples > MAX_SIGNAL_HISTORY) {
  382. int min_sr = ((((1 << 8) - 50) * 400) + 0xFF) >> 8,
  383. max_sr = ((((MAX_SIGNAL_HISTORY - 8) << 8) + 205) * 2000 / 37) >> 8;
  384. av_log(ctx, AV_LOG_ERROR,
  385. "Unsupported samplerate %d (min=%d, max=%d)\n",
  386. ctx->sample_rate, min_sr, max_sr); // 322-22097 Hz
  387. return -1;
  388. }
  389. s->block_conv_table[0] = s->min_pitch_val;
  390. s->block_conv_table[1] = (pitch_range * 25) >> 6;
  391. s->block_conv_table[2] = (pitch_range * 44) >> 6;
  392. s->block_conv_table[3] = s->max_pitch_val - 1;
  393. s->block_delta_pitch_hrange = (pitch_range >> 3) & ~0xF;
  394. s->block_delta_pitch_nbits = 1 + av_ceil_log2(s->block_delta_pitch_hrange);
  395. s->block_pitch_range = s->block_conv_table[2] +
  396. s->block_conv_table[3] + 1 +
  397. 2 * (s->block_conv_table[1] - 2 * s->min_pitch_val);
  398. s->block_pitch_nbits = av_ceil_log2(s->block_pitch_range);
  399. ctx->sample_fmt = AV_SAMPLE_FMT_FLT;
  400. return 0;
  401. }
  402. /**
  403. * @defgroup postfilter Postfilter functions
  404. * Postfilter functions (gain control, wiener denoise filter, DC filter,
  405. * kalman smoothening, plus surrounding code to wrap it)
  406. * @{
  407. */
  408. /**
  409. * Adaptive gain control (as used in postfilter).
  410. *
  411. * Identical to #ff_adaptive_gain_control() in acelp_vectors.c, except
  412. * that the energy here is calculated using sum(abs(...)), whereas the
  413. * other codecs (e.g. AMR-NB, SIPRO) use sqrt(dotproduct(...)).
  414. *
  415. * @param out output buffer for filtered samples
  416. * @param in input buffer containing the samples as they are after the
  417. * postfilter steps so far
  418. * @param speech_synth input buffer containing speech synth before postfilter
  419. * @param size input buffer size
  420. * @param alpha exponential filter factor
  421. * @param gain_mem pointer to filter memory (single float)
  422. */
  423. static void adaptive_gain_control(float *out, const float *in,
  424. const float *speech_synth,
  425. int size, float alpha, float *gain_mem)
  426. {
  427. int i;
  428. float speech_energy = 0.0, postfilter_energy = 0.0, gain_scale_factor;
  429. float mem = *gain_mem;
  430. for (i = 0; i < size; i++) {
  431. speech_energy += fabsf(speech_synth[i]);
  432. postfilter_energy += fabsf(in[i]);
  433. }
  434. gain_scale_factor = (1.0 - alpha) * speech_energy / postfilter_energy;
  435. for (i = 0; i < size; i++) {
  436. mem = alpha * mem + gain_scale_factor;
  437. out[i] = in[i] * mem;
  438. }
  439. *gain_mem = mem;
  440. }
  441. /**
  442. * Kalman smoothing function.
  443. *
  444. * This function looks back pitch +/- 3 samples back into history to find
  445. * the best fitting curve (that one giving the optimal gain of the two
  446. * signals, i.e. the highest dot product between the two), and then
  447. * uses that signal history to smoothen the output of the speech synthesis
  448. * filter.
  449. *
  450. * @param s WMA Voice decoding context
  451. * @param pitch pitch of the speech signal
  452. * @param in input speech signal
  453. * @param out output pointer for smoothened signal
  454. * @param size input/output buffer size
  455. *
  456. * @returns -1 if no smoothening took place, e.g. because no optimal
  457. * fit could be found, or 0 on success.
  458. */
  459. static int kalman_smoothen(WMAVoiceContext *s, int pitch,
  460. const float *in, float *out, int size)
  461. {
  462. int n;
  463. float optimal_gain = 0, dot;
  464. const float *ptr = &in[-FFMAX(s->min_pitch_val, pitch - 3)],
  465. *end = &in[-FFMIN(s->max_pitch_val, pitch + 3)],
  466. *best_hist_ptr;
  467. /* find best fitting point in history */
  468. do {
  469. dot = ff_dot_productf(in, ptr, size);
  470. if (dot > optimal_gain) {
  471. optimal_gain = dot;
  472. best_hist_ptr = ptr;
  473. }
  474. } while (--ptr >= end);
  475. if (optimal_gain <= 0)
  476. return -1;
  477. dot = ff_dot_productf(best_hist_ptr, best_hist_ptr, size);
  478. if (dot <= 0) // would be 1.0
  479. return -1;
  480. if (optimal_gain <= dot) {
  481. dot = dot / (dot + 0.6 * optimal_gain); // 0.625-1.000
  482. } else
  483. dot = 0.625;
  484. /* actual smoothing */
  485. for (n = 0; n < size; n++)
  486. out[n] = best_hist_ptr[n] + dot * (in[n] - best_hist_ptr[n]);
  487. return 0;
  488. }
  489. /**
  490. * Get the tilt factor of a formant filter from its transfer function
  491. * @see #tilt_factor() in amrnbdec.c, which does essentially the same,
  492. * but somehow (??) it does a speech synthesis filter in the
  493. * middle, which is missing here
  494. *
  495. * @param lpcs LPC coefficients
  496. * @param n_lpcs Size of LPC buffer
  497. * @returns the tilt factor
  498. */
  499. static float tilt_factor(const float *lpcs, int n_lpcs)
  500. {
  501. float rh0, rh1;
  502. rh0 = 1.0 + ff_dot_productf(lpcs, lpcs, n_lpcs);
  503. rh1 = lpcs[0] + ff_dot_productf(lpcs, &lpcs[1], n_lpcs - 1);
  504. return rh1 / rh0;
  505. }
  506. /**
  507. * Derive denoise filter coefficients (in real domain) from the LPCs.
  508. */
  509. static void calc_input_response(WMAVoiceContext *s, float *lpcs,
  510. int fcb_type, float *coeffs, int remainder)
  511. {
  512. float last_coeff, min = 15.0, max = -15.0;
  513. float irange, angle_mul, gain_mul, range, sq;
  514. int n, idx;
  515. /* Create frequency power spectrum of speech input (i.e. RDFT of LPCs) */
  516. ff_rdft_calc(&s->rdft, lpcs);
  517. #define log_range(var, assign) do { \
  518. float tmp = log10f(assign); var = tmp; \
  519. max = FFMAX(max, tmp); min = FFMIN(min, tmp); \
  520. } while (0)
  521. log_range(last_coeff, lpcs[1] * lpcs[1]);
  522. for (n = 1; n < 64; n++)
  523. log_range(lpcs[n], lpcs[n * 2] * lpcs[n * 2] +
  524. lpcs[n * 2 + 1] * lpcs[n * 2 + 1]);
  525. log_range(lpcs[0], lpcs[0] * lpcs[0]);
  526. #undef log_range
  527. range = max - min;
  528. lpcs[64] = last_coeff;
  529. /* Now, use this spectrum to pick out these frequencies with higher
  530. * (relative) power/energy (which we then take to be "not noise"),
  531. * and set up a table (still in lpc[]) of (relative) gains per frequency.
  532. * These frequencies will be maintained, while others ("noise") will be
  533. * decreased in the filter output. */
  534. irange = 64.0 / range; // so irange*(max-value) is in the range [0, 63]
  535. gain_mul = range * (fcb_type == FCB_TYPE_HARDCODED ? (5.0 / 13.0) :
  536. (5.0 / 14.7));
  537. angle_mul = gain_mul * (8.0 * M_LN10 / M_PI);
  538. for (n = 0; n <= 64; n++) {
  539. float pwr;
  540. idx = FFMAX(0, lrint((max - lpcs[n]) * irange) - 1);
  541. pwr = wmavoice_denoise_power_table[s->denoise_strength][idx];
  542. lpcs[n] = angle_mul * pwr;
  543. /* 70.57 =~ 1/log10(1.0331663) */
  544. idx = (pwr * gain_mul - 0.0295) * 70.570526123;
  545. if (idx > 127) { // fallback if index falls outside table range
  546. coeffs[n] = wmavoice_energy_table[127] *
  547. powf(1.0331663, idx - 127);
  548. } else
  549. coeffs[n] = wmavoice_energy_table[FFMAX(0, idx)];
  550. }
  551. /* calculate the Hilbert transform of the gains, which we do (since this
  552. * is a sinus input) by doing a phase shift (in theory, H(sin())=cos()).
  553. * Hilbert_Transform(RDFT(x)) = Laplace_Transform(x), which calculates the
  554. * "moment" of the LPCs in this filter. */
  555. ff_dct_calc(&s->dct, lpcs);
  556. ff_dct_calc(&s->dst, lpcs);
  557. /* Split out the coefficient indexes into phase/magnitude pairs */
  558. idx = 255 + av_clip(lpcs[64], -255, 255);
  559. coeffs[0] = coeffs[0] * s->cos[idx];
  560. idx = 255 + av_clip(lpcs[64] - 2 * lpcs[63], -255, 255);
  561. last_coeff = coeffs[64] * s->cos[idx];
  562. for (n = 63;; n--) {
  563. idx = 255 + av_clip(-lpcs[64] - 2 * lpcs[n - 1], -255, 255);
  564. coeffs[n * 2 + 1] = coeffs[n] * s->sin[idx];
  565. coeffs[n * 2] = coeffs[n] * s->cos[idx];
  566. if (!--n) break;
  567. idx = 255 + av_clip( lpcs[64] - 2 * lpcs[n - 1], -255, 255);
  568. coeffs[n * 2 + 1] = coeffs[n] * s->sin[idx];
  569. coeffs[n * 2] = coeffs[n] * s->cos[idx];
  570. }
  571. coeffs[1] = last_coeff;
  572. /* move into real domain */
  573. ff_rdft_calc(&s->irdft, coeffs);
  574. /* tilt correction and normalize scale */
  575. memset(&coeffs[remainder], 0, sizeof(coeffs[0]) * (128 - remainder));
  576. if (s->denoise_tilt_corr) {
  577. float tilt_mem = 0;
  578. coeffs[remainder - 1] = 0;
  579. ff_tilt_compensation(&tilt_mem,
  580. -1.8 * tilt_factor(coeffs, remainder - 1),
  581. coeffs, remainder);
  582. }
  583. sq = (1.0 / 64.0) * sqrtf(1 / ff_dot_productf(coeffs, coeffs, remainder));
  584. for (n = 0; n < remainder; n++)
  585. coeffs[n] *= sq;
  586. }
  587. /**
  588. * This function applies a Wiener filter on the (noisy) speech signal as
  589. * a means to denoise it.
  590. *
  591. * - take RDFT of LPCs to get the power spectrum of the noise + speech;
  592. * - using this power spectrum, calculate (for each frequency) the Wiener
  593. * filter gain, which depends on the frequency power and desired level
  594. * of noise subtraction (when set too high, this leads to artifacts)
  595. * We can do this symmetrically over the X-axis (so 0-4kHz is the inverse
  596. * of 4-8kHz);
  597. * - by doing a phase shift, calculate the Hilbert transform of this array
  598. * of per-frequency filter-gains to get the filtering coefficients;
  599. * - smoothen/normalize/de-tilt these filter coefficients as desired;
  600. * - take RDFT of noisy sound, apply the coefficients and take its IRDFT
  601. * to get the denoised speech signal;
  602. * - the leftover (i.e. output of the IRDFT on denoised speech data beyond
  603. * the frame boundary) are saved and applied to subsequent frames by an
  604. * overlap-add method (otherwise you get clicking-artifacts).
  605. *
  606. * @param s WMA Voice decoding context
  607. * @param fcb_type Frame (codebook) type
  608. * @param synth_pf input: the noisy speech signal, output: denoised speech
  609. * data; should be 16-byte aligned (for ASM purposes)
  610. * @param size size of the speech data
  611. * @param lpcs LPCs used to synthesize this frame's speech data
  612. */
  613. static void wiener_denoise(WMAVoiceContext *s, int fcb_type,
  614. float *synth_pf, int size,
  615. const float *lpcs)
  616. {
  617. int remainder, lim, n;
  618. if (fcb_type != FCB_TYPE_SILENCE) {
  619. float *tilted_lpcs = s->tilted_lpcs_pf,
  620. *coeffs = s->denoise_coeffs_pf, tilt_mem = 0;
  621. tilted_lpcs[0] = 1.0;
  622. memcpy(&tilted_lpcs[1], lpcs, sizeof(lpcs[0]) * s->lsps);
  623. memset(&tilted_lpcs[s->lsps + 1], 0,
  624. sizeof(tilted_lpcs[0]) * (128 - s->lsps - 1));
  625. ff_tilt_compensation(&tilt_mem, 0.7 * tilt_factor(lpcs, s->lsps),
  626. tilted_lpcs, s->lsps + 2);
  627. /* The IRDFT output (127 samples for 7-bit filter) beyond the frame
  628. * size is applied to the next frame. All input beyond this is zero,
  629. * and thus all output beyond this will go towards zero, hence we can
  630. * limit to min(size-1, 127-size) as a performance consideration. */
  631. remainder = FFMIN(127 - size, size - 1);
  632. calc_input_response(s, tilted_lpcs, fcb_type, coeffs, remainder);
  633. /* apply coefficients (in frequency spectrum domain), i.e. complex
  634. * number multiplication */
  635. memset(&synth_pf[size], 0, sizeof(synth_pf[0]) * (128 - size));
  636. ff_rdft_calc(&s->rdft, synth_pf);
  637. ff_rdft_calc(&s->rdft, coeffs);
  638. synth_pf[0] *= coeffs[0];
  639. synth_pf[1] *= coeffs[1];
  640. for (n = 1; n < 64; n++) {
  641. float v1 = synth_pf[n * 2], v2 = synth_pf[n * 2 + 1];
  642. synth_pf[n * 2] = v1 * coeffs[n * 2] - v2 * coeffs[n * 2 + 1];
  643. synth_pf[n * 2 + 1] = v2 * coeffs[n * 2] + v1 * coeffs[n * 2 + 1];
  644. }
  645. ff_rdft_calc(&s->irdft, synth_pf);
  646. }
  647. /* merge filter output with the history of previous runs */
  648. if (s->denoise_filter_cache_size) {
  649. lim = FFMIN(s->denoise_filter_cache_size, size);
  650. for (n = 0; n < lim; n++)
  651. synth_pf[n] += s->denoise_filter_cache[n];
  652. s->denoise_filter_cache_size -= lim;
  653. memmove(s->denoise_filter_cache, &s->denoise_filter_cache[size],
  654. sizeof(s->denoise_filter_cache[0]) * s->denoise_filter_cache_size);
  655. }
  656. /* move remainder of filter output into a cache for future runs */
  657. if (fcb_type != FCB_TYPE_SILENCE) {
  658. lim = FFMIN(remainder, s->denoise_filter_cache_size);
  659. for (n = 0; n < lim; n++)
  660. s->denoise_filter_cache[n] += synth_pf[size + n];
  661. if (lim < remainder) {
  662. memcpy(&s->denoise_filter_cache[lim], &synth_pf[size + lim],
  663. sizeof(s->denoise_filter_cache[0]) * (remainder - lim));
  664. s->denoise_filter_cache_size = remainder;
  665. }
  666. }
  667. }
  668. /**
  669. * Averaging projection filter, the postfilter used in WMAVoice.
  670. *
  671. * This uses the following steps:
  672. * - A zero-synthesis filter (generate excitation from synth signal)
  673. * - Kalman smoothing on excitation, based on pitch
  674. * - Re-synthesized smoothened output
  675. * - Iterative Wiener denoise filter
  676. * - Adaptive gain filter
  677. * - DC filter
  678. *
  679. * @param s WMAVoice decoding context
  680. * @param synth Speech synthesis output (before postfilter)
  681. * @param samples Output buffer for filtered samples
  682. * @param size Buffer size of synth & samples
  683. * @param lpcs Generated LPCs used for speech synthesis
  684. * @param zero_exc_pf destination for zero synthesis filter (16-byte aligned)
  685. * @param fcb_type Frame type (silence, hardcoded, AW-pulses or FCB-pulses)
  686. * @param pitch Pitch of the input signal
  687. */
  688. static void postfilter(WMAVoiceContext *s, const float *synth,
  689. float *samples, int size,
  690. const float *lpcs, float *zero_exc_pf,
  691. int fcb_type, int pitch)
  692. {
  693. float synth_filter_in_buf[MAX_FRAMESIZE / 2],
  694. *synth_pf = &s->synth_filter_out_buf[MAX_LSPS_ALIGN16],
  695. *synth_filter_in = zero_exc_pf;
  696. assert(size <= MAX_FRAMESIZE / 2);
  697. /* generate excitation from input signal */
  698. ff_celp_lp_zero_synthesis_filterf(zero_exc_pf, lpcs, synth, size, s->lsps);
  699. if (fcb_type >= FCB_TYPE_AW_PULSES &&
  700. !kalman_smoothen(s, pitch, zero_exc_pf, synth_filter_in_buf, size))
  701. synth_filter_in = synth_filter_in_buf;
  702. /* re-synthesize speech after smoothening, and keep history */
  703. ff_celp_lp_synthesis_filterf(synth_pf, lpcs,
  704. synth_filter_in, size, s->lsps);
  705. memcpy(&synth_pf[-s->lsps], &synth_pf[size - s->lsps],
  706. sizeof(synth_pf[0]) * s->lsps);
  707. wiener_denoise(s, fcb_type, synth_pf, size, lpcs);
  708. adaptive_gain_control(samples, synth_pf, synth, size, 0.99,
  709. &s->postfilter_agc);
  710. if (s->dc_level > 8) {
  711. /* remove ultra-low frequency DC noise / highpass filter;
  712. * coefficients are identical to those used in SIPR decoding,
  713. * and very closely resemble those used in AMR-NB decoding. */
  714. ff_acelp_apply_order_2_transfer_function(samples, samples,
  715. (const float[2]) { -1.99997, 1.0 },
  716. (const float[2]) { -1.9330735188, 0.93589198496 },
  717. 0.93980580475, s->dcf_mem, size);
  718. }
  719. }
  720. /**
  721. * @}
  722. */
  723. /**
  724. * Dequantize LSPs
  725. * @param lsps output pointer to the array that will hold the LSPs
  726. * @param num number of LSPs to be dequantized
  727. * @param values quantized values, contains n_stages values
  728. * @param sizes range (i.e. max value) of each quantized value
  729. * @param n_stages number of dequantization runs
  730. * @param table dequantization table to be used
  731. * @param mul_q LSF multiplier
  732. * @param base_q base (lowest) LSF values
  733. */
  734. static void dequant_lsps(double *lsps, int num,
  735. const uint16_t *values,
  736. const uint16_t *sizes,
  737. int n_stages, const uint8_t *table,
  738. const double *mul_q,
  739. const double *base_q)
  740. {
  741. int n, m;
  742. memset(lsps, 0, num * sizeof(*lsps));
  743. for (n = 0; n < n_stages; n++) {
  744. const uint8_t *t_off = &table[values[n] * num];
  745. double base = base_q[n], mul = mul_q[n];
  746. for (m = 0; m < num; m++)
  747. lsps[m] += base + mul * t_off[m];
  748. table += sizes[n] * num;
  749. }
  750. }
  751. /**
  752. * @defgroup lsp_dequant LSP dequantization routines
  753. * LSP dequantization routines, for 10/16LSPs and independent/residual coding.
  754. * @note we assume enough bits are available, caller should check.
  755. * lsp10i() consumes 24 bits; lsp10r() consumes an additional 24 bits;
  756. * lsp16i() consumes 34 bits; lsp16r() consumes an additional 26 bits.
  757. * @{
  758. */
  759. /**
  760. * Parse 10 independently-coded LSPs.
  761. */
  762. static void dequant_lsp10i(GetBitContext *gb, double *lsps)
  763. {
  764. static const uint16_t vec_sizes[4] = { 256, 64, 32, 32 };
  765. static const double mul_lsf[4] = {
  766. 5.2187144800e-3, 1.4626986422e-3,
  767. 9.6179549166e-4, 1.1325736225e-3
  768. };
  769. static const double base_lsf[4] = {
  770. M_PI * -2.15522e-1, M_PI * -6.1646e-2,
  771. M_PI * -3.3486e-2, M_PI * -5.7408e-2
  772. };
  773. uint16_t v[4];
  774. v[0] = get_bits(gb, 8);
  775. v[1] = get_bits(gb, 6);
  776. v[2] = get_bits(gb, 5);
  777. v[3] = get_bits(gb, 5);
  778. dequant_lsps(lsps, 10, v, vec_sizes, 4, wmavoice_dq_lsp10i,
  779. mul_lsf, base_lsf);
  780. }
  781. /**
  782. * Parse 10 independently-coded LSPs, and then derive the tables to
  783. * generate LSPs for the other frames from them (residual coding).
  784. */
  785. static void dequant_lsp10r(GetBitContext *gb,
  786. double *i_lsps, const double *old,
  787. double *a1, double *a2, int q_mode)
  788. {
  789. static const uint16_t vec_sizes[3] = { 128, 64, 64 };
  790. static const double mul_lsf[3] = {
  791. 2.5807601174e-3, 1.2354460219e-3, 1.1763821673e-3
  792. };
  793. static const double base_lsf[3] = {
  794. M_PI * -1.07448e-1, M_PI * -5.2706e-2, M_PI * -5.1634e-2
  795. };
  796. const float (*ipol_tab)[2][10] = q_mode ?
  797. wmavoice_lsp10_intercoeff_b : wmavoice_lsp10_intercoeff_a;
  798. uint16_t interpol, v[3];
  799. int n;
  800. dequant_lsp10i(gb, i_lsps);
  801. interpol = get_bits(gb, 5);
  802. v[0] = get_bits(gb, 7);
  803. v[1] = get_bits(gb, 6);
  804. v[2] = get_bits(gb, 6);
  805. for (n = 0; n < 10; n++) {
  806. double delta = old[n] - i_lsps[n];
  807. a1[n] = ipol_tab[interpol][0][n] * delta + i_lsps[n];
  808. a1[10 + n] = ipol_tab[interpol][1][n] * delta + i_lsps[n];
  809. }
  810. dequant_lsps(a2, 20, v, vec_sizes, 3, wmavoice_dq_lsp10r,
  811. mul_lsf, base_lsf);
  812. }
  813. /**
  814. * Parse 16 independently-coded LSPs.
  815. */
  816. static void dequant_lsp16i(GetBitContext *gb, double *lsps)
  817. {
  818. static const uint16_t vec_sizes[5] = { 256, 64, 128, 64, 128 };
  819. static const double mul_lsf[5] = {
  820. 3.3439586280e-3, 6.9908173703e-4,
  821. 3.3216608306e-3, 1.0334960326e-3,
  822. 3.1899104283e-3
  823. };
  824. static const double base_lsf[5] = {
  825. M_PI * -1.27576e-1, M_PI * -2.4292e-2,
  826. M_PI * -1.28094e-1, M_PI * -3.2128e-2,
  827. M_PI * -1.29816e-1
  828. };
  829. uint16_t v[5];
  830. v[0] = get_bits(gb, 8);
  831. v[1] = get_bits(gb, 6);
  832. v[2] = get_bits(gb, 7);
  833. v[3] = get_bits(gb, 6);
  834. v[4] = get_bits(gb, 7);
  835. dequant_lsps( lsps, 5, v, vec_sizes, 2,
  836. wmavoice_dq_lsp16i1, mul_lsf, base_lsf);
  837. dequant_lsps(&lsps[5], 5, &v[2], &vec_sizes[2], 2,
  838. wmavoice_dq_lsp16i2, &mul_lsf[2], &base_lsf[2]);
  839. dequant_lsps(&lsps[10], 6, &v[4], &vec_sizes[4], 1,
  840. wmavoice_dq_lsp16i3, &mul_lsf[4], &base_lsf[4]);
  841. }
  842. /**
  843. * Parse 16 independently-coded LSPs, and then derive the tables to
  844. * generate LSPs for the other frames from them (residual coding).
  845. */
  846. static void dequant_lsp16r(GetBitContext *gb,
  847. double *i_lsps, const double *old,
  848. double *a1, double *a2, int q_mode)
  849. {
  850. static const uint16_t vec_sizes[3] = { 128, 128, 128 };
  851. static const double mul_lsf[3] = {
  852. 1.2232979501e-3, 1.4062241527e-3, 1.6114744851e-3
  853. };
  854. static const double base_lsf[3] = {
  855. M_PI * -5.5830e-2, M_PI * -5.2908e-2, M_PI * -5.4776e-2
  856. };
  857. const float (*ipol_tab)[2][16] = q_mode ?
  858. wmavoice_lsp16_intercoeff_b : wmavoice_lsp16_intercoeff_a;
  859. uint16_t interpol, v[3];
  860. int n;
  861. dequant_lsp16i(gb, i_lsps);
  862. interpol = get_bits(gb, 5);
  863. v[0] = get_bits(gb, 7);
  864. v[1] = get_bits(gb, 7);
  865. v[2] = get_bits(gb, 7);
  866. for (n = 0; n < 16; n++) {
  867. double delta = old[n] - i_lsps[n];
  868. a1[n] = ipol_tab[interpol][0][n] * delta + i_lsps[n];
  869. a1[16 + n] = ipol_tab[interpol][1][n] * delta + i_lsps[n];
  870. }
  871. dequant_lsps( a2, 10, v, vec_sizes, 1,
  872. wmavoice_dq_lsp16r1, mul_lsf, base_lsf);
  873. dequant_lsps(&a2[10], 10, &v[1], &vec_sizes[1], 1,
  874. wmavoice_dq_lsp16r2, &mul_lsf[1], &base_lsf[1]);
  875. dequant_lsps(&a2[20], 12, &v[2], &vec_sizes[2], 1,
  876. wmavoice_dq_lsp16r3, &mul_lsf[2], &base_lsf[2]);
  877. }
  878. /**
  879. * @}
  880. * @defgroup aw Pitch-adaptive window coding functions
  881. * The next few functions are for pitch-adaptive window coding.
  882. * @{
  883. */
  884. /**
  885. * Parse the offset of the first pitch-adaptive window pulses, and
  886. * the distribution of pulses between the two blocks in this frame.
  887. * @param s WMA Voice decoding context private data
  888. * @param gb bit I/O context
  889. * @param pitch pitch for each block in this frame
  890. */
  891. static void aw_parse_coords(WMAVoiceContext *s, GetBitContext *gb,
  892. const int *pitch)
  893. {
  894. static const int16_t start_offset[94] = {
  895. -11, -9, -7, -5, -3, -1, 1, 3, 5, 7, 9, 11,
  896. 13, 15, 18, 17, 19, 20, 21, 22, 23, 24, 25, 26,
  897. 27, 28, 29, 30, 31, 32, 33, 35, 37, 39, 41, 43,
  898. 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67,
  899. 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91,
  900. 93, 95, 97, 99, 101, 103, 105, 107, 109, 111, 113, 115,
  901. 117, 119, 121, 123, 125, 127, 129, 131, 133, 135, 137, 139,
  902. 141, 143, 145, 147, 149, 151, 153, 155, 157, 159
  903. };
  904. int bits, offset;
  905. /* position of pulse */
  906. s->aw_idx_is_ext = 0;
  907. if ((bits = get_bits(gb, 6)) >= 54) {
  908. s->aw_idx_is_ext = 1;
  909. bits += (bits - 54) * 3 + get_bits(gb, 2);
  910. }
  911. /* for a repeated pulse at pulse_off with a pitch_lag of pitch[], count
  912. * the distribution of the pulses in each block contained in this frame. */
  913. s->aw_pulse_range = FFMIN(pitch[0], pitch[1]) > 32 ? 24 : 16;
  914. for (offset = start_offset[bits]; offset < 0; offset += pitch[0]) ;
  915. s->aw_n_pulses[0] = (pitch[0] - 1 + MAX_FRAMESIZE / 2 - offset) / pitch[0];
  916. s->aw_first_pulse_off[0] = offset - s->aw_pulse_range / 2;
  917. offset += s->aw_n_pulses[0] * pitch[0];
  918. s->aw_n_pulses[1] = (pitch[1] - 1 + MAX_FRAMESIZE - offset) / pitch[1];
  919. s->aw_first_pulse_off[1] = offset - (MAX_FRAMESIZE + s->aw_pulse_range) / 2;
  920. /* if continuing from a position before the block, reset position to
  921. * start of block (when corrected for the range over which it can be
  922. * spread in aw_pulse_set1()). */
  923. if (start_offset[bits] < MAX_FRAMESIZE / 2) {
  924. while (s->aw_first_pulse_off[1] - pitch[1] + s->aw_pulse_range > 0)
  925. s->aw_first_pulse_off[1] -= pitch[1];
  926. if (start_offset[bits] < 0)
  927. while (s->aw_first_pulse_off[0] - pitch[0] + s->aw_pulse_range > 0)
  928. s->aw_first_pulse_off[0] -= pitch[0];
  929. }
  930. }
  931. /**
  932. * Apply second set of pitch-adaptive window pulses.
  933. * @param s WMA Voice decoding context private data
  934. * @param gb bit I/O context
  935. * @param block_idx block index in frame [0, 1]
  936. * @param fcb structure containing fixed codebook vector info
  937. */
  938. static void aw_pulse_set2(WMAVoiceContext *s, GetBitContext *gb,
  939. int block_idx, AMRFixed *fcb)
  940. {
  941. uint16_t use_mask_mem[9]; // only 5 are used, rest is padding
  942. uint16_t *use_mask = use_mask_mem + 2;
  943. /* in this function, idx is the index in the 80-bit (+ padding) use_mask
  944. * bit-array. Since use_mask consists of 16-bit values, the lower 4 bits
  945. * of idx are the position of the bit within a particular item in the
  946. * array (0 being the most significant bit, and 15 being the least
  947. * significant bit), and the remainder (>> 4) is the index in the
  948. * use_mask[]-array. This is faster and uses less memory than using a
  949. * 80-byte/80-int array. */
  950. int pulse_off = s->aw_first_pulse_off[block_idx],
  951. pulse_start, n, idx, range, aidx, start_off = 0;
  952. /* set offset of first pulse to within this block */
  953. if (s->aw_n_pulses[block_idx] > 0)
  954. while (pulse_off + s->aw_pulse_range < 1)
  955. pulse_off += fcb->pitch_lag;
  956. /* find range per pulse */
  957. if (s->aw_n_pulses[0] > 0) {
  958. if (block_idx == 0) {
  959. range = 32;
  960. } else /* block_idx = 1 */ {
  961. range = 8;
  962. if (s->aw_n_pulses[block_idx] > 0)
  963. pulse_off = s->aw_next_pulse_off_cache;
  964. }
  965. } else
  966. range = 16;
  967. pulse_start = s->aw_n_pulses[block_idx] > 0 ? pulse_off - range / 2 : 0;
  968. /* aw_pulse_set1() already applies pulses around pulse_off (to be exactly,
  969. * in the range of [pulse_off, pulse_off + s->aw_pulse_range], and thus
  970. * we exclude that range from being pulsed again in this function. */
  971. memset(&use_mask[-2], 0, 2 * sizeof(use_mask[0]));
  972. memset( use_mask, -1, 5 * sizeof(use_mask[0]));
  973. memset(&use_mask[5], 0, 2 * sizeof(use_mask[0]));
  974. if (s->aw_n_pulses[block_idx] > 0)
  975. for (idx = pulse_off; idx < MAX_FRAMESIZE / 2; idx += fcb->pitch_lag) {
  976. int excl_range = s->aw_pulse_range; // always 16 or 24
  977. uint16_t *use_mask_ptr = &use_mask[idx >> 4];
  978. int first_sh = 16 - (idx & 15);
  979. *use_mask_ptr++ &= 0xFFFF << first_sh;
  980. excl_range -= first_sh;
  981. if (excl_range >= 16) {
  982. *use_mask_ptr++ = 0;
  983. *use_mask_ptr &= 0xFFFF >> (excl_range - 16);
  984. } else
  985. *use_mask_ptr &= 0xFFFF >> excl_range;
  986. }
  987. /* find the 'aidx'th offset that is not excluded */
  988. aidx = get_bits(gb, s->aw_n_pulses[0] > 0 ? 5 - 2 * block_idx : 4);
  989. for (n = 0; n <= aidx; pulse_start++) {
  990. for (idx = pulse_start; idx < 0; idx += fcb->pitch_lag) ;
  991. if (idx >= MAX_FRAMESIZE / 2) { // find from zero
  992. if (use_mask[0]) idx = 0x0F;
  993. else if (use_mask[1]) idx = 0x1F;
  994. else if (use_mask[2]) idx = 0x2F;
  995. else if (use_mask[3]) idx = 0x3F;
  996. else if (use_mask[4]) idx = 0x4F;
  997. else return;
  998. idx -= av_log2_16bit(use_mask[idx >> 4]);
  999. }
  1000. if (use_mask[idx >> 4] & (0x8000 >> (idx & 15))) {
  1001. use_mask[idx >> 4] &= ~(0x8000 >> (idx & 15));
  1002. n++;
  1003. start_off = idx;
  1004. }
  1005. }
  1006. fcb->x[fcb->n] = start_off;
  1007. fcb->y[fcb->n] = get_bits1(gb) ? -1.0 : 1.0;
  1008. fcb->n++;
  1009. /* set offset for next block, relative to start of that block */
  1010. n = (MAX_FRAMESIZE / 2 - start_off) % fcb->pitch_lag;
  1011. s->aw_next_pulse_off_cache = n ? fcb->pitch_lag - n : 0;
  1012. }
  1013. /**
  1014. * Apply first set of pitch-adaptive window pulses.
  1015. * @param s WMA Voice decoding context private data
  1016. * @param gb bit I/O context
  1017. * @param block_idx block index in frame [0, 1]
  1018. * @param fcb storage location for fixed codebook pulse info
  1019. */
  1020. static void aw_pulse_set1(WMAVoiceContext *s, GetBitContext *gb,
  1021. int block_idx, AMRFixed *fcb)
  1022. {
  1023. int val = get_bits(gb, 12 - 2 * (s->aw_idx_is_ext && !block_idx));
  1024. float v;
  1025. if (s->aw_n_pulses[block_idx] > 0) {
  1026. int n, v_mask, i_mask, sh, n_pulses;
  1027. if (s->aw_pulse_range == 24) { // 3 pulses, 1:sign + 3:index each
  1028. n_pulses = 3;
  1029. v_mask = 8;
  1030. i_mask = 7;
  1031. sh = 4;
  1032. } else { // 4 pulses, 1:sign + 2:index each
  1033. n_pulses = 4;
  1034. v_mask = 4;
  1035. i_mask = 3;
  1036. sh = 3;
  1037. }
  1038. for (n = n_pulses - 1; n >= 0; n--, val >>= sh) {
  1039. fcb->y[fcb->n] = (val & v_mask) ? -1.0 : 1.0;
  1040. fcb->x[fcb->n] = (val & i_mask) * n_pulses + n +
  1041. s->aw_first_pulse_off[block_idx];
  1042. while (fcb->x[fcb->n] < 0)
  1043. fcb->x[fcb->n] += fcb->pitch_lag;
  1044. if (fcb->x[fcb->n] < MAX_FRAMESIZE / 2)
  1045. fcb->n++;
  1046. }
  1047. } else {
  1048. int num2 = (val & 0x1FF) >> 1, delta, idx;
  1049. if (num2 < 1 * 79) { delta = 1; idx = num2 + 1; }
  1050. else if (num2 < 2 * 78) { delta = 3; idx = num2 + 1 - 1 * 77; }
  1051. else if (num2 < 3 * 77) { delta = 5; idx = num2 + 1 - 2 * 76; }
  1052. else { delta = 7; idx = num2 + 1 - 3 * 75; }
  1053. v = (val & 0x200) ? -1.0 : 1.0;
  1054. fcb->no_repeat_mask |= 3 << fcb->n;
  1055. fcb->x[fcb->n] = idx - delta;
  1056. fcb->y[fcb->n] = v;
  1057. fcb->x[fcb->n + 1] = idx;
  1058. fcb->y[fcb->n + 1] = (val & 1) ? -v : v;
  1059. fcb->n += 2;
  1060. }
  1061. }
  1062. /**
  1063. * @}
  1064. *
  1065. * Generate a random number from frame_cntr and block_idx, which will lief
  1066. * in the range [0, 1000 - block_size] (so it can be used as an index in a
  1067. * table of size 1000 of which you want to read block_size entries).
  1068. *
  1069. * @param frame_cntr current frame number
  1070. * @param block_num current block index
  1071. * @param block_size amount of entries we want to read from a table
  1072. * that has 1000 entries
  1073. * @return a (non-)random number in the [0, 1000 - block_size] range.
  1074. */
  1075. static int pRNG(int frame_cntr, int block_num, int block_size)
  1076. {
  1077. /* array to simplify the calculation of z:
  1078. * y = (x % 9) * 5 + 6;
  1079. * z = (49995 * x) / y;
  1080. * Since y only has 9 values, we can remove the division by using a
  1081. * LUT and using FASTDIV-style divisions. For each of the 9 values
  1082. * of y, we can rewrite z as:
  1083. * z = x * (49995 / y) + x * ((49995 % y) / y)
  1084. * In this table, each col represents one possible value of y, the
  1085. * first number is 49995 / y, and the second is the FASTDIV variant
  1086. * of 49995 % y / y. */
  1087. static const unsigned int div_tbl[9][2] = {
  1088. { 8332, 3 * 715827883U }, // y = 6
  1089. { 4545, 0 * 390451573U }, // y = 11
  1090. { 3124, 11 * 268435456U }, // y = 16
  1091. { 2380, 15 * 204522253U }, // y = 21
  1092. { 1922, 23 * 165191050U }, // y = 26
  1093. { 1612, 23 * 138547333U }, // y = 31
  1094. { 1388, 27 * 119304648U }, // y = 36
  1095. { 1219, 16 * 104755300U }, // y = 41
  1096. { 1086, 39 * 93368855U } // y = 46
  1097. };
  1098. unsigned int z, y, x = MUL16(block_num, 1877) + frame_cntr;
  1099. if (x >= 0xFFFF) x -= 0xFFFF; // max value of x is 8*1877+0xFFFE=0x13AA6,
  1100. // so this is effectively a modulo (%)
  1101. y = x - 9 * MULH(477218589, x); // x % 9
  1102. z = (uint16_t) (x * div_tbl[y][0] + UMULH(x, div_tbl[y][1]));
  1103. // z = x * 49995 / (y * 5 + 6)
  1104. return z % (1000 - block_size);
  1105. }
  1106. /**
  1107. * Parse hardcoded signal for a single block.
  1108. * @note see #synth_block().
  1109. */
  1110. static void synth_block_hardcoded(WMAVoiceContext *s, GetBitContext *gb,
  1111. int block_idx, int size,
  1112. const struct frame_type_desc *frame_desc,
  1113. float *excitation)
  1114. {
  1115. float gain;
  1116. int n, r_idx;
  1117. assert(size <= MAX_FRAMESIZE);
  1118. /* Set the offset from which we start reading wmavoice_std_codebook */
  1119. if (frame_desc->fcb_type == FCB_TYPE_SILENCE) {
  1120. r_idx = pRNG(s->frame_cntr, block_idx, size);
  1121. gain = s->silence_gain;
  1122. } else /* FCB_TYPE_HARDCODED */ {
  1123. r_idx = get_bits(gb, 8);
  1124. gain = wmavoice_gain_universal[get_bits(gb, 6)];
  1125. }
  1126. /* Clear gain prediction parameters */
  1127. memset(s->gain_pred_err, 0, sizeof(s->gain_pred_err));
  1128. /* Apply gain to hardcoded codebook and use that as excitation signal */
  1129. for (n = 0; n < size; n++)
  1130. excitation[n] = wmavoice_std_codebook[r_idx + n] * gain;
  1131. }
  1132. /**
  1133. * Parse FCB/ACB signal for a single block.
  1134. * @note see #synth_block().
  1135. */
  1136. static void synth_block_fcb_acb(WMAVoiceContext *s, GetBitContext *gb,
  1137. int block_idx, int size,
  1138. int block_pitch_sh2,
  1139. const struct frame_type_desc *frame_desc,
  1140. float *excitation)
  1141. {
  1142. static const float gain_coeff[6] = {
  1143. 0.8169, -0.06545, 0.1726, 0.0185, -0.0359, 0.0458
  1144. };
  1145. float pulses[MAX_FRAMESIZE / 2], pred_err, acb_gain, fcb_gain;
  1146. int n, idx, gain_weight;
  1147. AMRFixed fcb;
  1148. assert(size <= MAX_FRAMESIZE / 2);
  1149. memset(pulses, 0, sizeof(*pulses) * size);
  1150. fcb.pitch_lag = block_pitch_sh2 >> 2;
  1151. fcb.pitch_fac = 1.0;
  1152. fcb.no_repeat_mask = 0;
  1153. fcb.n = 0;
  1154. /* For the other frame types, this is where we apply the innovation
  1155. * (fixed) codebook pulses of the speech signal. */
  1156. if (frame_desc->fcb_type == FCB_TYPE_AW_PULSES) {
  1157. aw_pulse_set1(s, gb, block_idx, &fcb);
  1158. aw_pulse_set2(s, gb, block_idx, &fcb);
  1159. } else /* FCB_TYPE_EXC_PULSES */ {
  1160. int offset_nbits = 5 - frame_desc->log_n_blocks;
  1161. fcb.no_repeat_mask = -1;
  1162. /* similar to ff_decode_10_pulses_35bits(), but with single pulses
  1163. * (instead of double) for a subset of pulses */
  1164. for (n = 0; n < 5; n++) {
  1165. float sign;
  1166. int pos1, pos2;
  1167. sign = get_bits1(gb) ? 1.0 : -1.0;
  1168. pos1 = get_bits(gb, offset_nbits);
  1169. fcb.x[fcb.n] = n + 5 * pos1;
  1170. fcb.y[fcb.n++] = sign;
  1171. if (n < frame_desc->dbl_pulses) {
  1172. pos2 = get_bits(gb, offset_nbits);
  1173. fcb.x[fcb.n] = n + 5 * pos2;
  1174. fcb.y[fcb.n++] = (pos1 < pos2) ? -sign : sign;
  1175. }
  1176. }
  1177. }
  1178. ff_set_fixed_vector(pulses, &fcb, 1.0, size);
  1179. /* Calculate gain for adaptive & fixed codebook signal.
  1180. * see ff_amr_set_fixed_gain(). */
  1181. idx = get_bits(gb, 7);
  1182. fcb_gain = expf(ff_dot_productf(s->gain_pred_err, gain_coeff, 6) -
  1183. 5.2409161640 + wmavoice_gain_codebook_fcb[idx]);
  1184. acb_gain = wmavoice_gain_codebook_acb[idx];
  1185. pred_err = av_clipf(wmavoice_gain_codebook_fcb[idx],
  1186. -2.9957322736 /* log(0.05) */,
  1187. 1.6094379124 /* log(5.0) */);
  1188. gain_weight = 8 >> frame_desc->log_n_blocks;
  1189. memmove(&s->gain_pred_err[gain_weight], s->gain_pred_err,
  1190. sizeof(*s->gain_pred_err) * (6 - gain_weight));
  1191. for (n = 0; n < gain_weight; n++)
  1192. s->gain_pred_err[n] = pred_err;
  1193. /* Calculation of adaptive codebook */
  1194. if (frame_desc->acb_type == ACB_TYPE_ASYMMETRIC) {
  1195. int len;
  1196. for (n = 0; n < size; n += len) {
  1197. int next_idx_sh16;
  1198. int abs_idx = block_idx * size + n;
  1199. int pitch_sh16 = (s->last_pitch_val << 16) +
  1200. s->pitch_diff_sh16 * abs_idx;
  1201. int pitch = (pitch_sh16 + 0x6FFF) >> 16;
  1202. int idx_sh16 = ((pitch << 16) - pitch_sh16) * 8 + 0x58000;
  1203. idx = idx_sh16 >> 16;
  1204. if (s->pitch_diff_sh16) {
  1205. if (s->pitch_diff_sh16 > 0) {
  1206. next_idx_sh16 = (idx_sh16) &~ 0xFFFF;
  1207. } else
  1208. next_idx_sh16 = (idx_sh16 + 0x10000) &~ 0xFFFF;
  1209. len = av_clip((idx_sh16 - next_idx_sh16) / s->pitch_diff_sh16 / 8,
  1210. 1, size - n);
  1211. } else
  1212. len = size;
  1213. ff_acelp_interpolatef(&excitation[n], &excitation[n - pitch],
  1214. wmavoice_ipol1_coeffs, 17,
  1215. idx, 9, len);
  1216. }
  1217. } else /* ACB_TYPE_HAMMING */ {
  1218. int block_pitch = block_pitch_sh2 >> 2;
  1219. idx = block_pitch_sh2 & 3;
  1220. if (idx) {
  1221. ff_acelp_interpolatef(excitation, &excitation[-block_pitch],
  1222. wmavoice_ipol2_coeffs, 4,
  1223. idx, 8, size);
  1224. } else
  1225. av_memcpy_backptr((uint8_t *) excitation, sizeof(float) * block_pitch,
  1226. sizeof(float) * size);
  1227. }
  1228. /* Interpolate ACB/FCB and use as excitation signal */
  1229. ff_weighted_vector_sumf(excitation, excitation, pulses,
  1230. acb_gain, fcb_gain, size);
  1231. }
  1232. /**
  1233. * Parse data in a single block.
  1234. * @note we assume enough bits are available, caller should check.
  1235. *
  1236. * @param s WMA Voice decoding context private data
  1237. * @param gb bit I/O context
  1238. * @param block_idx index of the to-be-read block
  1239. * @param size amount of samples to be read in this block
  1240. * @param block_pitch_sh2 pitch for this block << 2
  1241. * @param lsps LSPs for (the end of) this frame
  1242. * @param prev_lsps LSPs for the last frame
  1243. * @param frame_desc frame type descriptor
  1244. * @param excitation target memory for the ACB+FCB interpolated signal
  1245. * @param synth target memory for the speech synthesis filter output
  1246. * @return 0 on success, <0 on error.
  1247. */
  1248. static void synth_block(WMAVoiceContext *s, GetBitContext *gb,
  1249. int block_idx, int size,
  1250. int block_pitch_sh2,
  1251. const double *lsps, const double *prev_lsps,
  1252. const struct frame_type_desc *frame_desc,
  1253. float *excitation, float *synth)
  1254. {
  1255. double i_lsps[MAX_LSPS];
  1256. float lpcs[MAX_LSPS];
  1257. float fac;
  1258. int n;
  1259. if (frame_desc->acb_type == ACB_TYPE_NONE)
  1260. synth_block_hardcoded(s, gb, block_idx, size, frame_desc, excitation);
  1261. else
  1262. synth_block_fcb_acb(s, gb, block_idx, size, block_pitch_sh2,
  1263. frame_desc, excitation);
  1264. /* convert interpolated LSPs to LPCs */
  1265. fac = (block_idx + 0.5) / frame_desc->n_blocks;
  1266. for (n = 0; n < s->lsps; n++) // LSF -> LSP
  1267. i_lsps[n] = cos(prev_lsps[n] + fac * (lsps[n] - prev_lsps[n]));
  1268. ff_acelp_lspd2lpc(i_lsps, lpcs, s->lsps >> 1);
  1269. /* Speech synthesis */
  1270. ff_celp_lp_synthesis_filterf(synth, lpcs, excitation, size, s->lsps);
  1271. }
  1272. /**
  1273. * Synthesize output samples for a single frame.
  1274. * @note we assume enough bits are available, caller should check.
  1275. *
  1276. * @param ctx WMA Voice decoder context
  1277. * @param gb bit I/O context (s->gb or one for cross-packet superframes)
  1278. * @param frame_idx Frame number within superframe [0-2]
  1279. * @param samples pointer to output sample buffer, has space for at least 160
  1280. * samples
  1281. * @param lsps LSP array
  1282. * @param prev_lsps array of previous frame's LSPs
  1283. * @param excitation target buffer for excitation signal
  1284. * @param synth target buffer for synthesized speech data
  1285. * @return 0 on success, <0 on error.
  1286. */
  1287. static int synth_frame(AVCodecContext *ctx, GetBitContext *gb, int frame_idx,
  1288. float *samples,
  1289. const double *lsps, const double *prev_lsps,
  1290. float *excitation, float *synth)
  1291. {
  1292. WMAVoiceContext *s = ctx->priv_data;
  1293. int n, n_blocks_x2, log_n_blocks_x2, cur_pitch_val;
  1294. int pitch[MAX_BLOCKS], last_block_pitch;
  1295. /* Parse frame type ("frame header"), see frame_descs */
  1296. int bd_idx = s->vbm_tree[get_vlc2(gb, frame_type_vlc.table, 6, 3)],
  1297. block_nsamples = MAX_FRAMESIZE / frame_descs[bd_idx].n_blocks;
  1298. if (bd_idx < 0) {
  1299. av_log(ctx, AV_LOG_ERROR,
  1300. "Invalid frame type VLC code, skipping\n");
  1301. return -1;
  1302. }
  1303. /* Pitch calculation for ACB_TYPE_ASYMMETRIC ("pitch-per-frame") */
  1304. if (frame_descs[bd_idx].acb_type == ACB_TYPE_ASYMMETRIC) {
  1305. /* Pitch is provided per frame, which is interpreted as the pitch of
  1306. * the last sample of the last block of this frame. We can interpolate
  1307. * the pitch of other blocks (and even pitch-per-sample) by gradually
  1308. * incrementing/decrementing prev_frame_pitch to cur_pitch_val. */
  1309. n_blocks_x2 = frame_descs[bd_idx].n_blocks << 1;
  1310. log_n_blocks_x2 = frame_descs[bd_idx].log_n_blocks + 1;
  1311. cur_pitch_val = s->min_pitch_val + get_bits(gb, s->pitch_nbits);
  1312. cur_pitch_val = FFMIN(cur_pitch_val, s->max_pitch_val - 1);
  1313. if (s->last_acb_type == ACB_TYPE_NONE ||
  1314. 20 * abs(cur_pitch_val - s->last_pitch_val) >
  1315. (cur_pitch_val + s->last_pitch_val))
  1316. s->last_pitch_val = cur_pitch_val;
  1317. /* pitch per block */
  1318. for (n = 0; n < frame_descs[bd_idx].n_blocks; n++) {
  1319. int fac = n * 2 + 1;
  1320. pitch[n] = (MUL16(fac, cur_pitch_val) +
  1321. MUL16((n_blocks_x2 - fac), s->last_pitch_val) +
  1322. frame_descs[bd_idx].n_blocks) >> log_n_blocks_x2;
  1323. }
  1324. /* "pitch-diff-per-sample" for calculation of pitch per sample */
  1325. s->pitch_diff_sh16 =
  1326. ((cur_pitch_val - s->last_pitch_val) << 16) / MAX_FRAMESIZE;
  1327. }
  1328. /* Global gain (if silence) and pitch-adaptive window coordinates */
  1329. switch (frame_descs[bd_idx].fcb_type) {
  1330. case FCB_TYPE_SILENCE:
  1331. s->silence_gain = wmavoice_gain_silence[get_bits(gb, 8)];
  1332. break;
  1333. case FCB_TYPE_AW_PULSES:
  1334. aw_parse_coords(s, gb, pitch);
  1335. break;
  1336. }
  1337. for (n = 0; n < frame_descs[bd_idx].n_blocks; n++) {
  1338. int bl_pitch_sh2;
  1339. /* Pitch calculation for ACB_TYPE_HAMMING ("pitch-per-block") */
  1340. switch (frame_descs[bd_idx].acb_type) {
  1341. case ACB_TYPE_HAMMING: {
  1342. /* Pitch is given per block. Per-block pitches are encoded as an
  1343. * absolute value for the first block, and then delta values
  1344. * relative to this value) for all subsequent blocks. The scale of
  1345. * this pitch value is semi-logaritmic compared to its use in the
  1346. * decoder, so we convert it to normal scale also. */
  1347. int block_pitch,
  1348. t1 = (s->block_conv_table[1] - s->block_conv_table[0]) << 2,
  1349. t2 = (s->block_conv_table[2] - s->block_conv_table[1]) << 1,
  1350. t3 = s->block_conv_table[3] - s->block_conv_table[2] + 1;
  1351. if (n == 0) {
  1352. block_pitch = get_bits(gb, s->block_pitch_nbits);
  1353. } else
  1354. block_pitch = last_block_pitch - s->block_delta_pitch_hrange +
  1355. get_bits(gb, s->block_delta_pitch_nbits);
  1356. /* Convert last_ so that any next delta is within _range */
  1357. last_block_pitch = av_clip(block_pitch,
  1358. s->block_delta_pitch_hrange,
  1359. s->block_pitch_range -
  1360. s->block_delta_pitch_hrange);
  1361. /* Convert semi-log-style scale back to normal scale */
  1362. if (block_pitch < t1) {
  1363. bl_pitch_sh2 = (s->block_conv_table[0] << 2) + block_pitch;
  1364. } else {
  1365. block_pitch -= t1;
  1366. if (block_pitch < t2) {
  1367. bl_pitch_sh2 =
  1368. (s->block_conv_table[1] << 2) + (block_pitch << 1);
  1369. } else {
  1370. block_pitch -= t2;
  1371. if (block_pitch < t3) {
  1372. bl_pitch_sh2 =
  1373. (s->block_conv_table[2] + block_pitch) << 2;
  1374. } else
  1375. bl_pitch_sh2 = s->block_conv_table[3] << 2;
  1376. }
  1377. }
  1378. pitch[n] = bl_pitch_sh2 >> 2;
  1379. break;
  1380. }
  1381. case ACB_TYPE_ASYMMETRIC: {
  1382. bl_pitch_sh2 = pitch[n] << 2;
  1383. break;
  1384. }
  1385. default: // ACB_TYPE_NONE has no pitch
  1386. bl_pitch_sh2 = 0;
  1387. break;
  1388. }
  1389. synth_block(s, gb, n, block_nsamples, bl_pitch_sh2,
  1390. lsps, prev_lsps, &frame_descs[bd_idx],
  1391. &excitation[n * block_nsamples],
  1392. &synth[n * block_nsamples]);
  1393. }
  1394. /* Averaging projection filter, if applicable. Else, just copy samples
  1395. * from synthesis buffer */
  1396. if (s->do_apf) {
  1397. double i_lsps[MAX_LSPS];
  1398. float lpcs[MAX_LSPS];
  1399. for (n = 0; n < s->lsps; n++) // LSF -> LSP
  1400. i_lsps[n] = cos(0.5 * (prev_lsps[n] + lsps[n]));
  1401. ff_acelp_lspd2lpc(i_lsps, lpcs, s->lsps >> 1);
  1402. postfilter(s, synth, samples, 80, lpcs,
  1403. &s->zero_exc_pf[s->history_nsamples + MAX_FRAMESIZE * frame_idx],
  1404. frame_descs[bd_idx].fcb_type, pitch[0]);
  1405. for (n = 0; n < s->lsps; n++) // LSF -> LSP
  1406. i_lsps[n] = cos(lsps[n]);
  1407. ff_acelp_lspd2lpc(i_lsps, lpcs, s->lsps >> 1);
  1408. postfilter(s, &synth[80], &samples[80], 80, lpcs,
  1409. &s->zero_exc_pf[s->history_nsamples + MAX_FRAMESIZE * frame_idx + 80],
  1410. frame_descs[bd_idx].fcb_type, pitch[0]);
  1411. } else
  1412. memcpy(samples, synth, 160 * sizeof(synth[0]));
  1413. /* Cache values for next frame */
  1414. s->frame_cntr++;
  1415. if (s->frame_cntr >= 0xFFFF) s->frame_cntr -= 0xFFFF; // i.e. modulo (%)
  1416. s->last_acb_type = frame_descs[bd_idx].acb_type;
  1417. switch (frame_descs[bd_idx].acb_type) {
  1418. case ACB_TYPE_NONE:
  1419. s->last_pitch_val = 0;
  1420. break;
  1421. case ACB_TYPE_ASYMMETRIC:
  1422. s->last_pitch_val = cur_pitch_val;
  1423. break;
  1424. case ACB_TYPE_HAMMING:
  1425. s->last_pitch_val = pitch[frame_descs[bd_idx].n_blocks - 1];
  1426. break;
  1427. }
  1428. return 0;
  1429. }
  1430. /**
  1431. * Ensure minimum value for first item, maximum value for last value,
  1432. * proper spacing between each value and proper ordering.
  1433. *
  1434. * @param lsps array of LSPs
  1435. * @param num size of LSP array
  1436. *
  1437. * @note basically a double version of #ff_acelp_reorder_lsf(), might be
  1438. * useful to put in a generic location later on. Parts are also
  1439. * present in #ff_set_min_dist_lsf() + #ff_sort_nearly_sorted_floats(),
  1440. * which is in float.
  1441. */
  1442. static void stabilize_lsps(double *lsps, int num)
  1443. {
  1444. int n, m, l;
  1445. /* set minimum value for first, maximum value for last and minimum
  1446. * spacing between LSF values.
  1447. * Very similar to ff_set_min_dist_lsf(), but in double. */
  1448. lsps[0] = FFMAX(lsps[0], 0.0015 * M_PI);
  1449. for (n = 1; n < num; n++)
  1450. lsps[n] = FFMAX(lsps[n], lsps[n - 1] + 0.0125 * M_PI);
  1451. lsps[num - 1] = FFMIN(lsps[num - 1], 0.9985 * M_PI);
  1452. /* reorder (looks like one-time / non-recursed bubblesort).
  1453. * Very similar to ff_sort_nearly_sorted_floats(), but in double. */
  1454. for (n = 1; n < num; n++) {
  1455. if (lsps[n] < lsps[n - 1]) {
  1456. for (m = 1; m < num; m++) {
  1457. double tmp = lsps[m];
  1458. for (l = m - 1; l >= 0; l--) {
  1459. if (lsps[l] <= tmp) break;
  1460. lsps[l + 1] = lsps[l];
  1461. }
  1462. lsps[l + 1] = tmp;
  1463. }
  1464. break;
  1465. }
  1466. }
  1467. }
  1468. /**
  1469. * Test if there's enough bits to read 1 superframe.
  1470. *
  1471. * @param orig_gb bit I/O context used for reading. This function
  1472. * does not modify the state of the bitreader; it
  1473. * only uses it to copy the current stream position
  1474. * @param s WMA Voice decoding context private data
  1475. * @return -1 if unsupported, 1 on not enough bits or 0 if OK.
  1476. */
  1477. static int check_bits_for_superframe(GetBitContext *orig_gb,
  1478. WMAVoiceContext *s)
  1479. {
  1480. GetBitContext s_gb, *gb = &s_gb;
  1481. int n, need_bits, bd_idx;
  1482. const struct frame_type_desc *frame_desc;
  1483. /* initialize a copy */
  1484. init_get_bits(gb, orig_gb->buffer, orig_gb->size_in_bits);
  1485. skip_bits_long(gb, get_bits_count(orig_gb));
  1486. assert(get_bits_left(gb) == get_bits_left(orig_gb));
  1487. /* superframe header */
  1488. if (get_bits_left(gb) < 14)
  1489. return 1;
  1490. if (!get_bits1(gb))
  1491. return -1; // WMAPro-in-WMAVoice superframe
  1492. if (get_bits1(gb)) skip_bits(gb, 12); // number of samples in superframe
  1493. if (s->has_residual_lsps) { // residual LSPs (for all frames)
  1494. if (get_bits_left(gb) < s->sframe_lsp_bitsize)
  1495. return 1;
  1496. skip_bits_long(gb, s->sframe_lsp_bitsize);
  1497. }
  1498. /* frames */
  1499. for (n = 0; n < MAX_FRAMES; n++) {
  1500. int aw_idx_is_ext = 0;
  1501. if (!s->has_residual_lsps) { // independent LSPs (per-frame)
  1502. if (get_bits_left(gb) < s->frame_lsp_bitsize) return 1;
  1503. skip_bits_long(gb, s->frame_lsp_bitsize);
  1504. }
  1505. bd_idx = s->vbm_tree[get_vlc2(gb, frame_type_vlc.table, 6, 3)];
  1506. if (bd_idx < 0)
  1507. return -1; // invalid frame type VLC code
  1508. frame_desc = &frame_descs[bd_idx];
  1509. if (frame_desc->acb_type == ACB_TYPE_ASYMMETRIC) {
  1510. if (get_bits_left(gb) < s->pitch_nbits)
  1511. return 1;
  1512. skip_bits_long(gb, s->pitch_nbits);
  1513. }
  1514. if (frame_desc->fcb_type == FCB_TYPE_SILENCE) {
  1515. skip_bits(gb, 8);
  1516. } else if (frame_desc->fcb_type == FCB_TYPE_AW_PULSES) {
  1517. int tmp = get_bits(gb, 6);
  1518. if (tmp >= 0x36) {
  1519. skip_bits(gb, 2);
  1520. aw_idx_is_ext = 1;
  1521. }
  1522. }
  1523. /* blocks */
  1524. if (frame_desc->acb_type == ACB_TYPE_HAMMING) {
  1525. need_bits = s->block_pitch_nbits +
  1526. (frame_desc->n_blocks - 1) * s->block_delta_pitch_nbits;
  1527. } else if (frame_desc->fcb_type == FCB_TYPE_AW_PULSES) {
  1528. need_bits = 2 * !aw_idx_is_ext;
  1529. } else
  1530. need_bits = 0;
  1531. need_bits += frame_desc->frame_size;
  1532. if (get_bits_left(gb) < need_bits)
  1533. return 1;
  1534. skip_bits_long(gb, need_bits);
  1535. }
  1536. return 0;
  1537. }
  1538. /**
  1539. * Synthesize output samples for a single superframe. If we have any data
  1540. * cached in s->sframe_cache, that will be used instead of whatever is loaded
  1541. * in s->gb.
  1542. *
  1543. * WMA Voice superframes contain 3 frames, each containing 160 audio samples,
  1544. * to give a total of 480 samples per frame. See #synth_frame() for frame
  1545. * parsing. In addition to 3 frames, superframes can also contain the LSPs
  1546. * (if these are globally specified for all frames (residually); they can
  1547. * also be specified individually per-frame. See the s->has_residual_lsps
  1548. * option), and can specify the number of samples encoded in this superframe
  1549. * (if less than 480), usually used to prevent blanks at track boundaries.
  1550. *
  1551. * @param ctx WMA Voice decoder context
  1552. * @param samples pointer to output buffer for voice samples
  1553. * @param data_size pointer containing the size of #samples on input, and the
  1554. * amount of #samples filled on output
  1555. * @return 0 on success, <0 on error or 1 if there was not enough data to
  1556. * fully parse the superframe
  1557. */
  1558. static int synth_superframe(AVCodecContext *ctx,
  1559. float *samples, int *data_size)
  1560. {
  1561. WMAVoiceContext *s = ctx->priv_data;
  1562. GetBitContext *gb = &s->gb, s_gb;
  1563. int n, res, n_samples = 480;
  1564. double lsps[MAX_FRAMES][MAX_LSPS];
  1565. const double *mean_lsf = s->lsps == 16 ?
  1566. wmavoice_mean_lsf16[s->lsp_def_mode] : wmavoice_mean_lsf10[s->lsp_def_mode];
  1567. float excitation[MAX_SIGNAL_HISTORY + MAX_SFRAMESIZE + 12];
  1568. float synth[MAX_LSPS + MAX_SFRAMESIZE];
  1569. memcpy(synth, s->synth_history,
  1570. s->lsps * sizeof(*synth));
  1571. memcpy(excitation, s->excitation_history,
  1572. s->history_nsamples * sizeof(*excitation));
  1573. if (s->sframe_cache_size > 0) {
  1574. gb = &s_gb;
  1575. init_get_bits(gb, s->sframe_cache, s->sframe_cache_size);
  1576. s->sframe_cache_size = 0;
  1577. }
  1578. if ((res = check_bits_for_superframe(gb, s)) == 1) return 1;
  1579. /* First bit is speech/music bit, it differentiates between WMAVoice
  1580. * speech samples (the actual codec) and WMAVoice music samples, which
  1581. * are really WMAPro-in-WMAVoice-superframes. I've never seen those in
  1582. * the wild yet. */
  1583. if (!get_bits1(gb)) {
  1584. av_log_missing_feature(ctx, "WMAPro-in-WMAVoice support", 1);
  1585. return -1;
  1586. }
  1587. /* (optional) nr. of samples in superframe; always <= 480 and >= 0 */
  1588. if (get_bits1(gb)) {
  1589. if ((n_samples = get_bits(gb, 12)) > 480) {
  1590. av_log(ctx, AV_LOG_ERROR,
  1591. "Superframe encodes >480 samples (%d), not allowed\n",
  1592. n_samples);
  1593. return -1;
  1594. }
  1595. }
  1596. /* Parse LSPs, if global for the superframe (can also be per-frame). */
  1597. if (s->has_residual_lsps) {
  1598. double prev_lsps[MAX_LSPS], a1[MAX_LSPS * 2], a2[MAX_LSPS * 2];
  1599. for (n = 0; n < s->lsps; n++)
  1600. prev_lsps[n] = s->prev_lsps[n] - mean_lsf[n];
  1601. if (s->lsps == 10) {
  1602. dequant_lsp10r(gb, lsps[2], prev_lsps, a1, a2, s->lsp_q_mode);
  1603. } else /* s->lsps == 16 */
  1604. dequant_lsp16r(gb, lsps[2], prev_lsps, a1, a2, s->lsp_q_mode);
  1605. for (n = 0; n < s->lsps; n++) {
  1606. lsps[0][n] = mean_lsf[n] + (a1[n] - a2[n * 2]);
  1607. lsps[1][n] = mean_lsf[n] + (a1[s->lsps + n] - a2[n * 2 + 1]);
  1608. lsps[2][n] += mean_lsf[n];
  1609. }
  1610. for (n = 0; n < 3; n++)
  1611. stabilize_lsps(lsps[n], s->lsps);
  1612. }
  1613. /* Parse frames, optionally preceeded by per-frame (independent) LSPs. */
  1614. for (n = 0; n < 3; n++) {
  1615. if (!s->has_residual_lsps) {
  1616. int m;
  1617. if (s->lsps == 10) {
  1618. dequant_lsp10i(gb, lsps[n]);
  1619. } else /* s->lsps == 16 */
  1620. dequant_lsp16i(gb, lsps[n]);
  1621. for (m = 0; m < s->lsps; m++)
  1622. lsps[n][m] += mean_lsf[m];
  1623. stabilize_lsps(lsps[n], s->lsps);
  1624. }
  1625. if ((res = synth_frame(ctx, gb, n,
  1626. &samples[n * MAX_FRAMESIZE],
  1627. lsps[n], n == 0 ? s->prev_lsps : lsps[n - 1],
  1628. &excitation[s->history_nsamples + n * MAX_FRAMESIZE],
  1629. &synth[s->lsps + n * MAX_FRAMESIZE])))
  1630. return res;
  1631. }
  1632. /* Statistics? FIXME - we don't check for length, a slight overrun
  1633. * will be caught by internal buffer padding, and anything else
  1634. * will be skipped, not read. */
  1635. if (get_bits1(gb)) {
  1636. res = get_bits(gb, 4);
  1637. skip_bits(gb, 10 * (res + 1));
  1638. }
  1639. /* Specify nr. of output samples */
  1640. *data_size = n_samples * sizeof(float);
  1641. /* Update history */
  1642. memcpy(s->prev_lsps, lsps[2],
  1643. s->lsps * sizeof(*s->prev_lsps));
  1644. memcpy(s->synth_history, &synth[MAX_SFRAMESIZE],
  1645. s->lsps * sizeof(*synth));
  1646. memcpy(s->excitation_history, &excitation[MAX_SFRAMESIZE],
  1647. s->history_nsamples * sizeof(*excitation));
  1648. if (s->do_apf)
  1649. memmove(s->zero_exc_pf, &s->zero_exc_pf[MAX_SFRAMESIZE],
  1650. s->history_nsamples * sizeof(*s->zero_exc_pf));
  1651. return 0;
  1652. }
  1653. /**
  1654. * Parse the packet header at the start of each packet (input data to this
  1655. * decoder).
  1656. *
  1657. * @param s WMA Voice decoding context private data
  1658. * @return 1 if not enough bits were available, or 0 on success.
  1659. */
  1660. static int parse_packet_header(WMAVoiceContext *s)
  1661. {
  1662. GetBitContext *gb = &s->gb;
  1663. unsigned int res;
  1664. if (get_bits_left(gb) < 11)
  1665. return 1;
  1666. skip_bits(gb, 4); // packet sequence number
  1667. s->has_residual_lsps = get_bits1(gb);
  1668. do {
  1669. res = get_bits(gb, 6); // number of superframes per packet
  1670. // (minus first one if there is spillover)
  1671. if (get_bits_left(gb) < 6 * (res == 0x3F) + s->spillover_bitsize)
  1672. return 1;
  1673. } while (res == 0x3F);
  1674. s->spillover_nbits = get_bits(gb, s->spillover_bitsize);
  1675. return 0;
  1676. }
  1677. /**
  1678. * Copy (unaligned) bits from gb/data/size to pb.
  1679. *
  1680. * @param pb target buffer to copy bits into
  1681. * @param data source buffer to copy bits from
  1682. * @param size size of the source data, in bytes
  1683. * @param gb bit I/O context specifying the current position in the source.
  1684. * data. This function might use this to align the bit position to
  1685. * a whole-byte boundary before calling #ff_copy_bits() on aligned
  1686. * source data
  1687. * @param nbits the amount of bits to copy from source to target
  1688. *
  1689. * @note after calling this function, the current position in the input bit
  1690. * I/O context is undefined.
  1691. */
  1692. static void copy_bits(PutBitContext *pb,
  1693. const uint8_t *data, int size,
  1694. GetBitContext *gb, int nbits)
  1695. {
  1696. int rmn_bytes, rmn_bits;
  1697. rmn_bits = rmn_bytes = get_bits_left(gb);
  1698. if (rmn_bits < nbits)
  1699. return;
  1700. rmn_bits &= 7; rmn_bytes >>= 3;
  1701. if ((rmn_bits = FFMIN(rmn_bits, nbits)) > 0)
  1702. put_bits(pb, rmn_bits, get_bits(gb, rmn_bits));
  1703. ff_copy_bits(pb, data + size - rmn_bytes,
  1704. FFMIN(nbits - rmn_bits, rmn_bytes << 3));
  1705. }
  1706. /**
  1707. * Packet decoding: a packet is anything that the (ASF) demuxer contains,
  1708. * and we expect that the demuxer / application provides it to us as such
  1709. * (else you'll probably get garbage as output). Every packet has a size of
  1710. * ctx->block_align bytes, starts with a packet header (see
  1711. * #parse_packet_header()), and then a series of superframes. Superframe
  1712. * boundaries may exceed packets, i.e. superframes can split data over
  1713. * multiple (two) packets.
  1714. *
  1715. * For more information about frames, see #synth_superframe().
  1716. */
  1717. static int wmavoice_decode_packet(AVCodecContext *ctx, void *data,
  1718. int *data_size, AVPacket *avpkt)
  1719. {
  1720. WMAVoiceContext *s = ctx->priv_data;
  1721. GetBitContext *gb = &s->gb;
  1722. int size, res, pos;
  1723. if (*data_size < 480 * sizeof(float)) {
  1724. av_log(ctx, AV_LOG_ERROR,
  1725. "Output buffer too small (%d given - %zu needed)\n",
  1726. *data_size, 480 * sizeof(float));
  1727. return -1;
  1728. }
  1729. *data_size = 0;
  1730. /* Packets are sometimes a multiple of ctx->block_align, with a packet
  1731. * header at each ctx->block_align bytes. However, FFmpeg's ASF demuxer
  1732. * feeds us ASF packets, which may concatenate multiple "codec" packets
  1733. * in a single "muxer" packet, so we artificially emulate that by
  1734. * capping the packet size at ctx->block_align. */
  1735. for (size = avpkt->size; size > ctx->block_align; size -= ctx->block_align);
  1736. if (!size)
  1737. return 0;
  1738. init_get_bits(&s->gb, avpkt->data, size << 3);
  1739. /* size == ctx->block_align is used to indicate whether we are dealing with
  1740. * a new packet or a packet of which we already read the packet header
  1741. * previously. */
  1742. if (size == ctx->block_align) { // new packet header
  1743. if ((res = parse_packet_header(s)) < 0)
  1744. return res;
  1745. /* If the packet header specifies a s->spillover_nbits, then we want
  1746. * to push out all data of the previous packet (+ spillover) before
  1747. * continuing to parse new superframes in the current packet. */
  1748. if (s->spillover_nbits > 0) {
  1749. if (s->sframe_cache_size > 0) {
  1750. int cnt = get_bits_count(gb);
  1751. copy_bits(&s->pb, avpkt->data, size, gb, s->spillover_nbits);
  1752. flush_put_bits(&s->pb);
  1753. s->sframe_cache_size += s->spillover_nbits;
  1754. if ((res = synth_superframe(ctx, data, data_size)) == 0 &&
  1755. *data_size > 0) {
  1756. cnt += s->spillover_nbits;
  1757. s->skip_bits_next = cnt & 7;
  1758. return cnt >> 3;
  1759. } else
  1760. skip_bits_long (gb, s->spillover_nbits - cnt +
  1761. get_bits_count(gb)); // resync
  1762. } else
  1763. skip_bits_long(gb, s->spillover_nbits); // resync
  1764. }
  1765. } else if (s->skip_bits_next)
  1766. skip_bits(gb, s->skip_bits_next);
  1767. /* Try parsing superframes in current packet */
  1768. s->sframe_cache_size = 0;
  1769. s->skip_bits_next = 0;
  1770. pos = get_bits_left(gb);
  1771. if ((res = synth_superframe(ctx, data, data_size)) < 0) {
  1772. return res;
  1773. } else if (*data_size > 0) {
  1774. int cnt = get_bits_count(gb);
  1775. s->skip_bits_next = cnt & 7;
  1776. return cnt >> 3;
  1777. } else if ((s->sframe_cache_size = pos) > 0) {
  1778. /* rewind bit reader to start of last (incomplete) superframe... */
  1779. init_get_bits(gb, avpkt->data, size << 3);
  1780. skip_bits_long(gb, (size << 3) - pos);
  1781. assert(get_bits_left(gb) == pos);
  1782. /* ...and cache it for spillover in next packet */
  1783. init_put_bits(&s->pb, s->sframe_cache, SFRAME_CACHE_MAXSIZE);
  1784. copy_bits(&s->pb, avpkt->data, size, gb, s->sframe_cache_size);
  1785. // FIXME bad - just copy bytes as whole and add use the
  1786. // skip_bits_next field
  1787. }
  1788. return size;
  1789. }
  1790. static av_cold int wmavoice_decode_end(AVCodecContext *ctx)
  1791. {
  1792. WMAVoiceContext *s = ctx->priv_data;
  1793. if (s->do_apf) {
  1794. ff_rdft_end(&s->rdft);
  1795. ff_rdft_end(&s->irdft);
  1796. ff_dct_end(&s->dct);
  1797. ff_dct_end(&s->dst);
  1798. }
  1799. return 0;
  1800. }
  1801. static av_cold void wmavoice_flush(AVCodecContext *ctx)
  1802. {
  1803. WMAVoiceContext *s = ctx->priv_data;
  1804. int n;
  1805. s->postfilter_agc = 0;
  1806. s->sframe_cache_size = 0;
  1807. s->skip_bits_next = 0;
  1808. for (n = 0; n < s->lsps; n++)
  1809. s->prev_lsps[n] = M_PI * (n + 1.0) / (s->lsps + 1.0);
  1810. memset(s->excitation_history, 0,
  1811. sizeof(*s->excitation_history) * MAX_SIGNAL_HISTORY);
  1812. memset(s->synth_history, 0,
  1813. sizeof(*s->synth_history) * MAX_LSPS);
  1814. memset(s->gain_pred_err, 0,
  1815. sizeof(s->gain_pred_err));
  1816. if (s->do_apf) {
  1817. memset(&s->synth_filter_out_buf[MAX_LSPS_ALIGN16 - s->lsps], 0,
  1818. sizeof(*s->synth_filter_out_buf) * s->lsps);
  1819. memset(s->dcf_mem, 0,
  1820. sizeof(*s->dcf_mem) * 2);
  1821. memset(s->zero_exc_pf, 0,
  1822. sizeof(*s->zero_exc_pf) * s->history_nsamples);
  1823. memset(s->denoise_filter_cache, 0, sizeof(s->denoise_filter_cache));
  1824. }
  1825. }
  1826. AVCodec ff_wmavoice_decoder = {
  1827. "wmavoice",
  1828. AVMEDIA_TYPE_AUDIO,
  1829. CODEC_ID_WMAVOICE,
  1830. sizeof(WMAVoiceContext),
  1831. wmavoice_decode_init,
  1832. NULL,
  1833. wmavoice_decode_end,
  1834. wmavoice_decode_packet,
  1835. CODEC_CAP_SUBFRAMES,
  1836. .flush = wmavoice_flush,
  1837. .long_name = NULL_IF_CONFIG_SMALL("Windows Media Audio Voice"),
  1838. };