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.

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