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.

2479 lines
77KB

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