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.

2217 lines
70KB

  1. /*
  2. * G.723.1 compatible decoder
  3. * Copyright (c) 2006 Benjamin Larsson
  4. * Copyright (c) 2010 Mohamed Naufal Basheer
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. /**
  23. * @file
  24. * G.723.1 compatible decoder
  25. */
  26. #include "avcodec.h"
  27. #define ALT_BITSTREAM_READER_LE
  28. #include "get_bits.h"
  29. #include "acelp_vectors.h"
  30. #include "celp_filters.h"
  31. #include "celp_math.h"
  32. #include "lsp.h"
  33. #include "libavutil/lzo.h"
  34. #include "g723_1_data.h"
  35. typedef struct g723_1_context {
  36. G723_1_Subframe subframe[4];
  37. FrameType cur_frame_type;
  38. FrameType past_frame_type;
  39. Rate cur_rate;
  40. uint8_t lsp_index[LSP_BANDS];
  41. int pitch_lag[2];
  42. int erased_frames;
  43. int16_t prev_lsp[LPC_ORDER];
  44. int16_t prev_excitation[PITCH_MAX];
  45. int16_t excitation[PITCH_MAX + FRAME_LEN];
  46. int16_t synth_mem[LPC_ORDER];
  47. int16_t fir_mem[LPC_ORDER];
  48. int iir_mem[LPC_ORDER];
  49. int random_seed;
  50. int interp_index;
  51. int interp_gain;
  52. int sid_gain;
  53. int cur_gain;
  54. int reflection_coef;
  55. int pf_gain; ///< formant postfilter
  56. ///< gain scaling unit memory
  57. int16_t prev_data[HALF_FRAME_LEN];
  58. int16_t prev_weight_sig[PITCH_MAX];
  59. int16_t hpf_fir_mem; ///< highpass filter fir
  60. int hpf_iir_mem; ///< and iir memories
  61. int16_t perf_fir_mem[LPC_ORDER]; ///< perceptual filter fir
  62. int16_t perf_iir_mem[LPC_ORDER]; ///< and iir memories
  63. int16_t harmonic_mem[PITCH_MAX];
  64. } G723_1_Context;
  65. static av_cold int g723_1_decode_init(AVCodecContext *avctx)
  66. {
  67. G723_1_Context *p = avctx->priv_data;
  68. avctx->sample_fmt = SAMPLE_FMT_S16;
  69. p->pf_gain = 1 << 12;
  70. memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(int16_t));
  71. return 0;
  72. }
  73. /**
  74. * Unpack the frame into parameters.
  75. *
  76. * @param p the context
  77. * @param buf pointer to the input buffer
  78. * @param buf_size size of the input buffer
  79. */
  80. static int unpack_bitstream(G723_1_Context *p, const uint8_t *buf,
  81. int buf_size)
  82. {
  83. GetBitContext gb;
  84. int ad_cb_len;
  85. int temp, info_bits, i;
  86. init_get_bits(&gb, buf, buf_size * 8);
  87. /* Extract frame type and rate info */
  88. info_bits = get_bits(&gb, 2);
  89. if (info_bits == 3) {
  90. p->cur_frame_type = UntransmittedFrame;
  91. return 0;
  92. }
  93. /* Extract 24 bit lsp indices, 8 bit for each band */
  94. p->lsp_index[2] = get_bits(&gb, 8);
  95. p->lsp_index[1] = get_bits(&gb, 8);
  96. p->lsp_index[0] = get_bits(&gb, 8);
  97. if (info_bits == 2) {
  98. p->cur_frame_type = SIDFrame;
  99. p->subframe[0].amp_index = get_bits(&gb, 6);
  100. return 0;
  101. }
  102. /* Extract the info common to both rates */
  103. p->cur_rate = info_bits ? Rate5k3 : Rate6k3;
  104. p->cur_frame_type = ActiveFrame;
  105. p->pitch_lag[0] = get_bits(&gb, 7);
  106. if (p->pitch_lag[0] > 123) /* test if forbidden code */
  107. return -1;
  108. p->pitch_lag[0] += PITCH_MIN;
  109. p->subframe[1].ad_cb_lag = get_bits(&gb, 2);
  110. p->pitch_lag[1] = get_bits(&gb, 7);
  111. if (p->pitch_lag[1] > 123)
  112. return -1;
  113. p->pitch_lag[1] += PITCH_MIN;
  114. p->subframe[3].ad_cb_lag = get_bits(&gb, 2);
  115. p->subframe[0].ad_cb_lag = 1;
  116. p->subframe[2].ad_cb_lag = 1;
  117. for (i = 0; i < SUBFRAMES; i++) {
  118. /* Extract combined gain */
  119. temp = get_bits(&gb, 12);
  120. ad_cb_len = 170;
  121. p->subframe[i].dirac_train = 0;
  122. if (p->cur_rate == Rate6k3 && p->pitch_lag[i >> 1] < SUBFRAME_LEN - 2) {
  123. p->subframe[i].dirac_train = temp >> 11;
  124. temp &= 0x7ff;
  125. ad_cb_len = 85;
  126. }
  127. p->subframe[i].ad_cb_gain = FASTDIV(temp, GAIN_LEVELS);
  128. if (p->subframe[i].ad_cb_gain < ad_cb_len) {
  129. p->subframe[i].amp_index = temp - p->subframe[i].ad_cb_gain *
  130. GAIN_LEVELS;
  131. } else {
  132. return -1;
  133. }
  134. }
  135. p->subframe[0].grid_index = get_bits1(&gb);
  136. p->subframe[1].grid_index = get_bits1(&gb);
  137. p->subframe[2].grid_index = get_bits1(&gb);
  138. p->subframe[3].grid_index = get_bits1(&gb);
  139. if (p->cur_rate == Rate6k3) {
  140. skip_bits1(&gb); /* skip reserved bit */
  141. /* Compute pulse_pos index using the 13-bit combined position index */
  142. temp = get_bits(&gb, 13);
  143. p->subframe[0].pulse_pos = temp / 810;
  144. temp -= p->subframe[0].pulse_pos * 810;
  145. p->subframe[1].pulse_pos = FASTDIV(temp, 90);
  146. temp -= p->subframe[1].pulse_pos * 90;
  147. p->subframe[2].pulse_pos = FASTDIV(temp, 9);
  148. p->subframe[3].pulse_pos = temp - p->subframe[2].pulse_pos * 9;
  149. p->subframe[0].pulse_pos = (p->subframe[0].pulse_pos << 16) +
  150. get_bits(&gb, 16);
  151. p->subframe[1].pulse_pos = (p->subframe[1].pulse_pos << 14) +
  152. get_bits(&gb, 14);
  153. p->subframe[2].pulse_pos = (p->subframe[2].pulse_pos << 16) +
  154. get_bits(&gb, 16);
  155. p->subframe[3].pulse_pos = (p->subframe[3].pulse_pos << 14) +
  156. get_bits(&gb, 14);
  157. p->subframe[0].pulse_sign = get_bits(&gb, 6);
  158. p->subframe[1].pulse_sign = get_bits(&gb, 5);
  159. p->subframe[2].pulse_sign = get_bits(&gb, 6);
  160. p->subframe[3].pulse_sign = get_bits(&gb, 5);
  161. } else { /* Rate5k3 */
  162. p->subframe[0].pulse_pos = get_bits(&gb, 12);
  163. p->subframe[1].pulse_pos = get_bits(&gb, 12);
  164. p->subframe[2].pulse_pos = get_bits(&gb, 12);
  165. p->subframe[3].pulse_pos = get_bits(&gb, 12);
  166. p->subframe[0].pulse_sign = get_bits(&gb, 4);
  167. p->subframe[1].pulse_sign = get_bits(&gb, 4);
  168. p->subframe[2].pulse_sign = get_bits(&gb, 4);
  169. p->subframe[3].pulse_sign = get_bits(&gb, 4);
  170. }
  171. return 0;
  172. }
  173. /**
  174. * Bitexact implementation of sqrt(val/2).
  175. */
  176. static int16_t square_root(int val)
  177. {
  178. return (ff_sqrt(val << 1) >> 1) & (~1);
  179. }
  180. /**
  181. * Calculate the number of left-shifts required for normalizing the input.
  182. *
  183. * @param num input number
  184. * @param width width of the input, 16 bits(0) / 32 bits(1)
  185. */
  186. static int normalize_bits(int num, int width)
  187. {
  188. int i = 0;
  189. int bits = (width) ? 31 : 15;
  190. if (num) {
  191. if (num == -1)
  192. return bits;
  193. if (num < 0)
  194. num = ~num;
  195. i= bits - av_log2(num) - 1;
  196. i= FFMAX(i, 0);
  197. }
  198. return i;
  199. }
  200. #define normalize_bits_int16(num) normalize_bits(num, 0)
  201. #define normalize_bits_int32(num) normalize_bits(num, 1)
  202. #define dot_product(a,b,c,d) (ff_dot_product(a,b,c)<<(d))
  203. /**
  204. * Scale vector contents based on the largest of their absolutes.
  205. */
  206. static int scale_vector(int16_t *vector, int length)
  207. {
  208. int bits, scale, max = 0;
  209. int i;
  210. const int16_t shift_table[16] = {
  211. 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  212. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000, 0x7fff
  213. };
  214. for (i = 0; i < length; i++)
  215. max = FFMAX(max, FFABS(vector[i]));
  216. bits = normalize_bits(max, 0);
  217. scale = shift_table[bits];
  218. for (i = 0; i < length; i++)
  219. vector[i] = (vector[i] * scale) >> 3;
  220. return bits - 3;
  221. }
  222. /**
  223. * Perform inverse quantization of LSP frequencies.
  224. *
  225. * @param cur_lsp the current LSP vector
  226. * @param prev_lsp the previous LSP vector
  227. * @param lsp_index VQ indices
  228. * @param bad_frame bad frame flag
  229. */
  230. static void inverse_quant(int16_t *cur_lsp, int16_t *prev_lsp,
  231. uint8_t *lsp_index, int bad_frame)
  232. {
  233. int min_dist, pred;
  234. int i, j, temp, stable;
  235. /* Check for frame erasure */
  236. if (!bad_frame) {
  237. min_dist = 0x100;
  238. pred = 12288;
  239. } else {
  240. min_dist = 0x200;
  241. pred = 23552;
  242. lsp_index[0] = lsp_index[1] = lsp_index[2] = 0;
  243. }
  244. /* Get the VQ table entry corresponding to the transmitted index */
  245. cur_lsp[0] = lsp_band0[lsp_index[0]][0];
  246. cur_lsp[1] = lsp_band0[lsp_index[0]][1];
  247. cur_lsp[2] = lsp_band0[lsp_index[0]][2];
  248. cur_lsp[3] = lsp_band1[lsp_index[1]][0];
  249. cur_lsp[4] = lsp_band1[lsp_index[1]][1];
  250. cur_lsp[5] = lsp_band1[lsp_index[1]][2];
  251. cur_lsp[6] = lsp_band2[lsp_index[2]][0];
  252. cur_lsp[7] = lsp_band2[lsp_index[2]][1];
  253. cur_lsp[8] = lsp_band2[lsp_index[2]][2];
  254. cur_lsp[9] = lsp_band2[lsp_index[2]][3];
  255. /* Add predicted vector & DC component to the previously quantized vector */
  256. for (i = 0; i < LPC_ORDER; i++) {
  257. temp = ((prev_lsp[i] - dc_lsp[i]) * pred + (1 << 14)) >> 15;
  258. cur_lsp[i] += dc_lsp[i] + temp;
  259. }
  260. for (i = 0; i < LPC_ORDER; i++) {
  261. cur_lsp[0] = FFMAX(cur_lsp[0], 0x180);
  262. cur_lsp[LPC_ORDER - 1] = FFMIN(cur_lsp[LPC_ORDER - 1], 0x7e00);
  263. /* Stability check */
  264. for (j = 1; j < LPC_ORDER; j++) {
  265. temp = min_dist + cur_lsp[j - 1] - cur_lsp[j];
  266. if (temp > 0) {
  267. temp >>= 1;
  268. cur_lsp[j - 1] -= temp;
  269. cur_lsp[j] += temp;
  270. }
  271. }
  272. stable = 1;
  273. for (j = 1; j < LPC_ORDER; j++) {
  274. temp = cur_lsp[j - 1] + min_dist - cur_lsp[j] - 4;
  275. if (temp > 0) {
  276. stable = 0;
  277. break;
  278. }
  279. }
  280. if (stable)
  281. break;
  282. }
  283. if (!stable)
  284. memcpy(cur_lsp, prev_lsp, LPC_ORDER * sizeof(int16_t));
  285. }
  286. /**
  287. * Bitexact implementation of 2ab scaled by 1/2^16.
  288. *
  289. * @param a 32 bit multiplicand
  290. * @param b 16 bit multiplier
  291. */
  292. #define MULL2(a, b) \
  293. MULL(a,b,15)
  294. /**
  295. * Convert LSP frequencies to LPC coefficients.
  296. *
  297. * @param lpc buffer for LPC coefficients
  298. */
  299. static void lsp2lpc(int16_t *lpc)
  300. {
  301. int f1[LPC_ORDER / 2 + 1];
  302. int f2[LPC_ORDER / 2 + 1];
  303. int i, j;
  304. /* Calculate negative cosine */
  305. for (j = 0; j < LPC_ORDER; j++) {
  306. int index = lpc[j] >> 7;
  307. int offset = lpc[j] & 0x7f;
  308. int64_t temp1 = cos_tab[index] << 16;
  309. int temp2 = (cos_tab[index + 1] - cos_tab[index]) *
  310. ((offset << 8) + 0x80) << 1;
  311. lpc[j] = -(av_clipl_int32(((temp1 + temp2) << 1) + (1 << 15)) >> 16);
  312. }
  313. /*
  314. * Compute sum and difference polynomial coefficients
  315. * (bitexact alternative to lsp2poly() in lsp.c)
  316. */
  317. /* Initialize with values in Q28 */
  318. f1[0] = 1 << 28;
  319. f1[1] = (lpc[0] << 14) + (lpc[2] << 14);
  320. f1[2] = lpc[0] * lpc[2] + (2 << 28);
  321. f2[0] = 1 << 28;
  322. f2[1] = (lpc[1] << 14) + (lpc[3] << 14);
  323. f2[2] = lpc[1] * lpc[3] + (2 << 28);
  324. /*
  325. * Calculate and scale the coefficients by 1/2 in
  326. * each iteration for a final scaling factor of Q25
  327. */
  328. for (i = 2; i < LPC_ORDER / 2; i++) {
  329. f1[i + 1] = f1[i - 1] + MULL2(f1[i], lpc[2 * i]);
  330. f2[i + 1] = f2[i - 1] + MULL2(f2[i], lpc[2 * i + 1]);
  331. for (j = i; j >= 2; j--) {
  332. f1[j] = MULL2(f1[j - 1], lpc[2 * i]) +
  333. (f1[j] >> 1) + (f1[j - 2] >> 1);
  334. f2[j] = MULL2(f2[j - 1], lpc[2 * i + 1]) +
  335. (f2[j] >> 1) + (f2[j - 2] >> 1);
  336. }
  337. f1[0] >>= 1;
  338. f2[0] >>= 1;
  339. f1[1] = ((lpc[2 * i] << 16 >> i) + f1[1]) >> 1;
  340. f2[1] = ((lpc[2 * i + 1] << 16 >> i) + f2[1]) >> 1;
  341. }
  342. /* Convert polynomial coefficients to LPC coefficients */
  343. for (i = 0; i < LPC_ORDER / 2; i++) {
  344. int64_t ff1 = f1[i + 1] + f1[i];
  345. int64_t ff2 = f2[i + 1] - f2[i];
  346. lpc[i] = av_clipl_int32(((ff1 + ff2) << 3) + (1 << 15)) >> 16;
  347. lpc[LPC_ORDER - i - 1] = av_clipl_int32(((ff1 - ff2) << 3) +
  348. (1 << 15)) >> 16;
  349. }
  350. }
  351. /**
  352. * Quantize LSP frequencies by interpolation and convert them to
  353. * the corresponding LPC coefficients.
  354. *
  355. * @param lpc buffer for LPC coefficients
  356. * @param cur_lsp the current LSP vector
  357. * @param prev_lsp the previous LSP vector
  358. */
  359. static void lsp_interpolate(int16_t *lpc, int16_t *cur_lsp, int16_t *prev_lsp)
  360. {
  361. int i;
  362. int16_t *lpc_ptr = lpc;
  363. /* cur_lsp * 0.25 + prev_lsp * 0.75 */
  364. ff_acelp_weighted_vector_sum(lpc, cur_lsp, prev_lsp,
  365. 4096, 12288, 1 << 13, 14, LPC_ORDER);
  366. ff_acelp_weighted_vector_sum(lpc + LPC_ORDER, cur_lsp, prev_lsp,
  367. 8192, 8192, 1 << 13, 14, LPC_ORDER);
  368. ff_acelp_weighted_vector_sum(lpc + 2 * LPC_ORDER, cur_lsp, prev_lsp,
  369. 12288, 4096, 1 << 13, 14, LPC_ORDER);
  370. memcpy(lpc + 3 * LPC_ORDER, cur_lsp, LPC_ORDER * sizeof(int16_t));
  371. for (i = 0; i < SUBFRAMES; i++) {
  372. lsp2lpc(lpc_ptr);
  373. lpc_ptr += LPC_ORDER;
  374. }
  375. }
  376. /**
  377. * Generate a train of dirac functions with period as pitch lag.
  378. */
  379. static void gen_dirac_train(int16_t *buf, int pitch_lag)
  380. {
  381. int16_t vector[SUBFRAME_LEN];
  382. int i, j;
  383. memcpy(vector, buf, SUBFRAME_LEN * sizeof(int16_t));
  384. for (i = pitch_lag; i < SUBFRAME_LEN; i += pitch_lag) {
  385. for (j = 0; j < SUBFRAME_LEN - i; j++)
  386. buf[i + j] += vector[j];
  387. }
  388. }
  389. /**
  390. * Generate fixed codebook excitation vector.
  391. *
  392. * @param vector decoded excitation vector
  393. * @param subfrm current subframe
  394. * @param cur_rate current bitrate
  395. * @param pitch_lag closed loop pitch lag
  396. * @param index current subframe index
  397. */
  398. static void gen_fcb_excitation(int16_t *vector, G723_1_Subframe subfrm,
  399. Rate cur_rate, int pitch_lag, int index)
  400. {
  401. int temp, i, j;
  402. memset(vector, 0, SUBFRAME_LEN * sizeof(int16_t));
  403. if (cur_rate == Rate6k3) {
  404. if (subfrm.pulse_pos >= max_pos[index])
  405. return;
  406. /* Decode amplitudes and positions */
  407. j = PULSE_MAX - pulses[index];
  408. temp = subfrm.pulse_pos;
  409. for (i = 0; i < SUBFRAME_LEN / GRID_SIZE; i++) {
  410. temp -= combinatorial_table[j][i];
  411. if (temp >= 0)
  412. continue;
  413. temp += combinatorial_table[j++][i];
  414. if (subfrm.pulse_sign & (1 << (PULSE_MAX - j))) {
  415. vector[subfrm.grid_index + GRID_SIZE * i] =
  416. -fixed_cb_gain[subfrm.amp_index];
  417. } else {
  418. vector[subfrm.grid_index + GRID_SIZE * i] =
  419. fixed_cb_gain[subfrm.amp_index];
  420. }
  421. if (j == PULSE_MAX)
  422. break;
  423. }
  424. if (subfrm.dirac_train == 1)
  425. gen_dirac_train(vector, pitch_lag);
  426. } else { /* Rate5k3 */
  427. int cb_gain = fixed_cb_gain[subfrm.amp_index];
  428. int cb_shift = subfrm.grid_index;
  429. int cb_sign = subfrm.pulse_sign;
  430. int cb_pos = subfrm.pulse_pos;
  431. int offset, beta, lag;
  432. for (i = 0; i < 8; i += 2) {
  433. offset = ((cb_pos & 7) << 3) + cb_shift + i;
  434. vector[offset] = (cb_sign & 1) ? cb_gain : -cb_gain;
  435. cb_pos >>= 3;
  436. cb_sign >>= 1;
  437. }
  438. /* Enhance harmonic components */
  439. lag = pitch_contrib[subfrm.ad_cb_gain << 1] + pitch_lag +
  440. subfrm.ad_cb_lag - 1;
  441. beta = pitch_contrib[(subfrm.ad_cb_gain << 1) + 1];
  442. if (lag < SUBFRAME_LEN - 2) {
  443. for (i = lag; i < SUBFRAME_LEN; i++)
  444. vector[i] += beta * vector[i - lag] >> 15;
  445. }
  446. }
  447. }
  448. /**
  449. * Get delayed contribution from the previous excitation vector.
  450. */
  451. static void get_residual(int16_t *residual, int16_t *prev_excitation, int lag)
  452. {
  453. int offset = PITCH_MAX - PITCH_ORDER / 2 - lag;
  454. int i;
  455. residual[0] = prev_excitation[offset];
  456. residual[1] = prev_excitation[offset + 1];
  457. offset += 2;
  458. for (i = 2; i < SUBFRAME_LEN + PITCH_ORDER - 1; i++)
  459. residual[i] = prev_excitation[offset + (i - 2) % lag];
  460. }
  461. /**
  462. * Generate adaptive codebook excitation.
  463. */
  464. static void gen_acb_excitation(int16_t *vector, int16_t *prev_excitation,
  465. int pitch_lag, G723_1_Subframe subfrm,
  466. Rate cur_rate)
  467. {
  468. int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
  469. const int16_t *cb_ptr;
  470. int lag = pitch_lag + subfrm.ad_cb_lag - 1;
  471. int i;
  472. int64_t sum;
  473. get_residual(residual, prev_excitation, lag);
  474. /* Select quantization table */
  475. if (cur_rate == Rate6k3 && pitch_lag < SUBFRAME_LEN - 2) {
  476. cb_ptr = adaptive_cb_gain85;
  477. } else
  478. cb_ptr = adaptive_cb_gain170;
  479. /* Calculate adaptive vector */
  480. cb_ptr += subfrm.ad_cb_gain * 20;
  481. for (i = 0; i < SUBFRAME_LEN; i++) {
  482. sum = ff_dot_product(residual + i, cb_ptr, PITCH_ORDER);
  483. vector[i] = av_clipl_int32((sum << 2) + (1 << 15)) >> 16;
  484. }
  485. }
  486. /**
  487. * Estimate maximum auto-correlation around pitch lag.
  488. *
  489. * @param p the context
  490. * @param offset offset of the excitation vector
  491. * @param ccr_max pointer to the maximum auto-correlation
  492. * @param pitch_lag decoded pitch lag
  493. * @param length length of autocorrelation
  494. * @param dir forward lag(1) / backward lag(-1)
  495. */
  496. static int autocorr_max(G723_1_Context *p, int offset, int *ccr_max,
  497. int pitch_lag, int length, int dir)
  498. {
  499. int limit, ccr, lag = 0;
  500. int16_t *buf = p->excitation + offset;
  501. int i;
  502. pitch_lag = FFMIN(PITCH_MAX - 3, pitch_lag);
  503. limit = FFMIN(FRAME_LEN + PITCH_MAX - offset - length, pitch_lag + 3);
  504. for (i = pitch_lag - 3; i <= limit; i++) {
  505. ccr = ff_dot_product(buf, buf + dir * i, length)<<1;
  506. if (ccr > *ccr_max) {
  507. *ccr_max = ccr;
  508. lag = i;
  509. }
  510. }
  511. return lag;
  512. }
  513. /**
  514. * Calculate pitch postfilter optimal and scaling gains.
  515. *
  516. * @param lag pitch postfilter forward/backward lag
  517. * @param ppf pitch postfilter parameters
  518. * @param cur_rate current bitrate
  519. * @param tgt_eng target energy
  520. * @param ccr cross-correlation
  521. * @param res_eng residual energy
  522. */
  523. static void comp_ppf_gains(int lag, PPFParam *ppf, Rate cur_rate,
  524. int tgt_eng, int ccr, int res_eng)
  525. {
  526. int pf_residual; /* square of postfiltered residual */
  527. int64_t temp1, temp2;
  528. ppf->index = lag;
  529. temp1 = tgt_eng * res_eng >> 1;
  530. temp2 = ccr * ccr << 1;
  531. if (temp2 > temp1) {
  532. if (ccr >= res_eng) {
  533. ppf->opt_gain = ppf_gain_weight[cur_rate];
  534. } else {
  535. ppf->opt_gain = (ccr << 15) / res_eng *
  536. ppf_gain_weight[cur_rate] >> 15;
  537. }
  538. /* pf_res^2 = tgt_eng + 2*ccr*gain + res_eng*gain^2 */
  539. temp1 = (tgt_eng << 15) + (ccr * ppf->opt_gain << 1);
  540. temp2 = (ppf->opt_gain * ppf->opt_gain >> 15) * res_eng;
  541. pf_residual = av_clipl_int32(temp1 + temp2 + (1 << 15)) >> 16;
  542. if (tgt_eng >= pf_residual << 1) {
  543. temp1 = 0x7fff;
  544. } else {
  545. temp1 = (tgt_eng << 14) / pf_residual;
  546. }
  547. /* scaling_gain = sqrt(tgt_eng/pf_res^2) */
  548. ppf->sc_gain = square_root(temp1 << 16);
  549. } else {
  550. ppf->opt_gain = 0;
  551. ppf->sc_gain = 0x7fff;
  552. }
  553. ppf->opt_gain = av_clip_int16(ppf->opt_gain * ppf->sc_gain >> 15);
  554. }
  555. /**
  556. * Calculate pitch postfilter parameters.
  557. *
  558. * @param p the context
  559. * @param offset offset of the excitation vector
  560. * @param pitch_lag decoded pitch lag
  561. * @param ppf pitch postfilter parameters
  562. * @param cur_rate current bitrate
  563. */
  564. static void comp_ppf_coeff(G723_1_Context *p, int offset, int pitch_lag,
  565. PPFParam *ppf, Rate cur_rate)
  566. {
  567. int16_t scale;
  568. int i;
  569. int64_t temp1, temp2;
  570. /*
  571. * 0 - target energy
  572. * 1 - forward cross-correlation
  573. * 2 - forward residual energy
  574. * 3 - backward cross-correlation
  575. * 4 - backward residual energy
  576. */
  577. int energy[5] = {0, 0, 0, 0, 0};
  578. int16_t *buf = p->excitation + offset;
  579. int fwd_lag = autocorr_max(p, offset, &energy[1], pitch_lag,
  580. SUBFRAME_LEN, 1);
  581. int back_lag = autocorr_max(p, offset, &energy[3], pitch_lag,
  582. SUBFRAME_LEN, -1);
  583. ppf->index = 0;
  584. ppf->opt_gain = 0;
  585. ppf->sc_gain = 0x7fff;
  586. /* Case 0, Section 3.6 */
  587. if (!back_lag && !fwd_lag)
  588. return;
  589. /* Compute target energy */
  590. energy[0] = ff_dot_product(buf, buf, SUBFRAME_LEN)<<1;
  591. /* Compute forward residual energy */
  592. if (fwd_lag)
  593. energy[2] = ff_dot_product(buf + fwd_lag, buf + fwd_lag,
  594. SUBFRAME_LEN)<<1;
  595. /* Compute backward residual energy */
  596. if (back_lag)
  597. energy[4] = ff_dot_product(buf - back_lag, buf - back_lag,
  598. SUBFRAME_LEN)<<1;
  599. /* Normalize and shorten */
  600. temp1 = 0;
  601. for (i = 0; i < 5; i++)
  602. temp1 = FFMAX(energy[i], temp1);
  603. scale = normalize_bits(temp1, 1);
  604. for (i = 0; i < 5; i++)
  605. energy[i] = av_clipl_int32(energy[i] << scale) >> 16;
  606. if (fwd_lag && !back_lag) { /* Case 1 */
  607. comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
  608. energy[2]);
  609. } else if (!fwd_lag) { /* Case 2 */
  610. comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
  611. energy[4]);
  612. } else { /* Case 3 */
  613. /*
  614. * Select the largest of energy[1]^2/energy[2]
  615. * and energy[3]^2/energy[4]
  616. */
  617. temp1 = energy[4] * ((energy[1] * energy[1] + (1 << 14)) >> 15);
  618. temp2 = energy[2] * ((energy[3] * energy[3] + (1 << 14)) >> 15);
  619. if (temp1 >= temp2) {
  620. comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
  621. energy[2]);
  622. } else {
  623. comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
  624. energy[4]);
  625. }
  626. }
  627. }
  628. /**
  629. * Classify frames as voiced/unvoiced.
  630. *
  631. * @param p the context
  632. * @param pitch_lag decoded pitch_lag
  633. * @param exc_eng excitation energy estimation
  634. * @param scale scaling factor of exc_eng
  635. *
  636. * @return residual interpolation index if voiced, 0 otherwise
  637. */
  638. static int comp_interp_index(G723_1_Context *p, int pitch_lag,
  639. int *exc_eng, int *scale)
  640. {
  641. int offset = PITCH_MAX + 2 * SUBFRAME_LEN;
  642. int16_t *buf = p->excitation + offset;
  643. int index, ccr, tgt_eng, best_eng, temp;
  644. *scale = scale_vector(p->excitation, FRAME_LEN + PITCH_MAX);
  645. /* Compute maximum backward cross-correlation */
  646. ccr = 0;
  647. index = autocorr_max(p, offset, &ccr, pitch_lag, SUBFRAME_LEN * 2, -1);
  648. ccr = av_clipl_int32((int64_t)ccr + (1 << 15)) >> 16;
  649. /* Compute target energy */
  650. tgt_eng = ff_dot_product(buf, buf, SUBFRAME_LEN * 2)<<1;
  651. *exc_eng = av_clipl_int32(tgt_eng + (1 << 15)) >> 16;
  652. if (ccr <= 0)
  653. return 0;
  654. /* Compute best energy */
  655. best_eng = ff_dot_product(buf - index, buf - index,
  656. SUBFRAME_LEN * 2)<<1;
  657. best_eng = av_clipl_int32((int64_t)best_eng + (1 << 15)) >> 16;
  658. temp = best_eng * *exc_eng >> 3;
  659. if (temp < ccr * ccr) {
  660. return index;
  661. } else
  662. return 0;
  663. }
  664. /**
  665. * Peform residual interpolation based on frame classification.
  666. *
  667. * @param buf decoded excitation vector
  668. * @param out output vector
  669. * @param lag decoded pitch lag
  670. * @param gain interpolated gain
  671. * @param rseed seed for random number generator
  672. */
  673. static void residual_interp(int16_t *buf, int16_t *out, int lag,
  674. int gain, int *rseed)
  675. {
  676. int i;
  677. if (lag) { /* Voiced */
  678. int16_t *vector_ptr = buf + PITCH_MAX;
  679. /* Attenuate */
  680. for (i = 0; i < lag; i++)
  681. vector_ptr[i - lag] = vector_ptr[i - lag] * 3 >> 2;
  682. av_memcpy_backptr((uint8_t*)vector_ptr, lag * sizeof(int16_t),
  683. FRAME_LEN * sizeof(int16_t));
  684. memcpy(out, vector_ptr, FRAME_LEN * sizeof(int16_t));
  685. } else { /* Unvoiced */
  686. for (i = 0; i < FRAME_LEN; i++) {
  687. *rseed = *rseed * 521 + 259;
  688. out[i] = gain * *rseed >> 15;
  689. }
  690. memset(buf, 0, (FRAME_LEN + PITCH_MAX) * sizeof(int16_t));
  691. }
  692. }
  693. /**
  694. * Perform IIR filtering.
  695. *
  696. * @param fir_coef FIR coefficients
  697. * @param iir_coef IIR coefficients
  698. * @param src source vector
  699. * @param dest destination vector
  700. * @param width width of the output, 16 bits(0) / 32 bits(1)
  701. */
  702. #define iir_filter(fir_coef, iir_coef, src, dest, width)\
  703. {\
  704. int m, n;\
  705. int res_shift = 16 & ~-(width);\
  706. int in_shift = 16 - res_shift;\
  707. \
  708. for (m = 0; m < SUBFRAME_LEN; m++) {\
  709. int64_t filter = 0;\
  710. for (n = 1; n <= LPC_ORDER; n++) {\
  711. filter -= (fir_coef)[n - 1] * (src)[m - n] -\
  712. (iir_coef)[n - 1] * ((dest)[m - n] >> in_shift);\
  713. }\
  714. \
  715. (dest)[m] = av_clipl_int32(((src)[m] << 16) + (filter << 3) +\
  716. (1 << 15)) >> res_shift;\
  717. }\
  718. }
  719. /**
  720. * Adjust gain of postfiltered signal.
  721. *
  722. * @param p the context
  723. * @param buf postfiltered output vector
  724. * @param energy input energy coefficient
  725. */
  726. static void gain_scale(G723_1_Context *p, int16_t * buf, int energy)
  727. {
  728. int num, denom, gain, bits1, bits2;
  729. int i;
  730. num = energy;
  731. denom = 0;
  732. for (i = 0; i < SUBFRAME_LEN; i++) {
  733. int64_t temp = buf[i] >> 2;
  734. temp = av_clipl_int32(MUL64(temp, temp) << 1);
  735. denom = av_clipl_int32(denom + temp);
  736. }
  737. if (num && denom) {
  738. bits1 = normalize_bits(num, 1);
  739. bits2 = normalize_bits(denom, 1);
  740. num = num << bits1 >> 1;
  741. denom <<= bits2;
  742. bits2 = 5 + bits1 - bits2;
  743. bits2 = FFMAX(0, bits2);
  744. gain = (num >> 1) / (denom >> 16);
  745. gain = square_root(gain << 16 >> bits2);
  746. } else {
  747. gain = 1 << 12;
  748. }
  749. for (i = 0; i < SUBFRAME_LEN; i++) {
  750. p->pf_gain = ((p->pf_gain << 4) - p->pf_gain + gain + (1 << 3)) >> 4;
  751. buf[i] = av_clip_int16((buf[i] * (p->pf_gain + (p->pf_gain >> 4)) +
  752. (1 << 10)) >> 11);
  753. }
  754. }
  755. /**
  756. * Perform formant filtering.
  757. *
  758. * @param p the context
  759. * @param lpc quantized lpc coefficients
  760. * @param buf output buffer
  761. */
  762. static void formant_postfilter(G723_1_Context *p, int16_t *lpc, int16_t *buf)
  763. {
  764. int16_t filter_coef[2][LPC_ORDER], *buf_ptr;
  765. int filter_signal[LPC_ORDER + FRAME_LEN], *signal_ptr;
  766. int i, j, k;
  767. memcpy(buf, p->fir_mem, LPC_ORDER * sizeof(int16_t));
  768. memcpy(filter_signal, p->iir_mem, LPC_ORDER * sizeof(int));
  769. for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
  770. for (k = 0; k < LPC_ORDER; k++) {
  771. filter_coef[0][k] = (-lpc[k] * postfilter_tbl[0][k] +
  772. (1 << 14)) >> 15;
  773. filter_coef[1][k] = (-lpc[k] * postfilter_tbl[1][k] +
  774. (1 << 14)) >> 15;
  775. }
  776. iir_filter(filter_coef[0], filter_coef[1], buf + i,
  777. filter_signal + i, 1);
  778. }
  779. memcpy(p->fir_mem, buf + FRAME_LEN, LPC_ORDER * sizeof(int16_t));
  780. memcpy(p->iir_mem, filter_signal + FRAME_LEN, LPC_ORDER * sizeof(int));
  781. buf_ptr = buf + LPC_ORDER;
  782. signal_ptr = filter_signal + LPC_ORDER;
  783. for (i = 0; i < SUBFRAMES; i++) {
  784. int16_t temp_vector[SUBFRAME_LEN];
  785. int16_t temp;
  786. int auto_corr[2];
  787. int scale, energy;
  788. /* Normalize */
  789. memcpy(temp_vector, buf_ptr, SUBFRAME_LEN * sizeof(int16_t));
  790. scale = scale_vector(temp_vector, SUBFRAME_LEN);
  791. /* Compute auto correlation coefficients */
  792. auto_corr[0] = ff_dot_product(temp_vector, temp_vector + 1,
  793. SUBFRAME_LEN - 1)<<1;
  794. auto_corr[1] = ff_dot_product(temp_vector, temp_vector,
  795. SUBFRAME_LEN)<<1;
  796. /* Compute reflection coefficient */
  797. temp = auto_corr[1] >> 16;
  798. if (temp) {
  799. temp = (auto_corr[0] >> 2) / temp;
  800. }
  801. p->reflection_coef = ((p->reflection_coef << 2) - p->reflection_coef +
  802. temp + 2) >> 2;
  803. temp = (p->reflection_coef * 0xffffc >> 3) & 0xfffc;
  804. /* Compensation filter */
  805. for (j = 0; j < SUBFRAME_LEN; j++) {
  806. buf_ptr[j] = av_clipl_int32(signal_ptr[j] +
  807. ((signal_ptr[j - 1] >> 16) *
  808. temp << 1)) >> 16;
  809. }
  810. /* Compute normalized signal energy */
  811. temp = 2 * scale + 4;
  812. if (temp < 0) {
  813. energy = av_clipl_int32((int64_t)auto_corr[1] << -temp);
  814. } else
  815. energy = auto_corr[1] >> temp;
  816. gain_scale(p, buf_ptr, energy);
  817. buf_ptr += SUBFRAME_LEN;
  818. signal_ptr += SUBFRAME_LEN;
  819. }
  820. }
  821. static int g723_1_decode_frame(AVCodecContext *avctx, void *data,
  822. int *data_size, AVPacket *avpkt)
  823. {
  824. G723_1_Context *p = avctx->priv_data;
  825. const uint8_t *buf = avpkt->data;
  826. int buf_size = avpkt->size;
  827. int16_t *out = data;
  828. int dec_mode = buf[0] & 3;
  829. PPFParam ppf[SUBFRAMES];
  830. int16_t cur_lsp[LPC_ORDER];
  831. int16_t lpc[SUBFRAMES * LPC_ORDER];
  832. int16_t acb_vector[SUBFRAME_LEN];
  833. int16_t *vector_ptr;
  834. int bad_frame = 0, i, j;
  835. if (!buf_size || buf_size < frame_size[dec_mode]) {
  836. *data_size = 0;
  837. return buf_size;
  838. }
  839. if (unpack_bitstream(p, buf, buf_size) < 0) {
  840. bad_frame = 1;
  841. p->cur_frame_type = p->past_frame_type == ActiveFrame ?
  842. ActiveFrame : UntransmittedFrame;
  843. }
  844. *data_size = FRAME_LEN * sizeof(int16_t);
  845. if(p->cur_frame_type == ActiveFrame) {
  846. if (!bad_frame) {
  847. p->erased_frames = 0;
  848. } else if(p->erased_frames != 3)
  849. p->erased_frames++;
  850. inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, bad_frame);
  851. lsp_interpolate(lpc, cur_lsp, p->prev_lsp);
  852. /* Save the lsp_vector for the next frame */
  853. memcpy(p->prev_lsp, cur_lsp, LPC_ORDER * sizeof(int16_t));
  854. /* Generate the excitation for the frame */
  855. memcpy(p->excitation, p->prev_excitation, PITCH_MAX * sizeof(int16_t));
  856. vector_ptr = p->excitation + PITCH_MAX;
  857. if (!p->erased_frames) {
  858. /* Update interpolation gain memory */
  859. p->interp_gain = fixed_cb_gain[(p->subframe[2].amp_index +
  860. p->subframe[3].amp_index) >> 1];
  861. for (i = 0; i < SUBFRAMES; i++) {
  862. gen_fcb_excitation(vector_ptr, p->subframe[i], p->cur_rate,
  863. p->pitch_lag[i >> 1], i);
  864. gen_acb_excitation(acb_vector, &p->excitation[SUBFRAME_LEN * i],
  865. p->pitch_lag[i >> 1], p->subframe[i],
  866. p->cur_rate);
  867. /* Get the total excitation */
  868. for (j = 0; j < SUBFRAME_LEN; j++) {
  869. vector_ptr[j] = av_clip_int16(vector_ptr[j] << 1);
  870. vector_ptr[j] = av_clip_int16(vector_ptr[j] +
  871. acb_vector[j]);
  872. }
  873. vector_ptr += SUBFRAME_LEN;
  874. }
  875. vector_ptr = p->excitation + PITCH_MAX;
  876. /* Save the excitation */
  877. memcpy(out, vector_ptr, FRAME_LEN * sizeof(int16_t));
  878. p->interp_index = comp_interp_index(p, p->pitch_lag[1],
  879. &p->sid_gain, &p->cur_gain);
  880. for (i = PITCH_MAX, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
  881. comp_ppf_coeff(p, i, p->pitch_lag[j >> 1],
  882. ppf + j, p->cur_rate);
  883. /* Restore the original excitation */
  884. memcpy(p->excitation, p->prev_excitation,
  885. PITCH_MAX * sizeof(int16_t));
  886. memcpy(vector_ptr, out, FRAME_LEN * sizeof(int16_t));
  887. /* Peform pitch postfiltering */
  888. for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
  889. ff_acelp_weighted_vector_sum(out + LPC_ORDER + i, vector_ptr + i,
  890. vector_ptr + i + ppf[j].index,
  891. ppf[j].sc_gain, ppf[j].opt_gain,
  892. 1 << 14, 15, SUBFRAME_LEN);
  893. } else {
  894. p->interp_gain = (p->interp_gain * 3 + 2) >> 2;
  895. if (p->erased_frames == 3) {
  896. /* Mute output */
  897. memset(p->excitation, 0,
  898. (FRAME_LEN + PITCH_MAX) * sizeof(int16_t));
  899. memset(out, 0, (FRAME_LEN + LPC_ORDER) * sizeof(int16_t));
  900. } else {
  901. /* Regenerate frame */
  902. residual_interp(p->excitation, out + LPC_ORDER, p->interp_index,
  903. p->interp_gain, &p->random_seed);
  904. }
  905. }
  906. /* Save the excitation for the next frame */
  907. memcpy(p->prev_excitation, p->excitation + FRAME_LEN,
  908. PITCH_MAX * sizeof(int16_t));
  909. } else {
  910. memset(out, 0, *data_size);
  911. av_log(avctx, AV_LOG_WARNING,
  912. "G.723.1: Comfort noise generation not supported yet\n");
  913. return frame_size[dec_mode];
  914. }
  915. p->past_frame_type = p->cur_frame_type;
  916. memcpy(out, p->synth_mem, LPC_ORDER * sizeof(int16_t));
  917. for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
  918. ff_celp_lp_synthesis_filter(out + i, &lpc[j * LPC_ORDER],
  919. out + i, SUBFRAME_LEN, LPC_ORDER,
  920. 0, 1, 1 << 12);
  921. memcpy(p->synth_mem, out + FRAME_LEN, LPC_ORDER * sizeof(int16_t));
  922. formant_postfilter(p, lpc, out);
  923. memmove(out, out + LPC_ORDER, *data_size);
  924. return frame_size[dec_mode];
  925. }
  926. AVCodec ff_g723_1_decoder = {
  927. .name = "g723_1",
  928. .type = AVMEDIA_TYPE_AUDIO,
  929. .id = CODEC_ID_G723_1,
  930. .priv_data_size = sizeof(G723_1_Context),
  931. .init = g723_1_decode_init,
  932. .decode = g723_1_decode_frame,
  933. .long_name = NULL_IF_CONFIG_SMALL("G.723.1"),
  934. .capabilities = CODEC_CAP_SUBFRAMES,
  935. };
  936. #if CONFIG_G723_1_ENCODER
  937. #define BITSTREAM_WRITER_LE
  938. #include "put_bits.h"
  939. static av_cold int g723_1_encode_init(AVCodecContext *avctx)
  940. {
  941. G723_1_Context *p = avctx->priv_data;
  942. if (avctx->sample_rate != 8000) {
  943. av_log(avctx, AV_LOG_ERROR, "Only 8000Hz sample rate supported\n");
  944. return -1;
  945. }
  946. if (avctx->channels != 1) {
  947. av_log(avctx, AV_LOG_ERROR, "Only mono supported\n");
  948. return AVERROR(EINVAL);
  949. }
  950. if (avctx->bit_rate == 6300) {
  951. p->cur_rate = Rate6k3;
  952. } else if (avctx->bit_rate == 5300) {
  953. av_log(avctx, AV_LOG_ERROR, "Bitrate not supported yet, use 6.3k\n");
  954. return AVERROR_PATCHWELCOME;
  955. } else {
  956. av_log(avctx, AV_LOG_ERROR,
  957. "Bitrate not supported, use 6.3k\n");
  958. return AVERROR(EINVAL);
  959. }
  960. avctx->frame_size = 240;
  961. memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(int16_t));
  962. return 0;
  963. }
  964. /**
  965. * Remove DC component from the input signal.
  966. *
  967. * @param buf input signal
  968. * @param fir zero memory
  969. * @param iir pole memory
  970. */
  971. static void highpass_filter(int16_t *buf, int16_t *fir, int *iir)
  972. {
  973. int i;
  974. for (i = 0; i < FRAME_LEN; i++) {
  975. *iir = (buf[i] << 15) + ((-*fir) << 15) + MULL2(*iir, 0x7f00);
  976. *fir = buf[i];
  977. buf[i] = av_clipl_int32((int64_t)*iir + (1 << 15)) >> 16;
  978. }
  979. }
  980. /**
  981. * Estimate autocorrelation of the input vector.
  982. *
  983. * @param buf input buffer
  984. * @param autocorr autocorrelation coefficients vector
  985. */
  986. static void comp_autocorr(int16_t *buf, int16_t *autocorr)
  987. {
  988. int i, scale, temp;
  989. int16_t vector[LPC_FRAME];
  990. memcpy(vector, buf, LPC_FRAME * sizeof(int16_t));
  991. scale_vector(vector, LPC_FRAME);
  992. /* Apply the Hamming window */
  993. for (i = 0; i < LPC_FRAME; i++)
  994. vector[i] = (vector[i] * hamming_window[i] + (1 << 14)) >> 15;
  995. /* Compute the first autocorrelation coefficient */
  996. temp = dot_product(vector, vector, LPC_FRAME, 0);
  997. /* Apply a white noise correlation factor of (1025/1024) */
  998. temp += temp >> 10;
  999. /* Normalize */
  1000. scale = normalize_bits_int32(temp);
  1001. autocorr[0] = av_clipl_int32((int64_t)(temp << scale) +
  1002. (1 << 15)) >> 16;
  1003. /* Compute the remaining coefficients */
  1004. if (!autocorr[0]) {
  1005. memset(autocorr + 1, 0, LPC_ORDER * sizeof(int16_t));
  1006. } else {
  1007. for (i = 1; i <= LPC_ORDER; i++) {
  1008. temp = dot_product(vector, vector + i, LPC_FRAME - i, 0);
  1009. temp = MULL2((temp << scale), binomial_window[i - 1]);
  1010. autocorr[i] = av_clipl_int32((int64_t)temp + (1 << 15)) >> 16;
  1011. }
  1012. }
  1013. }
  1014. /**
  1015. * Use Levinson-Durbin recursion to compute LPC coefficients from
  1016. * autocorrelation values.
  1017. *
  1018. * @param lpc LPC coefficients vector
  1019. * @param autocorr autocorrelation coefficients vector
  1020. * @param error prediction error
  1021. */
  1022. static void levinson_durbin(int16_t *lpc, int16_t *autocorr, int16_t error)
  1023. {
  1024. int16_t vector[LPC_ORDER];
  1025. int16_t partial_corr;
  1026. int i, j, temp;
  1027. memset(lpc, 0, LPC_ORDER * sizeof(int16_t));
  1028. for (i = 0; i < LPC_ORDER; i++) {
  1029. /* Compute the partial correlation coefficient */
  1030. temp = 0;
  1031. for (j = 0; j < i; j++)
  1032. temp -= lpc[j] * autocorr[i - j - 1];
  1033. temp = ((autocorr[i] << 13) + temp) << 3;
  1034. if (FFABS(temp) >= (error << 16))
  1035. break;
  1036. partial_corr = temp / (error << 1);
  1037. lpc[i] = av_clipl_int32((int64_t)(partial_corr << 14) +
  1038. (1 << 15)) >> 16;
  1039. /* Update the prediction error */
  1040. temp = MULL2(temp, partial_corr);
  1041. error = av_clipl_int32((int64_t)(error << 16) - temp +
  1042. (1 << 15)) >> 16;
  1043. memcpy(vector, lpc, i * sizeof(int16_t));
  1044. for (j = 0; j < i; j++) {
  1045. temp = partial_corr * vector[i - j - 1] << 1;
  1046. lpc[j] = av_clipl_int32((int64_t)(lpc[j] << 16) - temp +
  1047. (1 << 15)) >> 16;
  1048. }
  1049. }
  1050. }
  1051. /**
  1052. * Calculate LPC coefficients for the current frame.
  1053. *
  1054. * @param buf current frame
  1055. * @param prev_data 2 trailing subframes of the previous frame
  1056. * @param lpc LPC coefficients vector
  1057. */
  1058. static void comp_lpc_coeff(int16_t *buf, int16_t *lpc)
  1059. {
  1060. int16_t autocorr[(LPC_ORDER + 1) * SUBFRAMES];
  1061. int16_t *autocorr_ptr = autocorr;
  1062. int16_t *lpc_ptr = lpc;
  1063. int i, j;
  1064. for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
  1065. comp_autocorr(buf + i, autocorr_ptr);
  1066. levinson_durbin(lpc_ptr, autocorr_ptr + 1, autocorr_ptr[0]);
  1067. lpc_ptr += LPC_ORDER;
  1068. autocorr_ptr += LPC_ORDER + 1;
  1069. }
  1070. }
  1071. static void lpc2lsp(int16_t *lpc, int16_t *prev_lsp, int16_t *lsp)
  1072. {
  1073. int f[LPC_ORDER + 2]; ///< coefficients of the sum and difference
  1074. ///< polynomials (F1, F2) ordered as
  1075. ///< f1[0], f2[0], ...., f1[5], f2[5]
  1076. int max, shift, cur_val, prev_val, count, p;
  1077. int i, j;
  1078. int64_t temp;
  1079. /* Initialize f1[0] and f2[0] to 1 in Q25 */
  1080. for (i = 0; i < LPC_ORDER; i++)
  1081. lsp[i] = (lpc[i] * bandwidth_expand[i] + (1 << 14)) >> 15;
  1082. /* Apply bandwidth expansion on the LPC coefficients */
  1083. f[0] = f[1] = 1 << 25;
  1084. /* Compute the remaining coefficients */
  1085. for (i = 0; i < LPC_ORDER / 2; i++) {
  1086. /* f1 */
  1087. f[2 * i + 2] = -f[2 * i] - ((lsp[i] + lsp[LPC_ORDER - 1 - i]) << 12);
  1088. /* f2 */
  1089. f[2 * i + 3] = f[2 * i + 1] - ((lsp[i] - lsp[LPC_ORDER - 1 - i]) << 12);
  1090. }
  1091. /* Divide f1[5] and f2[5] by 2 for use in polynomial evaluation */
  1092. f[LPC_ORDER] >>= 1;
  1093. f[LPC_ORDER + 1] >>= 1;
  1094. /* Normalize and shorten */
  1095. max = FFABS(f[0]);
  1096. for (i = 1; i < LPC_ORDER + 2; i++)
  1097. max = FFMAX(max, FFABS(f[i]));
  1098. shift = normalize_bits_int32(max);
  1099. for (i = 0; i < LPC_ORDER + 2; i++)
  1100. f[i] = av_clipl_int32((int64_t)(f[i] << shift) + (1 << 15)) >> 16;
  1101. /**
  1102. * Evaluate F1 and F2 at uniform intervals of pi/256 along the
  1103. * unit circle and check for zero crossings.
  1104. */
  1105. p = 0;
  1106. temp = 0;
  1107. for (i = 0; i <= LPC_ORDER / 2; i++)
  1108. temp += f[2 * i] * cos_tab[0];
  1109. prev_val = av_clipl_int32(temp << 1);
  1110. count = 0;
  1111. for ( i = 1; i < COS_TBL_SIZE / 2; i++) {
  1112. /* Evaluate */
  1113. temp = 0;
  1114. for (j = 0; j <= LPC_ORDER / 2; j++)
  1115. temp += f[LPC_ORDER - 2 * j + p] * cos_tab[i * j % COS_TBL_SIZE];
  1116. cur_val = av_clipl_int32(temp << 1);
  1117. /* Check for sign change, indicating a zero crossing */
  1118. if ((cur_val ^ prev_val) < 0) {
  1119. int abs_cur = FFABS(cur_val);
  1120. int abs_prev = FFABS(prev_val);
  1121. int sum = abs_cur + abs_prev;
  1122. shift = normalize_bits_int32(sum);
  1123. sum <<= shift;
  1124. abs_prev = abs_prev << shift >> 8;
  1125. lsp[count++] = ((i - 1) << 7) + (abs_prev >> 1) / (sum >> 16);
  1126. if (count == LPC_ORDER)
  1127. break;
  1128. /* Switch between sum and difference polynomials */
  1129. p ^= 1;
  1130. /* Evaluate */
  1131. temp = 0;
  1132. for (j = 0; j <= LPC_ORDER / 2; j++){
  1133. temp += f[LPC_ORDER - 2 * j + p] *
  1134. cos_tab[i * j % COS_TBL_SIZE];
  1135. }
  1136. cur_val = av_clipl_int32(temp<<1);
  1137. }
  1138. prev_val = cur_val;
  1139. }
  1140. if (count != LPC_ORDER)
  1141. memcpy(lsp, prev_lsp, LPC_ORDER * sizeof(int16_t));
  1142. }
  1143. /**
  1144. * Quantize the current LSP subvector.
  1145. *
  1146. * @param num band number
  1147. * @param offset offset of the current subvector in an LPC_ORDER vector
  1148. * @param size size of the current subvector
  1149. */
  1150. #define get_index(num, offset, size) \
  1151. {\
  1152. int error, max = -1;\
  1153. int16_t temp[4];\
  1154. int i, j;\
  1155. for (i = 0; i < LSP_CB_SIZE; i++) {\
  1156. for (j = 0; j < size; j++){\
  1157. temp[j] = (weight[j + (offset)] * lsp_band##num[i][j] +\
  1158. (1 << 14)) >> 15;\
  1159. }\
  1160. error = dot_product(lsp + (offset), temp, size, 1) << 1;\
  1161. error -= dot_product(lsp_band##num[i], temp, size, 1);\
  1162. if (error > max) {\
  1163. max = error;\
  1164. lsp_index[num] = i;\
  1165. }\
  1166. }\
  1167. }
  1168. /**
  1169. * Vector quantize the LSP frequencies.
  1170. *
  1171. * @param lsp the current lsp vector
  1172. * @param prev_lsp the previous lsp vector
  1173. */
  1174. static void lsp_quantize(uint8_t *lsp_index, int16_t *lsp, int16_t *prev_lsp)
  1175. {
  1176. int16_t weight[LPC_ORDER];
  1177. int16_t min, max;
  1178. int shift, i;
  1179. /* Calculate the VQ weighting vector */
  1180. weight[0] = (1 << 20) / (lsp[1] - lsp[0]);
  1181. weight[LPC_ORDER - 1] = (1 << 20) /
  1182. (lsp[LPC_ORDER - 1] - lsp[LPC_ORDER - 2]);
  1183. for (i = 1; i < LPC_ORDER - 1; i++) {
  1184. min = FFMIN(lsp[i] - lsp[i - 1], lsp[i + 1] - lsp[i]);
  1185. if (min > 0x20)
  1186. weight[i] = (1 << 20) / min;
  1187. else
  1188. weight[i] = INT16_MAX;
  1189. }
  1190. /* Normalize */
  1191. max = 0;
  1192. for (i = 0; i < LPC_ORDER; i++)
  1193. max = FFMAX(weight[i], max);
  1194. shift = normalize_bits_int16(max);
  1195. for (i = 0; i < LPC_ORDER; i++) {
  1196. weight[i] <<= shift;
  1197. }
  1198. /* Compute the VQ target vector */
  1199. for (i = 0; i < LPC_ORDER; i++) {
  1200. lsp[i] -= dc_lsp[i] +
  1201. (((prev_lsp[i] - dc_lsp[i]) * 12288 + (1 << 14)) >> 15);
  1202. }
  1203. get_index(0, 0, 3);
  1204. get_index(1, 3, 3);
  1205. get_index(2, 6, 4);
  1206. }
  1207. /**
  1208. * Apply the formant perceptual weighting filter.
  1209. *
  1210. * @param flt_coef filter coefficients
  1211. * @param unq_lpc unquantized lpc vector
  1212. */
  1213. static void perceptual_filter(G723_1_Context *p, int16_t *flt_coef,
  1214. int16_t *unq_lpc, int16_t *buf)
  1215. {
  1216. int16_t vector[FRAME_LEN + LPC_ORDER];
  1217. int i, j, k, l = 0;
  1218. memcpy(buf, p->iir_mem, sizeof(int16_t) * LPC_ORDER);
  1219. memcpy(vector, p->fir_mem, sizeof(int16_t) * LPC_ORDER);
  1220. memcpy(vector + LPC_ORDER, buf + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
  1221. for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
  1222. for (k = 0; k < LPC_ORDER; k++) {
  1223. flt_coef[k + 2 * l] = (unq_lpc[k + l] * percept_flt_tbl[0][k] +
  1224. (1 << 14)) >> 15;
  1225. flt_coef[k + 2 * l + LPC_ORDER] = (unq_lpc[k + l] *
  1226. percept_flt_tbl[1][k] +
  1227. (1 << 14)) >> 15;
  1228. }
  1229. iir_filter(flt_coef + 2 * l, flt_coef + 2 * l + LPC_ORDER, vector + i,
  1230. buf + i, 0);
  1231. l += LPC_ORDER;
  1232. }
  1233. memcpy(p->iir_mem, buf + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
  1234. memcpy(p->fir_mem, vector + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
  1235. }
  1236. /**
  1237. * Estimate the open loop pitch period.
  1238. *
  1239. * @param buf perceptually weighted speech
  1240. * @param start estimation is carried out from this position
  1241. */
  1242. static int estimate_pitch(int16_t *buf, int start)
  1243. {
  1244. int max_exp = 32;
  1245. int max_ccr = 0x4000;
  1246. int max_eng = 0x7fff;
  1247. int index = PITCH_MIN;
  1248. int offset = start - PITCH_MIN + 1;
  1249. int ccr, eng, orig_eng, ccr_eng, exp;
  1250. int diff, temp;
  1251. int i;
  1252. orig_eng = dot_product(buf + offset, buf + offset, HALF_FRAME_LEN, 0);
  1253. for (i = PITCH_MIN; i <= PITCH_MAX - 3; i++) {
  1254. offset--;
  1255. /* Update energy and compute correlation */
  1256. orig_eng += buf[offset] * buf[offset] -
  1257. buf[offset + HALF_FRAME_LEN] * buf[offset + HALF_FRAME_LEN];
  1258. ccr = dot_product(buf + start, buf + offset, HALF_FRAME_LEN, 0);
  1259. if (ccr <= 0)
  1260. continue;
  1261. /* Split into mantissa and exponent to maintain precision */
  1262. exp = normalize_bits_int32(ccr);
  1263. ccr = av_clipl_int32((int64_t)(ccr << exp) + (1 << 15)) >> 16;
  1264. exp <<= 1;
  1265. ccr *= ccr;
  1266. temp = normalize_bits_int32(ccr);
  1267. ccr = ccr << temp >> 16;
  1268. exp += temp;
  1269. temp = normalize_bits_int32(orig_eng);
  1270. eng = av_clipl_int32((int64_t)(orig_eng << temp) + (1 << 15)) >> 16;
  1271. exp -= temp;
  1272. if (ccr >= eng) {
  1273. exp--;
  1274. ccr >>= 1;
  1275. }
  1276. if (exp > max_exp)
  1277. continue;
  1278. if (exp + 1 < max_exp)
  1279. goto update;
  1280. /* Equalize exponents before comparison */
  1281. if (exp + 1 == max_exp)
  1282. temp = max_ccr >> 1;
  1283. else
  1284. temp = max_ccr;
  1285. ccr_eng = ccr * max_eng;
  1286. diff = ccr_eng - eng * temp;
  1287. if (diff > 0 && (i - index < PITCH_MIN || diff > ccr_eng >> 2)) {
  1288. update:
  1289. index = i;
  1290. max_exp = exp;
  1291. max_ccr = ccr;
  1292. max_eng = eng;
  1293. }
  1294. }
  1295. return index;
  1296. }
  1297. /**
  1298. * Compute harmonic noise filter parameters.
  1299. *
  1300. * @param buf perceptually weighted speech
  1301. * @param pitch_lag open loop pitch period
  1302. * @param hf harmonic filter parameters
  1303. */
  1304. static void comp_harmonic_coeff(int16_t *buf, int16_t pitch_lag, HFParam *hf)
  1305. {
  1306. int ccr, eng, max_ccr, max_eng;
  1307. int exp, max, diff;
  1308. int energy[15];
  1309. int i, j;
  1310. for (i = 0, j = pitch_lag - 3; j <= pitch_lag + 3; i++, j++) {
  1311. /* Compute residual energy */
  1312. energy[i << 1] = dot_product(buf - j, buf - j, SUBFRAME_LEN, 0);
  1313. /* Compute correlation */
  1314. energy[(i << 1) + 1] = dot_product(buf, buf - j, SUBFRAME_LEN, 0);
  1315. }
  1316. /* Compute target energy */
  1317. energy[14] = dot_product(buf, buf, SUBFRAME_LEN, 0);
  1318. /* Normalize */
  1319. max = 0;
  1320. for (i = 0; i < 15; i++)
  1321. max = FFMAX(max, FFABS(energy[i]));
  1322. exp = normalize_bits_int32(max);
  1323. for (i = 0; i < 15; i++) {
  1324. energy[i] = av_clipl_int32((int64_t)(energy[i] << exp) +
  1325. (1 << 15)) >> 16;
  1326. }
  1327. hf->index = -1;
  1328. hf->gain = 0;
  1329. max_ccr = 1;
  1330. max_eng = 0x7fff;
  1331. for (i = 0; i <= 6; i++) {
  1332. eng = energy[i << 1];
  1333. ccr = energy[(i << 1) + 1];
  1334. if (ccr <= 0)
  1335. continue;
  1336. ccr = (ccr * ccr + (1 << 14)) >> 15;
  1337. diff = ccr * max_eng - eng * max_ccr;
  1338. if (diff > 0) {
  1339. max_ccr = ccr;
  1340. max_eng = eng;
  1341. hf->index = i;
  1342. }
  1343. }
  1344. if (hf->index == -1) {
  1345. hf->index = pitch_lag;
  1346. return;
  1347. }
  1348. eng = energy[14] * max_eng;
  1349. eng = (eng >> 2) + (eng >> 3);
  1350. ccr = energy[(hf->index << 1) + 1] * energy[(hf->index << 1) + 1];
  1351. if (eng < ccr) {
  1352. eng = energy[(hf->index << 1) + 1];
  1353. if (eng >= max_eng)
  1354. hf->gain = 0x2800;
  1355. else
  1356. hf->gain = ((eng << 15) / max_eng * 0x2800 + (1 << 14)) >> 15;
  1357. }
  1358. hf->index += pitch_lag - 3;
  1359. }
  1360. /**
  1361. * Apply the harmonic noise shaping filter.
  1362. *
  1363. * @param hf filter parameters
  1364. */
  1365. static void harmonic_filter(HFParam *hf, int16_t *src, int16_t *dest)
  1366. {
  1367. int i;
  1368. for (i = 0; i < SUBFRAME_LEN; i++) {
  1369. int64_t temp = hf->gain * src[i - hf->index] << 1;
  1370. dest[i] = av_clipl_int32((src[i] << 16) - temp + (1 << 15)) >> 16;
  1371. }
  1372. }
  1373. static void harmonic_noise_sub(HFParam *hf, int16_t *src, int16_t *dest)
  1374. {
  1375. int i;
  1376. for (i = 0; i < SUBFRAME_LEN; i++) {
  1377. int64_t temp = hf->gain * src[i - hf->index] << 1;
  1378. dest[i] = av_clipl_int32(((dest[i] - src[i]) << 16) + temp +
  1379. (1 << 15)) >> 16;
  1380. }
  1381. }
  1382. /**
  1383. * Combined synthesis and formant perceptual weighting filer.
  1384. *
  1385. * @param qnt_lpc quantized lpc coefficients
  1386. * @param perf_lpc perceptual filter coefficients
  1387. * @param perf_fir perceptual filter fir memory
  1388. * @param perf_iir perceptual filter iir memory
  1389. * @param scale the filter output will be scaled by 2^scale
  1390. */
  1391. static void synth_percept_filter(int16_t *qnt_lpc, int16_t *perf_lpc,
  1392. int16_t *perf_fir, int16_t *perf_iir,
  1393. int16_t *src, int16_t *dest, int scale)
  1394. {
  1395. int i, j;
  1396. int16_t buf_16[SUBFRAME_LEN + LPC_ORDER];
  1397. int64_t buf[SUBFRAME_LEN];
  1398. int16_t *bptr_16 = buf_16 + LPC_ORDER;
  1399. memcpy(buf_16, perf_fir, sizeof(int16_t) * LPC_ORDER);
  1400. memcpy(dest - LPC_ORDER, perf_iir, sizeof(int16_t) * LPC_ORDER);
  1401. for (i = 0; i < SUBFRAME_LEN; i++) {
  1402. int64_t temp = 0;
  1403. for (j = 1; j <= LPC_ORDER; j++)
  1404. temp -= qnt_lpc[j - 1] * bptr_16[i - j];
  1405. buf[i] = (src[i] << 15) + (temp << 3);
  1406. bptr_16[i] = av_clipl_int32(buf[i] + (1 << 15)) >> 16;
  1407. }
  1408. for (i = 0; i < SUBFRAME_LEN; i++) {
  1409. int64_t fir = 0, iir = 0;
  1410. for (j = 1; j <= LPC_ORDER; j++) {
  1411. fir -= perf_lpc[j - 1] * bptr_16[i - j];
  1412. iir += perf_lpc[j + LPC_ORDER - 1] * dest[i - j];
  1413. }
  1414. dest[i] = av_clipl_int32(((buf[i] + (fir << 3)) << scale) + (iir << 3) +
  1415. (1 << 15)) >> 16;
  1416. }
  1417. memcpy(perf_fir, buf_16 + SUBFRAME_LEN, sizeof(int16_t) * LPC_ORDER);
  1418. memcpy(perf_iir, dest + SUBFRAME_LEN - LPC_ORDER,
  1419. sizeof(int16_t) * LPC_ORDER);
  1420. }
  1421. /**
  1422. * Compute the adaptive codebook contribution.
  1423. *
  1424. * @param buf input signal
  1425. * @param index the current subframe index
  1426. */
  1427. static void acb_search(G723_1_Context *p, int16_t *residual,
  1428. int16_t *impulse_resp, int16_t *buf,
  1429. int index)
  1430. {
  1431. int16_t flt_buf[PITCH_ORDER][SUBFRAME_LEN];
  1432. const int16_t *cb_tbl = adaptive_cb_gain85;
  1433. int ccr_buf[PITCH_ORDER * SUBFRAMES << 2];
  1434. int pitch_lag = p->pitch_lag[index >> 1];
  1435. int acb_lag = 1;
  1436. int acb_gain = 0;
  1437. int odd_frame = index & 1;
  1438. int iter = 3 + odd_frame;
  1439. int count = 0;
  1440. int tbl_size = 85;
  1441. int i, j, k, l, max;
  1442. int64_t temp;
  1443. if (!odd_frame) {
  1444. if (pitch_lag == PITCH_MIN)
  1445. pitch_lag++;
  1446. else
  1447. pitch_lag = FFMIN(pitch_lag, PITCH_MAX - 5);
  1448. }
  1449. for (i = 0; i < iter; i++) {
  1450. get_residual(residual, p->prev_excitation, pitch_lag + i - 1);
  1451. for (j = 0; j < SUBFRAME_LEN; j++) {
  1452. temp = 0;
  1453. for (k = 0; k <= j; k++)
  1454. temp += residual[PITCH_ORDER - 1 + k] * impulse_resp[j - k];
  1455. flt_buf[PITCH_ORDER - 1][j] = av_clipl_int32((temp << 1) +
  1456. (1 << 15)) >> 16;
  1457. }
  1458. for (j = PITCH_ORDER - 2; j >= 0; j--) {
  1459. flt_buf[j][0] = ((residual[j] << 13) + (1 << 14)) >> 15;
  1460. for (k = 1; k < SUBFRAME_LEN; k++) {
  1461. temp = (flt_buf[j + 1][k - 1] << 15) +
  1462. residual[j] * impulse_resp[k];
  1463. flt_buf[j][k] = av_clipl_int32((temp << 1) + (1 << 15)) >> 16;
  1464. }
  1465. }
  1466. /* Compute crosscorrelation with the signal */
  1467. for (j = 0; j < PITCH_ORDER; j++) {
  1468. temp = dot_product(buf, flt_buf[j], SUBFRAME_LEN, 0);
  1469. ccr_buf[count++] = av_clipl_int32(temp << 1);
  1470. }
  1471. /* Compute energies */
  1472. for (j = 0; j < PITCH_ORDER; j++) {
  1473. ccr_buf[count++] = dot_product(flt_buf[j], flt_buf[j],
  1474. SUBFRAME_LEN, 1);
  1475. }
  1476. for (j = 1; j < PITCH_ORDER; j++) {
  1477. for (k = 0; k < j; k++) {
  1478. temp = dot_product(flt_buf[j], flt_buf[k], SUBFRAME_LEN, 0);
  1479. ccr_buf[count++] = av_clipl_int32(temp<<2);
  1480. }
  1481. }
  1482. }
  1483. /* Normalize and shorten */
  1484. max = 0;
  1485. for (i = 0; i < 20 * iter; i++)
  1486. max = FFMAX(max, FFABS(ccr_buf[i]));
  1487. temp = normalize_bits_int32(max);
  1488. for (i = 0; i < 20 * iter; i++){
  1489. ccr_buf[i] = av_clipl_int32((int64_t)(ccr_buf[i] << temp) +
  1490. (1 << 15)) >> 16;
  1491. }
  1492. max = 0;
  1493. for (i = 0; i < iter; i++) {
  1494. /* Select quantization table */
  1495. if (!odd_frame && pitch_lag + i - 1 >= SUBFRAME_LEN - 2 ||
  1496. odd_frame && pitch_lag >= SUBFRAME_LEN - 2) {
  1497. cb_tbl = adaptive_cb_gain170;
  1498. tbl_size = 170;
  1499. }
  1500. for (j = 0, k = 0; j < tbl_size; j++, k += 20) {
  1501. temp = 0;
  1502. for (l = 0; l < 20; l++)
  1503. temp += ccr_buf[20 * i + l] * cb_tbl[k + l];
  1504. temp = av_clipl_int32(temp);
  1505. if (temp > max) {
  1506. max = temp;
  1507. acb_gain = j;
  1508. acb_lag = i;
  1509. }
  1510. }
  1511. }
  1512. if (!odd_frame) {
  1513. pitch_lag += acb_lag - 1;
  1514. acb_lag = 1;
  1515. }
  1516. p->pitch_lag[index >> 1] = pitch_lag;
  1517. p->subframe[index].ad_cb_lag = acb_lag;
  1518. p->subframe[index].ad_cb_gain = acb_gain;
  1519. }
  1520. /**
  1521. * Subtract the adaptive codebook contribution from the input
  1522. * to obtain the residual.
  1523. *
  1524. * @param buf target vector
  1525. */
  1526. static void sub_acb_contrib(int16_t *residual, int16_t *impulse_resp,
  1527. int16_t *buf)
  1528. {
  1529. int i, j;
  1530. /* Subtract adaptive CB contribution to obtain the residual */
  1531. for (i = 0; i < SUBFRAME_LEN; i++) {
  1532. int64_t temp = buf[i] << 14;
  1533. for (j = 0; j <= i; j++)
  1534. temp -= residual[j] * impulse_resp[i - j];
  1535. buf[i] = av_clipl_int32((temp << 2) + (1 << 15)) >> 16;
  1536. }
  1537. }
  1538. /**
  1539. * Quantize the residual signal using the fixed codebook (MP-MLQ).
  1540. *
  1541. * @param optim optimized fixed codebook parameters
  1542. * @param buf excitation vector
  1543. */
  1544. static void get_fcb_param(FCBParam *optim, int16_t *impulse_resp,
  1545. int16_t *buf, int pulse_cnt, int pitch_lag)
  1546. {
  1547. FCBParam param;
  1548. int16_t impulse_r[SUBFRAME_LEN];
  1549. int16_t temp_corr[SUBFRAME_LEN];
  1550. int16_t impulse_corr[SUBFRAME_LEN];
  1551. int ccr1[SUBFRAME_LEN];
  1552. int ccr2[SUBFRAME_LEN];
  1553. int amp, err, max, max_amp_index, min, scale, i, j, k, l;
  1554. int64_t temp;
  1555. /* Update impulse response */
  1556. memcpy(impulse_r, impulse_resp, sizeof(int16_t) * SUBFRAME_LEN);
  1557. param.dirac_train = 0;
  1558. if (pitch_lag < SUBFRAME_LEN - 2) {
  1559. param.dirac_train = 1;
  1560. gen_dirac_train(impulse_r, pitch_lag);
  1561. }
  1562. for (i = 0; i < SUBFRAME_LEN; i++)
  1563. temp_corr[i] = impulse_r[i] >> 1;
  1564. /* Compute impulse response autocorrelation */
  1565. temp = dot_product(temp_corr, temp_corr, SUBFRAME_LEN, 1);
  1566. scale = normalize_bits_int32(temp);
  1567. impulse_corr[0] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
  1568. for (i = 1; i < SUBFRAME_LEN; i++) {
  1569. temp = dot_product(temp_corr + i, temp_corr, SUBFRAME_LEN - i, 1);
  1570. impulse_corr[i] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
  1571. }
  1572. /* Compute crosscorrelation of impulse response with residual signal */
  1573. scale -= 4;
  1574. for (i = 0; i < SUBFRAME_LEN; i++){
  1575. temp = dot_product(buf + i, impulse_r, SUBFRAME_LEN - i, 1);
  1576. if (scale < 0)
  1577. ccr1[i] = temp >> -scale;
  1578. else
  1579. ccr1[i] = av_clipl_int32(temp << scale);
  1580. }
  1581. /* Search loop */
  1582. for (i = 0; i < GRID_SIZE; i++) {
  1583. /* Maximize the crosscorrelation */
  1584. max = 0;
  1585. for (j = i; j < SUBFRAME_LEN; j += GRID_SIZE) {
  1586. temp = FFABS(ccr1[j]);
  1587. if (temp >= max) {
  1588. max = temp;
  1589. param.pulse_pos[0] = j;
  1590. }
  1591. }
  1592. /* Quantize the gain (max crosscorrelation/impulse_corr[0]) */
  1593. amp = max;
  1594. min = 1 << 30;
  1595. max_amp_index = GAIN_LEVELS - 2;
  1596. for (j = max_amp_index; j >= 2; j--) {
  1597. temp = av_clipl_int32((int64_t)fixed_cb_gain[j] *
  1598. impulse_corr[0] << 1);
  1599. temp = FFABS(temp - amp);
  1600. if (temp < min) {
  1601. min = temp;
  1602. max_amp_index = j;
  1603. }
  1604. }
  1605. max_amp_index--;
  1606. /* Select additional gain values */
  1607. for (j = 1; j < 5; j++) {
  1608. for (k = i; k < SUBFRAME_LEN; k += GRID_SIZE) {
  1609. temp_corr[k] = 0;
  1610. ccr2[k] = ccr1[k];
  1611. }
  1612. param.amp_index = max_amp_index + j - 2;
  1613. amp = fixed_cb_gain[param.amp_index];
  1614. param.pulse_sign[0] = (ccr2[param.pulse_pos[0]] < 0) ? -amp : amp;
  1615. temp_corr[param.pulse_pos[0]] = 1;
  1616. for (k = 1; k < pulse_cnt; k++) {
  1617. max = -1 << 30;
  1618. for (l = i; l < SUBFRAME_LEN; l += GRID_SIZE) {
  1619. if (temp_corr[l])
  1620. continue;
  1621. temp = impulse_corr[FFABS(l - param.pulse_pos[k - 1])];
  1622. temp = av_clipl_int32((int64_t)temp *
  1623. param.pulse_sign[k - 1] << 1);
  1624. ccr2[l] -= temp;
  1625. temp = FFABS(ccr2[l]);
  1626. if (temp > max) {
  1627. max = temp;
  1628. param.pulse_pos[k] = l;
  1629. }
  1630. }
  1631. param.pulse_sign[k] = (ccr2[param.pulse_pos[k]] < 0) ?
  1632. -amp : amp;
  1633. temp_corr[param.pulse_pos[k]] = 1;
  1634. }
  1635. /* Create the error vector */
  1636. memset(temp_corr, 0, sizeof(int16_t) * SUBFRAME_LEN);
  1637. for (k = 0; k < pulse_cnt; k++)
  1638. temp_corr[param.pulse_pos[k]] = param.pulse_sign[k];
  1639. for (k = SUBFRAME_LEN - 1; k >= 0; k--) {
  1640. temp = 0;
  1641. for (l = 0; l <= k; l++) {
  1642. int prod = av_clipl_int32((int64_t)temp_corr[l] *
  1643. impulse_r[k - l] << 1);
  1644. temp = av_clipl_int32(temp + prod);
  1645. }
  1646. temp_corr[k] = temp << 2 >> 16;
  1647. }
  1648. /* Compute square of error */
  1649. err = 0;
  1650. for (k = 0; k < SUBFRAME_LEN; k++) {
  1651. int64_t prod;
  1652. prod = av_clipl_int32((int64_t)buf[k] * temp_corr[k] << 1);
  1653. err = av_clipl_int32(err - prod);
  1654. prod = av_clipl_int32((int64_t)temp_corr[k] * temp_corr[k]);
  1655. err = av_clipl_int32(err + prod);
  1656. }
  1657. /* Minimize */
  1658. if (err < optim->min_err) {
  1659. optim->min_err = err;
  1660. optim->grid_index = i;
  1661. optim->amp_index = param.amp_index;
  1662. optim->dirac_train = param.dirac_train;
  1663. for (k = 0; k < pulse_cnt; k++) {
  1664. optim->pulse_sign[k] = param.pulse_sign[k];
  1665. optim->pulse_pos[k] = param.pulse_pos[k];
  1666. }
  1667. }
  1668. }
  1669. }
  1670. }
  1671. /**
  1672. * Encode the pulse position and gain of the current subframe.
  1673. *
  1674. * @param optim optimized fixed CB parameters
  1675. * @param buf excitation vector
  1676. */
  1677. static void pack_fcb_param(G723_1_Subframe *subfrm, FCBParam *optim,
  1678. int16_t *buf, int pulse_cnt)
  1679. {
  1680. int i, j;
  1681. j = PULSE_MAX - pulse_cnt;
  1682. subfrm->pulse_sign = 0;
  1683. subfrm->pulse_pos = 0;
  1684. for (i = 0; i < SUBFRAME_LEN >> 1; i++) {
  1685. int val = buf[optim->grid_index + (i << 1)];
  1686. if (!val) {
  1687. subfrm->pulse_pos += combinatorial_table[j][i];
  1688. } else {
  1689. subfrm->pulse_sign <<= 1;
  1690. if (val < 0) subfrm->pulse_sign++;
  1691. j++;
  1692. if (j == PULSE_MAX) break;
  1693. }
  1694. }
  1695. subfrm->amp_index = optim->amp_index;
  1696. subfrm->grid_index = optim->grid_index;
  1697. subfrm->dirac_train = optim->dirac_train;
  1698. }
  1699. /**
  1700. * Compute the fixed codebook excitation.
  1701. *
  1702. * @param buf target vector
  1703. * @param impulse_resp impulse response of the combined filter
  1704. */
  1705. static void fcb_search(G723_1_Context *p, int16_t *impulse_resp,
  1706. int16_t *buf, int index)
  1707. {
  1708. FCBParam optim;
  1709. int pulse_cnt = pulses[index];
  1710. int i;
  1711. optim.min_err = 1 << 30;
  1712. get_fcb_param(&optim, impulse_resp, buf, pulse_cnt, SUBFRAME_LEN);
  1713. if (p->pitch_lag[index >> 1] < SUBFRAME_LEN - 2) {
  1714. get_fcb_param(&optim, impulse_resp, buf, pulse_cnt,
  1715. p->pitch_lag[index >> 1]);
  1716. }
  1717. /* Reconstruct the excitation */
  1718. memset(buf, 0, sizeof(int16_t) * SUBFRAME_LEN);
  1719. for (i = 0; i < pulse_cnt; i++)
  1720. buf[optim.pulse_pos[i]] = optim.pulse_sign[i];
  1721. pack_fcb_param(&p->subframe[index], &optim, buf, pulse_cnt);
  1722. if (optim.dirac_train)
  1723. gen_dirac_train(buf, p->pitch_lag[index >> 1]);
  1724. }
  1725. /**
  1726. * Pack the frame parameters into output bitstream.
  1727. *
  1728. * @param frame output buffer
  1729. * @param size size of the buffer
  1730. */
  1731. static int pack_bitstream(G723_1_Context *p, unsigned char *frame, int size)
  1732. {
  1733. PutBitContext pb;
  1734. int info_bits, i, temp;
  1735. init_put_bits(&pb, frame, size);
  1736. if (p->cur_rate == Rate6k3) {
  1737. info_bits = 0;
  1738. put_bits(&pb, 2, info_bits);
  1739. }
  1740. put_bits(&pb, 8, p->lsp_index[2]);
  1741. put_bits(&pb, 8, p->lsp_index[1]);
  1742. put_bits(&pb, 8, p->lsp_index[0]);
  1743. put_bits(&pb, 7, p->pitch_lag[0] - PITCH_MIN);
  1744. put_bits(&pb, 2, p->subframe[1].ad_cb_lag);
  1745. put_bits(&pb, 7, p->pitch_lag[1] - PITCH_MIN);
  1746. put_bits(&pb, 2, p->subframe[3].ad_cb_lag);
  1747. /* Write 12 bit combined gain */
  1748. for (i = 0; i < SUBFRAMES; i++) {
  1749. temp = p->subframe[i].ad_cb_gain * GAIN_LEVELS +
  1750. p->subframe[i].amp_index;
  1751. if (p->cur_rate == Rate6k3)
  1752. temp += p->subframe[i].dirac_train << 11;
  1753. put_bits(&pb, 12, temp);
  1754. }
  1755. put_bits(&pb, 1, p->subframe[0].grid_index);
  1756. put_bits(&pb, 1, p->subframe[1].grid_index);
  1757. put_bits(&pb, 1, p->subframe[2].grid_index);
  1758. put_bits(&pb, 1, p->subframe[3].grid_index);
  1759. if (p->cur_rate == Rate6k3) {
  1760. skip_put_bits(&pb, 1); /* reserved bit */
  1761. /* Write 13 bit combined position index */
  1762. temp = (p->subframe[0].pulse_pos >> 16) * 810 +
  1763. (p->subframe[1].pulse_pos >> 14) * 90 +
  1764. (p->subframe[2].pulse_pos >> 16) * 9 +
  1765. (p->subframe[3].pulse_pos >> 14);
  1766. put_bits(&pb, 13, temp);
  1767. put_bits(&pb, 16, p->subframe[0].pulse_pos & 0xffff);
  1768. put_bits(&pb, 14, p->subframe[1].pulse_pos & 0x3fff);
  1769. put_bits(&pb, 16, p->subframe[2].pulse_pos & 0xffff);
  1770. put_bits(&pb, 14, p->subframe[3].pulse_pos & 0x3fff);
  1771. put_bits(&pb, 6, p->subframe[0].pulse_sign);
  1772. put_bits(&pb, 5, p->subframe[1].pulse_sign);
  1773. put_bits(&pb, 6, p->subframe[2].pulse_sign);
  1774. put_bits(&pb, 5, p->subframe[3].pulse_sign);
  1775. }
  1776. flush_put_bits(&pb);
  1777. return frame_size[info_bits];
  1778. }
  1779. static int g723_1_encode_frame(AVCodecContext *avctx, unsigned char *buf,
  1780. int buf_size, void *data)
  1781. {
  1782. G723_1_Context *p = avctx->priv_data;
  1783. int16_t unq_lpc[LPC_ORDER * SUBFRAMES];
  1784. int16_t qnt_lpc[LPC_ORDER * SUBFRAMES];
  1785. int16_t cur_lsp[LPC_ORDER];
  1786. int16_t weighted_lpc[LPC_ORDER * SUBFRAMES << 1];
  1787. int16_t vector[FRAME_LEN + PITCH_MAX];
  1788. int offset;
  1789. int16_t *in = data;
  1790. HFParam hf[4];
  1791. int i, j;
  1792. highpass_filter(in, &p->hpf_fir_mem, &p->hpf_iir_mem);
  1793. memcpy(vector, p->prev_data, HALF_FRAME_LEN * sizeof(int16_t));
  1794. memcpy(vector + HALF_FRAME_LEN, in, FRAME_LEN * sizeof(int16_t));
  1795. comp_lpc_coeff(vector, unq_lpc);
  1796. lpc2lsp(&unq_lpc[LPC_ORDER * 3], p->prev_lsp, cur_lsp);
  1797. lsp_quantize(p->lsp_index, cur_lsp, p->prev_lsp);
  1798. /* Update memory */
  1799. memcpy(vector + LPC_ORDER, p->prev_data + SUBFRAME_LEN,
  1800. sizeof(int16_t) * SUBFRAME_LEN);
  1801. memcpy(vector + LPC_ORDER + SUBFRAME_LEN, in,
  1802. sizeof(int16_t) * (HALF_FRAME_LEN + SUBFRAME_LEN));
  1803. memcpy(p->prev_data, in + HALF_FRAME_LEN,
  1804. sizeof(int16_t) * HALF_FRAME_LEN);
  1805. memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
  1806. perceptual_filter(p, weighted_lpc, unq_lpc, vector);
  1807. memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
  1808. memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
  1809. memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
  1810. scale_vector(vector, FRAME_LEN + PITCH_MAX);
  1811. p->pitch_lag[0] = estimate_pitch(vector, PITCH_MAX);
  1812. p->pitch_lag[1] = estimate_pitch(vector, PITCH_MAX + HALF_FRAME_LEN);
  1813. for (i = PITCH_MAX, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
  1814. comp_harmonic_coeff(vector + i, p->pitch_lag[j >> 1], hf + j);
  1815. memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
  1816. memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
  1817. memcpy(p->prev_weight_sig, vector + FRAME_LEN, sizeof(int16_t) * PITCH_MAX);
  1818. for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
  1819. harmonic_filter(hf + j, vector + PITCH_MAX + i, in + i);
  1820. inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, 0);
  1821. lsp_interpolate(qnt_lpc, cur_lsp, p->prev_lsp);
  1822. memcpy(p->prev_lsp, cur_lsp, sizeof(int16_t) * LPC_ORDER);
  1823. offset = 0;
  1824. for (i = 0; i < SUBFRAMES; i++) {
  1825. int16_t impulse_resp[SUBFRAME_LEN];
  1826. int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
  1827. int16_t flt_in[SUBFRAME_LEN];
  1828. int16_t zero[LPC_ORDER], fir[LPC_ORDER], iir[LPC_ORDER];
  1829. /**
  1830. * Compute the combined impulse response of the synthesis filter,
  1831. * formant perceptual weighting filter and harmonic noise shaping filter
  1832. */
  1833. memset(zero, 0, sizeof(int16_t) * LPC_ORDER);
  1834. memset(vector, 0, sizeof(int16_t) * PITCH_MAX);
  1835. memset(flt_in, 0, sizeof(int16_t) * SUBFRAME_LEN);
  1836. flt_in[0] = 1 << 13; /* Unit impulse */
  1837. synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
  1838. zero, zero, flt_in, vector + PITCH_MAX, 1);
  1839. harmonic_filter(hf + i, vector + PITCH_MAX, impulse_resp);
  1840. /* Compute the combined zero input response */
  1841. flt_in[0] = 0;
  1842. memcpy(fir, p->perf_fir_mem, sizeof(int16_t) * LPC_ORDER);
  1843. memcpy(iir, p->perf_iir_mem, sizeof(int16_t) * LPC_ORDER);
  1844. synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
  1845. fir, iir, flt_in, vector + PITCH_MAX, 0);
  1846. memcpy(vector, p->harmonic_mem, sizeof(int16_t) * PITCH_MAX);
  1847. harmonic_noise_sub(hf + i, vector + PITCH_MAX, in);
  1848. acb_search(p, residual, impulse_resp, in, i);
  1849. gen_acb_excitation(residual, p->prev_excitation,p->pitch_lag[i >> 1],
  1850. p->subframe[i], p->cur_rate);
  1851. sub_acb_contrib(residual, impulse_resp, in);
  1852. fcb_search(p, impulse_resp, in, i);
  1853. /* Reconstruct the excitation */
  1854. gen_acb_excitation(impulse_resp, p->prev_excitation, p->pitch_lag[i >> 1],
  1855. p->subframe[i], Rate6k3);
  1856. memcpy(p->prev_excitation, p->prev_excitation + SUBFRAME_LEN,
  1857. sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
  1858. for (j = 0; j < SUBFRAME_LEN; j++)
  1859. in[j] = av_clip_int16((in[j] << 1) + impulse_resp[j]);
  1860. memcpy(p->prev_excitation + PITCH_MAX - SUBFRAME_LEN, in,
  1861. sizeof(int16_t) * SUBFRAME_LEN);
  1862. /* Update filter memories */
  1863. synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
  1864. p->perf_fir_mem, p->perf_iir_mem,
  1865. in, vector + PITCH_MAX, 0);
  1866. memmove(p->harmonic_mem, p->harmonic_mem + SUBFRAME_LEN,
  1867. sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
  1868. memcpy(p->harmonic_mem + PITCH_MAX - SUBFRAME_LEN, vector + PITCH_MAX,
  1869. sizeof(int16_t) * SUBFRAME_LEN);
  1870. in += SUBFRAME_LEN;
  1871. offset += LPC_ORDER;
  1872. }
  1873. return pack_bitstream(p, buf, buf_size);
  1874. }
  1875. AVCodec ff_g723_1_encoder = {
  1876. .name = "g723_1",
  1877. .type = AVMEDIA_TYPE_AUDIO,
  1878. .id = CODEC_ID_G723_1,
  1879. .priv_data_size = sizeof(G723_1_Context),
  1880. .init = g723_1_encode_init,
  1881. .encode = g723_1_encode_frame,
  1882. .long_name = NULL_IF_CONFIG_SMALL("G.723.1"),
  1883. .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,
  1884. SAMPLE_FMT_NONE},
  1885. };
  1886. #endif