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.

2004 lines
79KB

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