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.

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