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.

1264 lines
46KB

  1. /*
  2. * AMR wideband decoder
  3. * Copyright (c) 2010 Marcelo Galvao Povoa
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; 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. * AMR wideband decoder
  24. */
  25. #include "libavutil/channel_layout.h"
  26. #include "libavutil/common.h"
  27. #include "libavutil/lfg.h"
  28. #include "avcodec.h"
  29. #include "dsputil.h"
  30. #include "lsp.h"
  31. #include "celp_filters.h"
  32. #include "acelp_filters.h"
  33. #include "acelp_vectors.h"
  34. #include "acelp_pitch_delay.h"
  35. #include "internal.h"
  36. #define AMR_USE_16BIT_TABLES
  37. #include "amr.h"
  38. #include "amrwbdata.h"
  39. typedef struct {
  40. AVFrame avframe; ///< AVFrame for decoded samples
  41. AMRWBFrame frame; ///< AMRWB parameters decoded from bitstream
  42. enum Mode fr_cur_mode; ///< mode index of current frame
  43. uint8_t fr_quality; ///< frame quality index (FQI)
  44. float isf_cur[LP_ORDER]; ///< working ISF vector from current frame
  45. float isf_q_past[LP_ORDER]; ///< quantized ISF vector of the previous frame
  46. float isf_past_final[LP_ORDER]; ///< final processed ISF vector of the previous frame
  47. double isp[4][LP_ORDER]; ///< ISP vectors from current frame
  48. double isp_sub4_past[LP_ORDER]; ///< ISP vector for the 4th subframe of the previous frame
  49. float lp_coef[4][LP_ORDER]; ///< Linear Prediction Coefficients from ISP vector
  50. uint8_t base_pitch_lag; ///< integer part of pitch lag for the next relative subframe
  51. uint8_t pitch_lag_int; ///< integer part of pitch lag of the previous subframe
  52. float excitation_buf[AMRWB_P_DELAY_MAX + LP_ORDER + 2 + AMRWB_SFR_SIZE]; ///< current excitation and all necessary excitation history
  53. float *excitation; ///< points to current excitation in excitation_buf[]
  54. float pitch_vector[AMRWB_SFR_SIZE]; ///< adaptive codebook (pitch) vector for current subframe
  55. float fixed_vector[AMRWB_SFR_SIZE]; ///< algebraic codebook (fixed) vector for current subframe
  56. float prediction_error[4]; ///< quantified prediction errors {20log10(^gamma_gc)} for previous four subframes
  57. float pitch_gain[6]; ///< quantified pitch gains for the current and previous five subframes
  58. float fixed_gain[2]; ///< quantified fixed gains for the current and previous subframes
  59. float tilt_coef; ///< {beta_1} related to the voicing of the previous subframe
  60. float prev_sparse_fixed_gain; ///< previous fixed gain; used by anti-sparseness to determine "onset"
  61. uint8_t prev_ir_filter_nr; ///< previous impulse response filter "impNr": 0 - strong, 1 - medium, 2 - none
  62. float prev_tr_gain; ///< previous initial gain used by noise enhancer for threshold
  63. float samples_az[LP_ORDER + AMRWB_SFR_SIZE]; ///< low-band samples and memory from synthesis at 12.8kHz
  64. float samples_up[UPS_MEM_SIZE + AMRWB_SFR_SIZE]; ///< low-band samples and memory processed for upsampling
  65. float samples_hb[LP_ORDER_16k + AMRWB_SFR_SIZE_16k]; ///< high-band samples and memory from synthesis at 16kHz
  66. float hpf_31_mem[2], hpf_400_mem[2]; ///< previous values in the high pass filters
  67. float demph_mem[1]; ///< previous value in the de-emphasis filter
  68. float bpf_6_7_mem[HB_FIR_SIZE]; ///< previous values in the high-band band pass filter
  69. float lpf_7_mem[HB_FIR_SIZE]; ///< previous values in the high-band low pass filter
  70. AVLFG prng; ///< random number generator for white noise excitation
  71. uint8_t first_frame; ///< flag active during decoding of the first frame
  72. } AMRWBContext;
  73. static av_cold int amrwb_decode_init(AVCodecContext *avctx)
  74. {
  75. AMRWBContext *ctx = avctx->priv_data;
  76. int i;
  77. if (avctx->channels > 1) {
  78. av_log_missing_feature(avctx, "multi-channel AMR", 0);
  79. return AVERROR_PATCHWELCOME;
  80. }
  81. avctx->channels = 1;
  82. avctx->channel_layout = AV_CH_LAYOUT_MONO;
  83. avctx->sample_rate = 16000;
  84. avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
  85. av_lfg_init(&ctx->prng, 1);
  86. ctx->excitation = &ctx->excitation_buf[AMRWB_P_DELAY_MAX + LP_ORDER + 1];
  87. ctx->first_frame = 1;
  88. for (i = 0; i < LP_ORDER; i++)
  89. ctx->isf_past_final[i] = isf_init[i] * (1.0f / (1 << 15));
  90. for (i = 0; i < 4; i++)
  91. ctx->prediction_error[i] = MIN_ENERGY;
  92. avcodec_get_frame_defaults(&ctx->avframe);
  93. avctx->coded_frame = &ctx->avframe;
  94. return 0;
  95. }
  96. /**
  97. * Decode the frame header in the "MIME/storage" format. This format
  98. * is simpler and does not carry the auxiliary frame information.
  99. *
  100. * @param[in] ctx The Context
  101. * @param[in] buf Pointer to the input buffer
  102. *
  103. * @return The decoded header length in bytes
  104. */
  105. static int decode_mime_header(AMRWBContext *ctx, const uint8_t *buf)
  106. {
  107. /* Decode frame header (1st octet) */
  108. ctx->fr_cur_mode = buf[0] >> 3 & 0x0F;
  109. ctx->fr_quality = (buf[0] & 0x4) == 0x4;
  110. return 1;
  111. }
  112. /**
  113. * Decode quantized ISF vectors using 36-bit indexes (6K60 mode only).
  114. *
  115. * @param[in] ind Array of 5 indexes
  116. * @param[out] isf_q Buffer for isf_q[LP_ORDER]
  117. *
  118. */
  119. static void decode_isf_indices_36b(uint16_t *ind, float *isf_q)
  120. {
  121. int i;
  122. for (i = 0; i < 9; i++)
  123. isf_q[i] = dico1_isf[ind[0]][i] * (1.0f / (1 << 15));
  124. for (i = 0; i < 7; i++)
  125. isf_q[i + 9] = dico2_isf[ind[1]][i] * (1.0f / (1 << 15));
  126. for (i = 0; i < 5; i++)
  127. isf_q[i] += dico21_isf_36b[ind[2]][i] * (1.0f / (1 << 15));
  128. for (i = 0; i < 4; i++)
  129. isf_q[i + 5] += dico22_isf_36b[ind[3]][i] * (1.0f / (1 << 15));
  130. for (i = 0; i < 7; i++)
  131. isf_q[i + 9] += dico23_isf_36b[ind[4]][i] * (1.0f / (1 << 15));
  132. }
  133. /**
  134. * Decode quantized ISF vectors using 46-bit indexes (except 6K60 mode).
  135. *
  136. * @param[in] ind Array of 7 indexes
  137. * @param[out] isf_q Buffer for isf_q[LP_ORDER]
  138. *
  139. */
  140. static void decode_isf_indices_46b(uint16_t *ind, float *isf_q)
  141. {
  142. int i;
  143. for (i = 0; i < 9; i++)
  144. isf_q[i] = dico1_isf[ind[0]][i] * (1.0f / (1 << 15));
  145. for (i = 0; i < 7; i++)
  146. isf_q[i + 9] = dico2_isf[ind[1]][i] * (1.0f / (1 << 15));
  147. for (i = 0; i < 3; i++)
  148. isf_q[i] += dico21_isf[ind[2]][i] * (1.0f / (1 << 15));
  149. for (i = 0; i < 3; i++)
  150. isf_q[i + 3] += dico22_isf[ind[3]][i] * (1.0f / (1 << 15));
  151. for (i = 0; i < 3; i++)
  152. isf_q[i + 6] += dico23_isf[ind[4]][i] * (1.0f / (1 << 15));
  153. for (i = 0; i < 3; i++)
  154. isf_q[i + 9] += dico24_isf[ind[5]][i] * (1.0f / (1 << 15));
  155. for (i = 0; i < 4; i++)
  156. isf_q[i + 12] += dico25_isf[ind[6]][i] * (1.0f / (1 << 15));
  157. }
  158. /**
  159. * Apply mean and past ISF values using the prediction factor.
  160. * Updates past ISF vector.
  161. *
  162. * @param[in,out] isf_q Current quantized ISF
  163. * @param[in,out] isf_past Past quantized ISF
  164. *
  165. */
  166. static void isf_add_mean_and_past(float *isf_q, float *isf_past)
  167. {
  168. int i;
  169. float tmp;
  170. for (i = 0; i < LP_ORDER; i++) {
  171. tmp = isf_q[i];
  172. isf_q[i] += isf_mean[i] * (1.0f / (1 << 15));
  173. isf_q[i] += PRED_FACTOR * isf_past[i];
  174. isf_past[i] = tmp;
  175. }
  176. }
  177. /**
  178. * Interpolate the fourth ISP vector from current and past frames
  179. * to obtain an ISP vector for each subframe.
  180. *
  181. * @param[in,out] isp_q ISPs for each subframe
  182. * @param[in] isp4_past Past ISP for subframe 4
  183. */
  184. static void interpolate_isp(double isp_q[4][LP_ORDER], const double *isp4_past)
  185. {
  186. int i, k;
  187. for (k = 0; k < 3; k++) {
  188. float c = isfp_inter[k];
  189. for (i = 0; i < LP_ORDER; i++)
  190. isp_q[k][i] = (1.0 - c) * isp4_past[i] + c * isp_q[3][i];
  191. }
  192. }
  193. /**
  194. * Decode an adaptive codebook index into pitch lag (except 6k60, 8k85 modes).
  195. * Calculate integer lag and fractional lag always using 1/4 resolution.
  196. * In 1st and 3rd subframes the index is relative to last subframe integer lag.
  197. *
  198. * @param[out] lag_int Decoded integer pitch lag
  199. * @param[out] lag_frac Decoded fractional pitch lag
  200. * @param[in] pitch_index Adaptive codebook pitch index
  201. * @param[in,out] base_lag_int Base integer lag used in relative subframes
  202. * @param[in] subframe Current subframe index (0 to 3)
  203. */
  204. static void decode_pitch_lag_high(int *lag_int, int *lag_frac, int pitch_index,
  205. uint8_t *base_lag_int, int subframe)
  206. {
  207. if (subframe == 0 || subframe == 2) {
  208. if (pitch_index < 376) {
  209. *lag_int = (pitch_index + 137) >> 2;
  210. *lag_frac = pitch_index - (*lag_int << 2) + 136;
  211. } else if (pitch_index < 440) {
  212. *lag_int = (pitch_index + 257 - 376) >> 1;
  213. *lag_frac = (pitch_index - (*lag_int << 1) + 256 - 376) << 1;
  214. /* the actual resolution is 1/2 but expressed as 1/4 */
  215. } else {
  216. *lag_int = pitch_index - 280;
  217. *lag_frac = 0;
  218. }
  219. /* minimum lag for next subframe */
  220. *base_lag_int = av_clip(*lag_int - 8 - (*lag_frac < 0),
  221. AMRWB_P_DELAY_MIN, AMRWB_P_DELAY_MAX - 15);
  222. // XXX: the spec states clearly that *base_lag_int should be
  223. // the nearest integer to *lag_int (minus 8), but the ref code
  224. // actually always uses its floor, I'm following the latter
  225. } else {
  226. *lag_int = (pitch_index + 1) >> 2;
  227. *lag_frac = pitch_index - (*lag_int << 2);
  228. *lag_int += *base_lag_int;
  229. }
  230. }
  231. /**
  232. * Decode an adaptive codebook index into pitch lag for 8k85 and 6k60 modes.
  233. * The description is analogous to decode_pitch_lag_high, but in 6k60 the
  234. * relative index is used for all subframes except the first.
  235. */
  236. static void decode_pitch_lag_low(int *lag_int, int *lag_frac, int pitch_index,
  237. uint8_t *base_lag_int, int subframe, enum Mode mode)
  238. {
  239. if (subframe == 0 || (subframe == 2 && mode != MODE_6k60)) {
  240. if (pitch_index < 116) {
  241. *lag_int = (pitch_index + 69) >> 1;
  242. *lag_frac = (pitch_index - (*lag_int << 1) + 68) << 1;
  243. } else {
  244. *lag_int = pitch_index - 24;
  245. *lag_frac = 0;
  246. }
  247. // XXX: same problem as before
  248. *base_lag_int = av_clip(*lag_int - 8 - (*lag_frac < 0),
  249. AMRWB_P_DELAY_MIN, AMRWB_P_DELAY_MAX - 15);
  250. } else {
  251. *lag_int = (pitch_index + 1) >> 1;
  252. *lag_frac = (pitch_index - (*lag_int << 1)) << 1;
  253. *lag_int += *base_lag_int;
  254. }
  255. }
  256. /**
  257. * Find the pitch vector by interpolating the past excitation at the
  258. * pitch delay, which is obtained in this function.
  259. *
  260. * @param[in,out] ctx The context
  261. * @param[in] amr_subframe Current subframe data
  262. * @param[in] subframe Current subframe index (0 to 3)
  263. */
  264. static void decode_pitch_vector(AMRWBContext *ctx,
  265. const AMRWBSubFrame *amr_subframe,
  266. const int subframe)
  267. {
  268. int pitch_lag_int, pitch_lag_frac;
  269. int i;
  270. float *exc = ctx->excitation;
  271. enum Mode mode = ctx->fr_cur_mode;
  272. if (mode <= MODE_8k85) {
  273. decode_pitch_lag_low(&pitch_lag_int, &pitch_lag_frac, amr_subframe->adap,
  274. &ctx->base_pitch_lag, subframe, mode);
  275. } else
  276. decode_pitch_lag_high(&pitch_lag_int, &pitch_lag_frac, amr_subframe->adap,
  277. &ctx->base_pitch_lag, subframe);
  278. ctx->pitch_lag_int = pitch_lag_int;
  279. pitch_lag_int += pitch_lag_frac > 0;
  280. /* Calculate the pitch vector by interpolating the past excitation at the
  281. pitch lag using a hamming windowed sinc function */
  282. ff_acelp_interpolatef(exc, exc + 1 - pitch_lag_int,
  283. ac_inter, 4,
  284. pitch_lag_frac + (pitch_lag_frac > 0 ? 0 : 4),
  285. LP_ORDER, AMRWB_SFR_SIZE + 1);
  286. /* Check which pitch signal path should be used
  287. * 6k60 and 8k85 modes have the ltp flag set to 0 */
  288. if (amr_subframe->ltp) {
  289. memcpy(ctx->pitch_vector, exc, AMRWB_SFR_SIZE * sizeof(float));
  290. } else {
  291. for (i = 0; i < AMRWB_SFR_SIZE; i++)
  292. ctx->pitch_vector[i] = 0.18 * exc[i - 1] + 0.64 * exc[i] +
  293. 0.18 * exc[i + 1];
  294. memcpy(exc, ctx->pitch_vector, AMRWB_SFR_SIZE * sizeof(float));
  295. }
  296. }
  297. /** Get x bits in the index interval [lsb,lsb+len-1] inclusive */
  298. #define BIT_STR(x,lsb,len) (((x) >> (lsb)) & ((1 << (len)) - 1))
  299. /** Get the bit at specified position */
  300. #define BIT_POS(x, p) (((x) >> (p)) & 1)
  301. /**
  302. * The next six functions decode_[i]p_track decode exactly i pulses
  303. * positions and amplitudes (-1 or 1) in a subframe track using
  304. * an encoded pulse indexing (TS 26.190 section 5.8.2).
  305. *
  306. * The results are given in out[], in which a negative number means
  307. * amplitude -1 and vice versa (i.e., ampl(x) = x / abs(x) ).
  308. *
  309. * @param[out] out Output buffer (writes i elements)
  310. * @param[in] code Pulse index (no. of bits varies, see below)
  311. * @param[in] m (log2) Number of potential positions
  312. * @param[in] off Offset for decoded positions
  313. */
  314. static inline void decode_1p_track(int *out, int code, int m, int off)
  315. {
  316. int pos = BIT_STR(code, 0, m) + off; ///code: m+1 bits
  317. out[0] = BIT_POS(code, m) ? -pos : pos;
  318. }
  319. static inline void decode_2p_track(int *out, int code, int m, int off) ///code: 2m+1 bits
  320. {
  321. int pos0 = BIT_STR(code, m, m) + off;
  322. int pos1 = BIT_STR(code, 0, m) + off;
  323. out[0] = BIT_POS(code, 2*m) ? -pos0 : pos0;
  324. out[1] = BIT_POS(code, 2*m) ? -pos1 : pos1;
  325. out[1] = pos0 > pos1 ? -out[1] : out[1];
  326. }
  327. static void decode_3p_track(int *out, int code, int m, int off) ///code: 3m+1 bits
  328. {
  329. int half_2p = BIT_POS(code, 2*m - 1) << (m - 1);
  330. decode_2p_track(out, BIT_STR(code, 0, 2*m - 1),
  331. m - 1, off + half_2p);
  332. decode_1p_track(out + 2, BIT_STR(code, 2*m, m + 1), m, off);
  333. }
  334. static void decode_4p_track(int *out, int code, int m, int off) ///code: 4m bits
  335. {
  336. int half_4p, subhalf_2p;
  337. int b_offset = 1 << (m - 1);
  338. switch (BIT_STR(code, 4*m - 2, 2)) { /* case ID (2 bits) */
  339. case 0: /* 0 pulses in A, 4 pulses in B or vice versa */
  340. half_4p = BIT_POS(code, 4*m - 3) << (m - 1); // which has 4 pulses
  341. subhalf_2p = BIT_POS(code, 2*m - 3) << (m - 2);
  342. decode_2p_track(out, BIT_STR(code, 0, 2*m - 3),
  343. m - 2, off + half_4p + subhalf_2p);
  344. decode_2p_track(out + 2, BIT_STR(code, 2*m - 2, 2*m - 1),
  345. m - 1, off + half_4p);
  346. break;
  347. case 1: /* 1 pulse in A, 3 pulses in B */
  348. decode_1p_track(out, BIT_STR(code, 3*m - 2, m),
  349. m - 1, off);
  350. decode_3p_track(out + 1, BIT_STR(code, 0, 3*m - 2),
  351. m - 1, off + b_offset);
  352. break;
  353. case 2: /* 2 pulses in each half */
  354. decode_2p_track(out, BIT_STR(code, 2*m - 1, 2*m - 1),
  355. m - 1, off);
  356. decode_2p_track(out + 2, BIT_STR(code, 0, 2*m - 1),
  357. m - 1, off + b_offset);
  358. break;
  359. case 3: /* 3 pulses in A, 1 pulse in B */
  360. decode_3p_track(out, BIT_STR(code, m, 3*m - 2),
  361. m - 1, off);
  362. decode_1p_track(out + 3, BIT_STR(code, 0, m),
  363. m - 1, off + b_offset);
  364. break;
  365. }
  366. }
  367. static void decode_5p_track(int *out, int code, int m, int off) ///code: 5m bits
  368. {
  369. int half_3p = BIT_POS(code, 5*m - 1) << (m - 1);
  370. decode_3p_track(out, BIT_STR(code, 2*m + 1, 3*m - 2),
  371. m - 1, off + half_3p);
  372. decode_2p_track(out + 3, BIT_STR(code, 0, 2*m + 1), m, off);
  373. }
  374. static void decode_6p_track(int *out, int code, int m, int off) ///code: 6m-2 bits
  375. {
  376. int b_offset = 1 << (m - 1);
  377. /* which half has more pulses in cases 0 to 2 */
  378. int half_more = BIT_POS(code, 6*m - 5) << (m - 1);
  379. int half_other = b_offset - half_more;
  380. switch (BIT_STR(code, 6*m - 4, 2)) { /* case ID (2 bits) */
  381. case 0: /* 0 pulses in A, 6 pulses in B or vice versa */
  382. decode_1p_track(out, BIT_STR(code, 0, m),
  383. m - 1, off + half_more);
  384. decode_5p_track(out + 1, BIT_STR(code, m, 5*m - 5),
  385. m - 1, off + half_more);
  386. break;
  387. case 1: /* 1 pulse in A, 5 pulses in B or vice versa */
  388. decode_1p_track(out, BIT_STR(code, 0, m),
  389. m - 1, off + half_other);
  390. decode_5p_track(out + 1, BIT_STR(code, m, 5*m - 5),
  391. m - 1, off + half_more);
  392. break;
  393. case 2: /* 2 pulses in A, 4 pulses in B or vice versa */
  394. decode_2p_track(out, BIT_STR(code, 0, 2*m - 1),
  395. m - 1, off + half_other);
  396. decode_4p_track(out + 2, BIT_STR(code, 2*m - 1, 4*m - 4),
  397. m - 1, off + half_more);
  398. break;
  399. case 3: /* 3 pulses in A, 3 pulses in B */
  400. decode_3p_track(out, BIT_STR(code, 3*m - 2, 3*m - 2),
  401. m - 1, off);
  402. decode_3p_track(out + 3, BIT_STR(code, 0, 3*m - 2),
  403. m - 1, off + b_offset);
  404. break;
  405. }
  406. }
  407. /**
  408. * Decode the algebraic codebook index to pulse positions and signs,
  409. * then construct the algebraic codebook vector.
  410. *
  411. * @param[out] fixed_vector Buffer for the fixed codebook excitation
  412. * @param[in] pulse_hi MSBs part of the pulse index array (higher modes only)
  413. * @param[in] pulse_lo LSBs part of the pulse index array
  414. * @param[in] mode Mode of the current frame
  415. */
  416. static void decode_fixed_vector(float *fixed_vector, const uint16_t *pulse_hi,
  417. const uint16_t *pulse_lo, const enum Mode mode)
  418. {
  419. /* sig_pos stores for each track the decoded pulse position indexes
  420. * (1-based) multiplied by its corresponding amplitude (+1 or -1) */
  421. int sig_pos[4][6];
  422. int spacing = (mode == MODE_6k60) ? 2 : 4;
  423. int i, j;
  424. switch (mode) {
  425. case MODE_6k60:
  426. for (i = 0; i < 2; i++)
  427. decode_1p_track(sig_pos[i], pulse_lo[i], 5, 1);
  428. break;
  429. case MODE_8k85:
  430. for (i = 0; i < 4; i++)
  431. decode_1p_track(sig_pos[i], pulse_lo[i], 4, 1);
  432. break;
  433. case MODE_12k65:
  434. for (i = 0; i < 4; i++)
  435. decode_2p_track(sig_pos[i], pulse_lo[i], 4, 1);
  436. break;
  437. case MODE_14k25:
  438. for (i = 0; i < 2; i++)
  439. decode_3p_track(sig_pos[i], pulse_lo[i], 4, 1);
  440. for (i = 2; i < 4; i++)
  441. decode_2p_track(sig_pos[i], pulse_lo[i], 4, 1);
  442. break;
  443. case MODE_15k85:
  444. for (i = 0; i < 4; i++)
  445. decode_3p_track(sig_pos[i], pulse_lo[i], 4, 1);
  446. break;
  447. case MODE_18k25:
  448. for (i = 0; i < 4; i++)
  449. decode_4p_track(sig_pos[i], (int) pulse_lo[i] +
  450. ((int) pulse_hi[i] << 14), 4, 1);
  451. break;
  452. case MODE_19k85:
  453. for (i = 0; i < 2; i++)
  454. decode_5p_track(sig_pos[i], (int) pulse_lo[i] +
  455. ((int) pulse_hi[i] << 10), 4, 1);
  456. for (i = 2; i < 4; i++)
  457. decode_4p_track(sig_pos[i], (int) pulse_lo[i] +
  458. ((int) pulse_hi[i] << 14), 4, 1);
  459. break;
  460. case MODE_23k05:
  461. case MODE_23k85:
  462. for (i = 0; i < 4; i++)
  463. decode_6p_track(sig_pos[i], (int) pulse_lo[i] +
  464. ((int) pulse_hi[i] << 11), 4, 1);
  465. break;
  466. }
  467. memset(fixed_vector, 0, sizeof(float) * AMRWB_SFR_SIZE);
  468. for (i = 0; i < 4; i++)
  469. for (j = 0; j < pulses_nb_per_mode_tr[mode][i]; j++) {
  470. int pos = (FFABS(sig_pos[i][j]) - 1) * spacing + i;
  471. fixed_vector[pos] += sig_pos[i][j] < 0 ? -1.0 : 1.0;
  472. }
  473. }
  474. /**
  475. * Decode pitch gain and fixed gain correction factor.
  476. *
  477. * @param[in] vq_gain Vector-quantized index for gains
  478. * @param[in] mode Mode of the current frame
  479. * @param[out] fixed_gain_factor Decoded fixed gain correction factor
  480. * @param[out] pitch_gain Decoded pitch gain
  481. */
  482. static void decode_gains(const uint8_t vq_gain, const enum Mode mode,
  483. float *fixed_gain_factor, float *pitch_gain)
  484. {
  485. const int16_t *gains = (mode <= MODE_8k85 ? qua_gain_6b[vq_gain] :
  486. qua_gain_7b[vq_gain]);
  487. *pitch_gain = gains[0] * (1.0f / (1 << 14));
  488. *fixed_gain_factor = gains[1] * (1.0f / (1 << 11));
  489. }
  490. /**
  491. * Apply pitch sharpening filters to the fixed codebook vector.
  492. *
  493. * @param[in] ctx The context
  494. * @param[in,out] fixed_vector Fixed codebook excitation
  495. */
  496. // XXX: Spec states this procedure should be applied when the pitch
  497. // lag is less than 64, but this checking seems absent in reference and AMR-NB
  498. static void pitch_sharpening(AMRWBContext *ctx, float *fixed_vector)
  499. {
  500. int i;
  501. /* Tilt part */
  502. for (i = AMRWB_SFR_SIZE - 1; i != 0; i--)
  503. fixed_vector[i] -= fixed_vector[i - 1] * ctx->tilt_coef;
  504. /* Periodicity enhancement part */
  505. for (i = ctx->pitch_lag_int; i < AMRWB_SFR_SIZE; i++)
  506. fixed_vector[i] += fixed_vector[i - ctx->pitch_lag_int] * 0.85;
  507. }
  508. /**
  509. * Calculate the voicing factor (-1.0 = unvoiced to 1.0 = voiced).
  510. *
  511. * @param[in] p_vector, f_vector Pitch and fixed excitation vectors
  512. * @param[in] p_gain, f_gain Pitch and fixed gains
  513. */
  514. // XXX: There is something wrong with the precision here! The magnitudes
  515. // of the energies are not correct. Please check the reference code carefully
  516. static float voice_factor(float *p_vector, float p_gain,
  517. float *f_vector, float f_gain)
  518. {
  519. double p_ener = (double) ff_scalarproduct_float_c(p_vector, p_vector,
  520. AMRWB_SFR_SIZE) *
  521. p_gain * p_gain;
  522. double f_ener = (double) ff_scalarproduct_float_c(f_vector, f_vector,
  523. AMRWB_SFR_SIZE) *
  524. f_gain * f_gain;
  525. return (p_ener - f_ener) / (p_ener + f_ener);
  526. }
  527. /**
  528. * Reduce fixed vector sparseness by smoothing with one of three IR filters,
  529. * also known as "adaptive phase dispersion".
  530. *
  531. * @param[in] ctx The context
  532. * @param[in,out] fixed_vector Unfiltered fixed vector
  533. * @param[out] buf Space for modified vector if necessary
  534. *
  535. * @return The potentially overwritten filtered fixed vector address
  536. */
  537. static float *anti_sparseness(AMRWBContext *ctx,
  538. float *fixed_vector, float *buf)
  539. {
  540. int ir_filter_nr;
  541. if (ctx->fr_cur_mode > MODE_8k85) // no filtering in higher modes
  542. return fixed_vector;
  543. if (ctx->pitch_gain[0] < 0.6) {
  544. ir_filter_nr = 0; // strong filtering
  545. } else if (ctx->pitch_gain[0] < 0.9) {
  546. ir_filter_nr = 1; // medium filtering
  547. } else
  548. ir_filter_nr = 2; // no filtering
  549. /* detect 'onset' */
  550. if (ctx->fixed_gain[0] > 3.0 * ctx->fixed_gain[1]) {
  551. if (ir_filter_nr < 2)
  552. ir_filter_nr++;
  553. } else {
  554. int i, count = 0;
  555. for (i = 0; i < 6; i++)
  556. if (ctx->pitch_gain[i] < 0.6)
  557. count++;
  558. if (count > 2)
  559. ir_filter_nr = 0;
  560. if (ir_filter_nr > ctx->prev_ir_filter_nr + 1)
  561. ir_filter_nr--;
  562. }
  563. /* update ir filter strength history */
  564. ctx->prev_ir_filter_nr = ir_filter_nr;
  565. ir_filter_nr += (ctx->fr_cur_mode == MODE_8k85);
  566. if (ir_filter_nr < 2) {
  567. int i;
  568. const float *coef = ir_filters_lookup[ir_filter_nr];
  569. /* Circular convolution code in the reference
  570. * decoder was modified to avoid using one
  571. * extra array. The filtered vector is given by:
  572. *
  573. * c2(n) = sum(i,0,len-1){ c(i) * coef( (n - i + len) % len ) }
  574. */
  575. memset(buf, 0, sizeof(float) * AMRWB_SFR_SIZE);
  576. for (i = 0; i < AMRWB_SFR_SIZE; i++)
  577. if (fixed_vector[i])
  578. ff_celp_circ_addf(buf, buf, coef, i, fixed_vector[i],
  579. AMRWB_SFR_SIZE);
  580. fixed_vector = buf;
  581. }
  582. return fixed_vector;
  583. }
  584. /**
  585. * Calculate a stability factor {teta} based on distance between
  586. * current and past isf. A value of 1 shows maximum signal stability.
  587. */
  588. static float stability_factor(const float *isf, const float *isf_past)
  589. {
  590. int i;
  591. float acc = 0.0;
  592. for (i = 0; i < LP_ORDER - 1; i++)
  593. acc += (isf[i] - isf_past[i]) * (isf[i] - isf_past[i]);
  594. // XXX: This part is not so clear from the reference code
  595. // the result is more accurate changing the "/ 256" to "* 512"
  596. return FFMAX(0.0, 1.25 - acc * 0.8 * 512);
  597. }
  598. /**
  599. * Apply a non-linear fixed gain smoothing in order to reduce
  600. * fluctuation in the energy of excitation.
  601. *
  602. * @param[in] fixed_gain Unsmoothed fixed gain
  603. * @param[in,out] prev_tr_gain Previous threshold gain (updated)
  604. * @param[in] voice_fac Frame voicing factor
  605. * @param[in] stab_fac Frame stability factor
  606. *
  607. * @return The smoothed gain
  608. */
  609. static float noise_enhancer(float fixed_gain, float *prev_tr_gain,
  610. float voice_fac, float stab_fac)
  611. {
  612. float sm_fac = 0.5 * (1 - voice_fac) * stab_fac;
  613. float g0;
  614. // XXX: the following fixed-point constants used to in(de)crement
  615. // gain by 1.5dB were taken from the reference code, maybe it could
  616. // be simpler
  617. if (fixed_gain < *prev_tr_gain) {
  618. g0 = FFMIN(*prev_tr_gain, fixed_gain + fixed_gain *
  619. (6226 * (1.0f / (1 << 15)))); // +1.5 dB
  620. } else
  621. g0 = FFMAX(*prev_tr_gain, fixed_gain *
  622. (27536 * (1.0f / (1 << 15)))); // -1.5 dB
  623. *prev_tr_gain = g0; // update next frame threshold
  624. return sm_fac * g0 + (1 - sm_fac) * fixed_gain;
  625. }
  626. /**
  627. * Filter the fixed_vector to emphasize the higher frequencies.
  628. *
  629. * @param[in,out] fixed_vector Fixed codebook vector
  630. * @param[in] voice_fac Frame voicing factor
  631. */
  632. static void pitch_enhancer(float *fixed_vector, float voice_fac)
  633. {
  634. int i;
  635. float cpe = 0.125 * (1 + voice_fac);
  636. float last = fixed_vector[0]; // holds c(i - 1)
  637. fixed_vector[0] -= cpe * fixed_vector[1];
  638. for (i = 1; i < AMRWB_SFR_SIZE - 1; i++) {
  639. float cur = fixed_vector[i];
  640. fixed_vector[i] -= cpe * (last + fixed_vector[i + 1]);
  641. last = cur;
  642. }
  643. fixed_vector[AMRWB_SFR_SIZE - 1] -= cpe * last;
  644. }
  645. /**
  646. * Conduct 16th order linear predictive coding synthesis from excitation.
  647. *
  648. * @param[in] ctx Pointer to the AMRWBContext
  649. * @param[in] lpc Pointer to the LPC coefficients
  650. * @param[out] excitation Buffer for synthesis final excitation
  651. * @param[in] fixed_gain Fixed codebook gain for synthesis
  652. * @param[in] fixed_vector Algebraic codebook vector
  653. * @param[in,out] samples Pointer to the output samples and memory
  654. */
  655. static void synthesis(AMRWBContext *ctx, float *lpc, float *excitation,
  656. float fixed_gain, const float *fixed_vector,
  657. float *samples)
  658. {
  659. ff_weighted_vector_sumf(excitation, ctx->pitch_vector, fixed_vector,
  660. ctx->pitch_gain[0], fixed_gain, AMRWB_SFR_SIZE);
  661. /* emphasize pitch vector contribution in low bitrate modes */
  662. if (ctx->pitch_gain[0] > 0.5 && ctx->fr_cur_mode <= MODE_8k85) {
  663. int i;
  664. float energy = ff_scalarproduct_float_c(excitation, excitation,
  665. AMRWB_SFR_SIZE);
  666. // XXX: Weird part in both ref code and spec. A unknown parameter
  667. // {beta} seems to be identical to the current pitch gain
  668. float pitch_factor = 0.25 * ctx->pitch_gain[0] * ctx->pitch_gain[0];
  669. for (i = 0; i < AMRWB_SFR_SIZE; i++)
  670. excitation[i] += pitch_factor * ctx->pitch_vector[i];
  671. ff_scale_vector_to_given_sum_of_squares(excitation, excitation,
  672. energy, AMRWB_SFR_SIZE);
  673. }
  674. ff_celp_lp_synthesis_filterf(samples, lpc, excitation,
  675. AMRWB_SFR_SIZE, LP_ORDER);
  676. }
  677. /**
  678. * Apply to synthesis a de-emphasis filter of the form:
  679. * H(z) = 1 / (1 - m * z^-1)
  680. *
  681. * @param[out] out Output buffer
  682. * @param[in] in Input samples array with in[-1]
  683. * @param[in] m Filter coefficient
  684. * @param[in,out] mem State from last filtering
  685. */
  686. static void de_emphasis(float *out, float *in, float m, float mem[1])
  687. {
  688. int i;
  689. out[0] = in[0] + m * mem[0];
  690. for (i = 1; i < AMRWB_SFR_SIZE; i++)
  691. out[i] = in[i] + out[i - 1] * m;
  692. mem[0] = out[AMRWB_SFR_SIZE - 1];
  693. }
  694. /**
  695. * Upsample a signal by 5/4 ratio (from 12.8kHz to 16kHz) using
  696. * a FIR interpolation filter. Uses past data from before *in address.
  697. *
  698. * @param[out] out Buffer for interpolated signal
  699. * @param[in] in Current signal data (length 0.8*o_size)
  700. * @param[in] o_size Output signal length
  701. */
  702. static void upsample_5_4(float *out, const float *in, int o_size)
  703. {
  704. const float *in0 = in - UPS_FIR_SIZE + 1;
  705. int i, j, k;
  706. int int_part = 0, frac_part;
  707. i = 0;
  708. for (j = 0; j < o_size / 5; j++) {
  709. out[i] = in[int_part];
  710. frac_part = 4;
  711. i++;
  712. for (k = 1; k < 5; k++) {
  713. out[i] = ff_scalarproduct_float_c(in0 + int_part,
  714. upsample_fir[4 - frac_part],
  715. UPS_MEM_SIZE);
  716. int_part++;
  717. frac_part--;
  718. i++;
  719. }
  720. }
  721. }
  722. /**
  723. * Calculate the high-band gain based on encoded index (23k85 mode) or
  724. * on the low-band speech signal and the Voice Activity Detection flag.
  725. *
  726. * @param[in] ctx The context
  727. * @param[in] synth LB speech synthesis at 12.8k
  728. * @param[in] hb_idx Gain index for mode 23k85 only
  729. * @param[in] vad VAD flag for the frame
  730. */
  731. static float find_hb_gain(AMRWBContext *ctx, const float *synth,
  732. uint16_t hb_idx, uint8_t vad)
  733. {
  734. int wsp = (vad > 0);
  735. float tilt;
  736. if (ctx->fr_cur_mode == MODE_23k85)
  737. return qua_hb_gain[hb_idx] * (1.0f / (1 << 14));
  738. tilt = ff_scalarproduct_float_c(synth, synth + 1, AMRWB_SFR_SIZE - 1) /
  739. ff_scalarproduct_float_c(synth, synth, AMRWB_SFR_SIZE);
  740. /* return gain bounded by [0.1, 1.0] */
  741. return av_clipf((1.0 - FFMAX(0.0, tilt)) * (1.25 - 0.25 * wsp), 0.1, 1.0);
  742. }
  743. /**
  744. * Generate the high-band excitation with the same energy from the lower
  745. * one and scaled by the given gain.
  746. *
  747. * @param[in] ctx The context
  748. * @param[out] hb_exc Buffer for the excitation
  749. * @param[in] synth_exc Low-band excitation used for synthesis
  750. * @param[in] hb_gain Wanted excitation gain
  751. */
  752. static void scaled_hb_excitation(AMRWBContext *ctx, float *hb_exc,
  753. const float *synth_exc, float hb_gain)
  754. {
  755. int i;
  756. float energy = ff_scalarproduct_float_c(synth_exc, synth_exc, AMRWB_SFR_SIZE);
  757. /* Generate a white-noise excitation */
  758. for (i = 0; i < AMRWB_SFR_SIZE_16k; i++)
  759. hb_exc[i] = 32768.0 - (uint16_t) av_lfg_get(&ctx->prng);
  760. ff_scale_vector_to_given_sum_of_squares(hb_exc, hb_exc,
  761. energy * hb_gain * hb_gain,
  762. AMRWB_SFR_SIZE_16k);
  763. }
  764. /**
  765. * Calculate the auto-correlation for the ISF difference vector.
  766. */
  767. static float auto_correlation(float *diff_isf, float mean, int lag)
  768. {
  769. int i;
  770. float sum = 0.0;
  771. for (i = 7; i < LP_ORDER - 2; i++) {
  772. float prod = (diff_isf[i] - mean) * (diff_isf[i - lag] - mean);
  773. sum += prod * prod;
  774. }
  775. return sum;
  776. }
  777. /**
  778. * Extrapolate a ISF vector to the 16kHz range (20th order LP)
  779. * used at mode 6k60 LP filter for the high frequency band.
  780. *
  781. * @param[out] isf Buffer for extrapolated isf; contains LP_ORDER
  782. * values on input
  783. */
  784. static void extrapolate_isf(float isf[LP_ORDER_16k])
  785. {
  786. float diff_isf[LP_ORDER - 2], diff_mean;
  787. float corr_lag[3];
  788. float est, scale;
  789. int i, j, i_max_corr;
  790. isf[LP_ORDER_16k - 1] = isf[LP_ORDER - 1];
  791. /* Calculate the difference vector */
  792. for (i = 0; i < LP_ORDER - 2; i++)
  793. diff_isf[i] = isf[i + 1] - isf[i];
  794. diff_mean = 0.0;
  795. for (i = 2; i < LP_ORDER - 2; i++)
  796. diff_mean += diff_isf[i] * (1.0f / (LP_ORDER - 4));
  797. /* Find which is the maximum autocorrelation */
  798. i_max_corr = 0;
  799. for (i = 0; i < 3; i++) {
  800. corr_lag[i] = auto_correlation(diff_isf, diff_mean, i + 2);
  801. if (corr_lag[i] > corr_lag[i_max_corr])
  802. i_max_corr = i;
  803. }
  804. i_max_corr++;
  805. for (i = LP_ORDER - 1; i < LP_ORDER_16k - 1; i++)
  806. isf[i] = isf[i - 1] + isf[i - 1 - i_max_corr]
  807. - isf[i - 2 - i_max_corr];
  808. /* Calculate an estimate for ISF(18) and scale ISF based on the error */
  809. est = 7965 + (isf[2] - isf[3] - isf[4]) / 6.0;
  810. scale = 0.5 * (FFMIN(est, 7600) - isf[LP_ORDER - 2]) /
  811. (isf[LP_ORDER_16k - 2] - isf[LP_ORDER - 2]);
  812. for (i = LP_ORDER - 1, j = 0; i < LP_ORDER_16k - 1; i++, j++)
  813. diff_isf[j] = scale * (isf[i] - isf[i - 1]);
  814. /* Stability insurance */
  815. for (i = 1; i < LP_ORDER_16k - LP_ORDER; i++)
  816. if (diff_isf[i] + diff_isf[i - 1] < 5.0) {
  817. if (diff_isf[i] > diff_isf[i - 1]) {
  818. diff_isf[i - 1] = 5.0 - diff_isf[i];
  819. } else
  820. diff_isf[i] = 5.0 - diff_isf[i - 1];
  821. }
  822. for (i = LP_ORDER - 1, j = 0; i < LP_ORDER_16k - 1; i++, j++)
  823. isf[i] = isf[i - 1] + diff_isf[j] * (1.0f / (1 << 15));
  824. /* Scale the ISF vector for 16000 Hz */
  825. for (i = 0; i < LP_ORDER_16k - 1; i++)
  826. isf[i] *= 0.8;
  827. }
  828. /**
  829. * Spectral expand the LP coefficients using the equation:
  830. * y[i] = x[i] * (gamma ** i)
  831. *
  832. * @param[out] out Output buffer (may use input array)
  833. * @param[in] lpc LP coefficients array
  834. * @param[in] gamma Weighting factor
  835. * @param[in] size LP array size
  836. */
  837. static void lpc_weighting(float *out, const float *lpc, float gamma, int size)
  838. {
  839. int i;
  840. float fac = gamma;
  841. for (i = 0; i < size; i++) {
  842. out[i] = lpc[i] * fac;
  843. fac *= gamma;
  844. }
  845. }
  846. /**
  847. * Conduct 20th order linear predictive coding synthesis for the high
  848. * frequency band excitation at 16kHz.
  849. *
  850. * @param[in] ctx The context
  851. * @param[in] subframe Current subframe index (0 to 3)
  852. * @param[in,out] samples Pointer to the output speech samples
  853. * @param[in] exc Generated white-noise scaled excitation
  854. * @param[in] isf Current frame isf vector
  855. * @param[in] isf_past Past frame final isf vector
  856. */
  857. static void hb_synthesis(AMRWBContext *ctx, int subframe, float *samples,
  858. const float *exc, const float *isf, const float *isf_past)
  859. {
  860. float hb_lpc[LP_ORDER_16k];
  861. enum Mode mode = ctx->fr_cur_mode;
  862. if (mode == MODE_6k60) {
  863. float e_isf[LP_ORDER_16k]; // ISF vector for extrapolation
  864. double e_isp[LP_ORDER_16k];
  865. ff_weighted_vector_sumf(e_isf, isf_past, isf, isfp_inter[subframe],
  866. 1.0 - isfp_inter[subframe], LP_ORDER);
  867. extrapolate_isf(e_isf);
  868. e_isf[LP_ORDER_16k - 1] *= 2.0;
  869. ff_acelp_lsf2lspd(e_isp, e_isf, LP_ORDER_16k);
  870. ff_amrwb_lsp2lpc(e_isp, hb_lpc, LP_ORDER_16k);
  871. lpc_weighting(hb_lpc, hb_lpc, 0.9, LP_ORDER_16k);
  872. } else {
  873. lpc_weighting(hb_lpc, ctx->lp_coef[subframe], 0.6, LP_ORDER);
  874. }
  875. ff_celp_lp_synthesis_filterf(samples, hb_lpc, exc, AMRWB_SFR_SIZE_16k,
  876. (mode == MODE_6k60) ? LP_ORDER_16k : LP_ORDER);
  877. }
  878. /**
  879. * Apply a 15th order filter to high-band samples.
  880. * The filter characteristic depends on the given coefficients.
  881. *
  882. * @param[out] out Buffer for filtered output
  883. * @param[in] fir_coef Filter coefficients
  884. * @param[in,out] mem State from last filtering (updated)
  885. * @param[in] in Input speech data (high-band)
  886. *
  887. * @remark It is safe to pass the same array in in and out parameters
  888. */
  889. static void hb_fir_filter(float *out, const float fir_coef[HB_FIR_SIZE + 1],
  890. float mem[HB_FIR_SIZE], const float *in)
  891. {
  892. int i, j;
  893. float data[AMRWB_SFR_SIZE_16k + HB_FIR_SIZE]; // past and current samples
  894. memcpy(data, mem, HB_FIR_SIZE * sizeof(float));
  895. memcpy(data + HB_FIR_SIZE, in, AMRWB_SFR_SIZE_16k * sizeof(float));
  896. for (i = 0; i < AMRWB_SFR_SIZE_16k; i++) {
  897. out[i] = 0.0;
  898. for (j = 0; j <= HB_FIR_SIZE; j++)
  899. out[i] += data[i + j] * fir_coef[j];
  900. }
  901. memcpy(mem, data + AMRWB_SFR_SIZE_16k, HB_FIR_SIZE * sizeof(float));
  902. }
  903. /**
  904. * Update context state before the next subframe.
  905. */
  906. static void update_sub_state(AMRWBContext *ctx)
  907. {
  908. memmove(&ctx->excitation_buf[0], &ctx->excitation_buf[AMRWB_SFR_SIZE],
  909. (AMRWB_P_DELAY_MAX + LP_ORDER + 1) * sizeof(float));
  910. memmove(&ctx->pitch_gain[1], &ctx->pitch_gain[0], 5 * sizeof(float));
  911. memmove(&ctx->fixed_gain[1], &ctx->fixed_gain[0], 1 * sizeof(float));
  912. memmove(&ctx->samples_az[0], &ctx->samples_az[AMRWB_SFR_SIZE],
  913. LP_ORDER * sizeof(float));
  914. memmove(&ctx->samples_up[0], &ctx->samples_up[AMRWB_SFR_SIZE],
  915. UPS_MEM_SIZE * sizeof(float));
  916. memmove(&ctx->samples_hb[0], &ctx->samples_hb[AMRWB_SFR_SIZE_16k],
  917. LP_ORDER_16k * sizeof(float));
  918. }
  919. static int amrwb_decode_frame(AVCodecContext *avctx, void *data,
  920. int *got_frame_ptr, AVPacket *avpkt)
  921. {
  922. AMRWBContext *ctx = avctx->priv_data;
  923. AMRWBFrame *cf = &ctx->frame;
  924. const uint8_t *buf = avpkt->data;
  925. int buf_size = avpkt->size;
  926. int expected_fr_size, header_size;
  927. float *buf_out;
  928. float spare_vector[AMRWB_SFR_SIZE]; // extra stack space to hold result from anti-sparseness processing
  929. float fixed_gain_factor; // fixed gain correction factor (gamma)
  930. float *synth_fixed_vector; // pointer to the fixed vector that synthesis should use
  931. float synth_fixed_gain; // the fixed gain that synthesis should use
  932. float voice_fac, stab_fac; // parameters used for gain smoothing
  933. float synth_exc[AMRWB_SFR_SIZE]; // post-processed excitation for synthesis
  934. float hb_exc[AMRWB_SFR_SIZE_16k]; // excitation for the high frequency band
  935. float hb_samples[AMRWB_SFR_SIZE_16k]; // filtered high-band samples from synthesis
  936. float hb_gain;
  937. int sub, i, ret;
  938. /* get output buffer */
  939. ctx->avframe.nb_samples = 4 * AMRWB_SFR_SIZE_16k;
  940. if ((ret = ff_get_buffer(avctx, &ctx->avframe)) < 0) {
  941. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  942. return ret;
  943. }
  944. buf_out = (float *)ctx->avframe.data[0];
  945. header_size = decode_mime_header(ctx, buf);
  946. if (ctx->fr_cur_mode > MODE_SID) {
  947. av_log(avctx, AV_LOG_ERROR,
  948. "Invalid mode %d\n", ctx->fr_cur_mode);
  949. return AVERROR_INVALIDDATA;
  950. }
  951. expected_fr_size = ((cf_sizes_wb[ctx->fr_cur_mode] + 7) >> 3) + 1;
  952. if (buf_size < expected_fr_size) {
  953. av_log(avctx, AV_LOG_ERROR,
  954. "Frame too small (%d bytes). Truncated file?\n", buf_size);
  955. *got_frame_ptr = 0;
  956. return AVERROR_INVALIDDATA;
  957. }
  958. if (!ctx->fr_quality || ctx->fr_cur_mode > MODE_SID)
  959. av_log(avctx, AV_LOG_ERROR, "Encountered a bad or corrupted frame\n");
  960. if (ctx->fr_cur_mode == MODE_SID) { /* Comfort noise frame */
  961. av_log_missing_feature(avctx, "SID mode", 1);
  962. return AVERROR_PATCHWELCOME;
  963. }
  964. ff_amr_bit_reorder((uint16_t *) &ctx->frame, sizeof(AMRWBFrame),
  965. buf + header_size, amr_bit_orderings_by_mode[ctx->fr_cur_mode]);
  966. /* Decode the quantized ISF vector */
  967. if (ctx->fr_cur_mode == MODE_6k60) {
  968. decode_isf_indices_36b(cf->isp_id, ctx->isf_cur);
  969. } else {
  970. decode_isf_indices_46b(cf->isp_id, ctx->isf_cur);
  971. }
  972. isf_add_mean_and_past(ctx->isf_cur, ctx->isf_q_past);
  973. ff_set_min_dist_lsf(ctx->isf_cur, MIN_ISF_SPACING, LP_ORDER - 1);
  974. stab_fac = stability_factor(ctx->isf_cur, ctx->isf_past_final);
  975. ctx->isf_cur[LP_ORDER - 1] *= 2.0;
  976. ff_acelp_lsf2lspd(ctx->isp[3], ctx->isf_cur, LP_ORDER);
  977. /* Generate a ISP vector for each subframe */
  978. if (ctx->first_frame) {
  979. ctx->first_frame = 0;
  980. memcpy(ctx->isp_sub4_past, ctx->isp[3], LP_ORDER * sizeof(double));
  981. }
  982. interpolate_isp(ctx->isp, ctx->isp_sub4_past);
  983. for (sub = 0; sub < 4; sub++)
  984. ff_amrwb_lsp2lpc(ctx->isp[sub], ctx->lp_coef[sub], LP_ORDER);
  985. for (sub = 0; sub < 4; sub++) {
  986. const AMRWBSubFrame *cur_subframe = &cf->subframe[sub];
  987. float *sub_buf = buf_out + sub * AMRWB_SFR_SIZE_16k;
  988. /* Decode adaptive codebook (pitch vector) */
  989. decode_pitch_vector(ctx, cur_subframe, sub);
  990. /* Decode innovative codebook (fixed vector) */
  991. decode_fixed_vector(ctx->fixed_vector, cur_subframe->pul_ih,
  992. cur_subframe->pul_il, ctx->fr_cur_mode);
  993. pitch_sharpening(ctx, ctx->fixed_vector);
  994. decode_gains(cur_subframe->vq_gain, ctx->fr_cur_mode,
  995. &fixed_gain_factor, &ctx->pitch_gain[0]);
  996. ctx->fixed_gain[0] =
  997. ff_amr_set_fixed_gain(fixed_gain_factor,
  998. ff_scalarproduct_float_c(ctx->fixed_vector,
  999. ctx->fixed_vector,
  1000. AMRWB_SFR_SIZE) /
  1001. AMRWB_SFR_SIZE,
  1002. ctx->prediction_error,
  1003. ENERGY_MEAN, energy_pred_fac);
  1004. /* Calculate voice factor and store tilt for next subframe */
  1005. voice_fac = voice_factor(ctx->pitch_vector, ctx->pitch_gain[0],
  1006. ctx->fixed_vector, ctx->fixed_gain[0]);
  1007. ctx->tilt_coef = voice_fac * 0.25 + 0.25;
  1008. /* Construct current excitation */
  1009. for (i = 0; i < AMRWB_SFR_SIZE; i++) {
  1010. ctx->excitation[i] *= ctx->pitch_gain[0];
  1011. ctx->excitation[i] += ctx->fixed_gain[0] * ctx->fixed_vector[i];
  1012. ctx->excitation[i] = truncf(ctx->excitation[i]);
  1013. }
  1014. /* Post-processing of excitation elements */
  1015. synth_fixed_gain = noise_enhancer(ctx->fixed_gain[0], &ctx->prev_tr_gain,
  1016. voice_fac, stab_fac);
  1017. synth_fixed_vector = anti_sparseness(ctx, ctx->fixed_vector,
  1018. spare_vector);
  1019. pitch_enhancer(synth_fixed_vector, voice_fac);
  1020. synthesis(ctx, ctx->lp_coef[sub], synth_exc, synth_fixed_gain,
  1021. synth_fixed_vector, &ctx->samples_az[LP_ORDER]);
  1022. /* Synthesis speech post-processing */
  1023. de_emphasis(&ctx->samples_up[UPS_MEM_SIZE],
  1024. &ctx->samples_az[LP_ORDER], PREEMPH_FAC, ctx->demph_mem);
  1025. ff_acelp_apply_order_2_transfer_function(&ctx->samples_up[UPS_MEM_SIZE],
  1026. &ctx->samples_up[UPS_MEM_SIZE], hpf_zeros, hpf_31_poles,
  1027. hpf_31_gain, ctx->hpf_31_mem, AMRWB_SFR_SIZE);
  1028. upsample_5_4(sub_buf, &ctx->samples_up[UPS_FIR_SIZE],
  1029. AMRWB_SFR_SIZE_16k);
  1030. /* High frequency band (6.4 - 7.0 kHz) generation part */
  1031. ff_acelp_apply_order_2_transfer_function(hb_samples,
  1032. &ctx->samples_up[UPS_MEM_SIZE], hpf_zeros, hpf_400_poles,
  1033. hpf_400_gain, ctx->hpf_400_mem, AMRWB_SFR_SIZE);
  1034. hb_gain = find_hb_gain(ctx, hb_samples,
  1035. cur_subframe->hb_gain, cf->vad);
  1036. scaled_hb_excitation(ctx, hb_exc, synth_exc, hb_gain);
  1037. hb_synthesis(ctx, sub, &ctx->samples_hb[LP_ORDER_16k],
  1038. hb_exc, ctx->isf_cur, ctx->isf_past_final);
  1039. /* High-band post-processing filters */
  1040. hb_fir_filter(hb_samples, bpf_6_7_coef, ctx->bpf_6_7_mem,
  1041. &ctx->samples_hb[LP_ORDER_16k]);
  1042. if (ctx->fr_cur_mode == MODE_23k85)
  1043. hb_fir_filter(hb_samples, lpf_7_coef, ctx->lpf_7_mem,
  1044. hb_samples);
  1045. /* Add the low and high frequency bands */
  1046. for (i = 0; i < AMRWB_SFR_SIZE_16k; i++)
  1047. sub_buf[i] = (sub_buf[i] + hb_samples[i]) * (1.0f / (1 << 15));
  1048. /* Update buffers and history */
  1049. update_sub_state(ctx);
  1050. }
  1051. /* update state for next frame */
  1052. memcpy(ctx->isp_sub4_past, ctx->isp[3], LP_ORDER * sizeof(ctx->isp[3][0]));
  1053. memcpy(ctx->isf_past_final, ctx->isf_cur, LP_ORDER * sizeof(float));
  1054. *got_frame_ptr = 1;
  1055. *(AVFrame *)data = ctx->avframe;
  1056. return expected_fr_size;
  1057. }
  1058. AVCodec ff_amrwb_decoder = {
  1059. .name = "amrwb",
  1060. .type = AVMEDIA_TYPE_AUDIO,
  1061. .id = AV_CODEC_ID_AMR_WB,
  1062. .priv_data_size = sizeof(AMRWBContext),
  1063. .init = amrwb_decode_init,
  1064. .decode = amrwb_decode_frame,
  1065. .capabilities = CODEC_CAP_DR1,
  1066. .long_name = NULL_IF_CONFIG_SMALL("AMR-WB (Adaptive Multi-Rate WideBand)"),
  1067. .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLT,
  1068. AV_SAMPLE_FMT_NONE },
  1069. };