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.

2481 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. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  1029. return ret;
  1030. }
  1031. out = (int16_t *)frame->data[0];
  1032. if (p->cur_frame_type == ACTIVE_FRAME) {
  1033. if (!bad_frame)
  1034. p->erased_frames = 0;
  1035. else if (p->erased_frames != 3)
  1036. p->erased_frames++;
  1037. inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, bad_frame);
  1038. lsp_interpolate(lpc, cur_lsp, p->prev_lsp);
  1039. /* Save the lsp_vector for the next frame */
  1040. memcpy(p->prev_lsp, cur_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
  1041. /* Generate the excitation for the frame */
  1042. memcpy(p->excitation, p->prev_excitation,
  1043. PITCH_MAX * sizeof(*p->excitation));
  1044. if (!p->erased_frames) {
  1045. int16_t *vector_ptr = p->excitation + PITCH_MAX;
  1046. /* Update interpolation gain memory */
  1047. p->interp_gain = fixed_cb_gain[(p->subframe[2].amp_index +
  1048. p->subframe[3].amp_index) >> 1];
  1049. for (i = 0; i < SUBFRAMES; i++) {
  1050. gen_fcb_excitation(vector_ptr, &p->subframe[i], p->cur_rate,
  1051. p->pitch_lag[i >> 1], i);
  1052. gen_acb_excitation(acb_vector, &p->excitation[SUBFRAME_LEN * i],
  1053. p->pitch_lag[i >> 1], &p->subframe[i],
  1054. p->cur_rate);
  1055. /* Get the total excitation */
  1056. for (j = 0; j < SUBFRAME_LEN; j++) {
  1057. int v = av_clip_int16(vector_ptr[j] << 1);
  1058. vector_ptr[j] = av_clip_int16(v + acb_vector[j]);
  1059. }
  1060. vector_ptr += SUBFRAME_LEN;
  1061. }
  1062. vector_ptr = p->excitation + PITCH_MAX;
  1063. p->interp_index = comp_interp_index(p, p->pitch_lag[1],
  1064. &p->sid_gain, &p->cur_gain);
  1065. /* Peform pitch postfiltering */
  1066. if (p->postfilter) {
  1067. i = PITCH_MAX;
  1068. for (j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
  1069. comp_ppf_coeff(p, i, p->pitch_lag[j >> 1],
  1070. ppf + j, p->cur_rate);
  1071. for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
  1072. ff_acelp_weighted_vector_sum(p->audio + LPC_ORDER + i,
  1073. vector_ptr + i,
  1074. vector_ptr + i + ppf[j].index,
  1075. ppf[j].sc_gain,
  1076. ppf[j].opt_gain,
  1077. 1 << 14, 15, SUBFRAME_LEN);
  1078. } else {
  1079. audio = vector_ptr - LPC_ORDER;
  1080. }
  1081. /* Save the excitation for the next frame */
  1082. memcpy(p->prev_excitation, p->excitation + FRAME_LEN,
  1083. PITCH_MAX * sizeof(*p->excitation));
  1084. } else {
  1085. p->interp_gain = (p->interp_gain * 3 + 2) >> 2;
  1086. if (p->erased_frames == 3) {
  1087. /* Mute output */
  1088. memset(p->excitation, 0,
  1089. (FRAME_LEN + PITCH_MAX) * sizeof(*p->excitation));
  1090. memset(p->prev_excitation, 0,
  1091. PITCH_MAX * sizeof(*p->excitation));
  1092. memset(frame->data[0], 0,
  1093. (FRAME_LEN + LPC_ORDER) * sizeof(int16_t));
  1094. } else {
  1095. int16_t *buf = p->audio + LPC_ORDER;
  1096. /* Regenerate frame */
  1097. residual_interp(p->excitation, buf, p->interp_index,
  1098. p->interp_gain, &p->random_seed);
  1099. /* Save the excitation for the next frame */
  1100. memcpy(p->prev_excitation, buf + (FRAME_LEN - PITCH_MAX),
  1101. PITCH_MAX * sizeof(*p->excitation));
  1102. }
  1103. }
  1104. p->cng_random_seed = CNG_RANDOM_SEED;
  1105. } else {
  1106. if (p->cur_frame_type == SID_FRAME) {
  1107. p->sid_gain = sid_gain_to_lsp_index(p->subframe[0].amp_index);
  1108. inverse_quant(p->sid_lsp, p->prev_lsp, p->lsp_index, 0);
  1109. } else if (p->past_frame_type == ACTIVE_FRAME) {
  1110. p->sid_gain = estimate_sid_gain(p);
  1111. }
  1112. if (p->past_frame_type == ACTIVE_FRAME)
  1113. p->cur_gain = p->sid_gain;
  1114. else
  1115. p->cur_gain = (p->cur_gain * 7 + p->sid_gain) >> 3;
  1116. generate_noise(p);
  1117. lsp_interpolate(lpc, p->sid_lsp, p->prev_lsp);
  1118. /* Save the lsp_vector for the next frame */
  1119. memcpy(p->prev_lsp, p->sid_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
  1120. }
  1121. p->past_frame_type = p->cur_frame_type;
  1122. memcpy(p->audio, p->synth_mem, LPC_ORDER * sizeof(*p->audio));
  1123. for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
  1124. ff_celp_lp_synthesis_filter(p->audio + i, &lpc[j * LPC_ORDER],
  1125. audio + i, SUBFRAME_LEN, LPC_ORDER,
  1126. 0, 1, 1 << 12);
  1127. memcpy(p->synth_mem, p->audio + FRAME_LEN, LPC_ORDER * sizeof(*p->audio));
  1128. if (p->postfilter) {
  1129. formant_postfilter(p, lpc, p->audio, out);
  1130. } else { // if output is not postfiltered it should be scaled by 2
  1131. for (i = 0; i < FRAME_LEN; i++)
  1132. out[i] = av_clip_int16(p->audio[LPC_ORDER + i] << 1);
  1133. }
  1134. *got_frame_ptr = 1;
  1135. return frame_size[dec_mode];
  1136. }
  1137. #define OFFSET(x) offsetof(G723_1_Context, x)
  1138. #define AD AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1139. static const AVOption options[] = {
  1140. { "postfilter", "postfilter on/off", OFFSET(postfilter), AV_OPT_TYPE_INT,
  1141. { .i64 = 1 }, 0, 1, AD },
  1142. { NULL }
  1143. };
  1144. static const AVClass g723_1dec_class = {
  1145. .class_name = "G.723.1 decoder",
  1146. .item_name = av_default_item_name,
  1147. .option = options,
  1148. .version = LIBAVUTIL_VERSION_INT,
  1149. };
  1150. AVCodec ff_g723_1_decoder = {
  1151. .name = "g723_1",
  1152. .type = AVMEDIA_TYPE_AUDIO,
  1153. .id = AV_CODEC_ID_G723_1,
  1154. .priv_data_size = sizeof(G723_1_Context),
  1155. .init = g723_1_decode_init,
  1156. .decode = g723_1_decode_frame,
  1157. .long_name = NULL_IF_CONFIG_SMALL("G.723.1"),
  1158. .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
  1159. .priv_class = &g723_1dec_class,
  1160. };
  1161. #if CONFIG_G723_1_ENCODER
  1162. #define BITSTREAM_WRITER_LE
  1163. #include "put_bits.h"
  1164. static av_cold int g723_1_encode_init(AVCodecContext *avctx)
  1165. {
  1166. G723_1_Context *p = avctx->priv_data;
  1167. if (avctx->sample_rate != 8000) {
  1168. av_log(avctx, AV_LOG_ERROR, "Only 8000Hz sample rate supported\n");
  1169. return -1;
  1170. }
  1171. if (avctx->channels != 1) {
  1172. av_log(avctx, AV_LOG_ERROR, "Only mono supported\n");
  1173. return AVERROR(EINVAL);
  1174. }
  1175. if (avctx->bit_rate == 6300) {
  1176. p->cur_rate = RATE_6300;
  1177. } else if (avctx->bit_rate == 5300) {
  1178. av_log(avctx, AV_LOG_ERROR, "Bitrate not supported yet, use 6.3k\n");
  1179. return AVERROR_PATCHWELCOME;
  1180. } else {
  1181. av_log(avctx, AV_LOG_ERROR,
  1182. "Bitrate not supported, use 6.3k\n");
  1183. return AVERROR(EINVAL);
  1184. }
  1185. avctx->frame_size = 240;
  1186. memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(int16_t));
  1187. return 0;
  1188. }
  1189. /**
  1190. * Remove DC component from the input signal.
  1191. *
  1192. * @param buf input signal
  1193. * @param fir zero memory
  1194. * @param iir pole memory
  1195. */
  1196. static void highpass_filter(int16_t *buf, int16_t *fir, int *iir)
  1197. {
  1198. int i;
  1199. for (i = 0; i < FRAME_LEN; i++) {
  1200. *iir = (buf[i] << 15) + ((-*fir) << 15) + MULL2(*iir, 0x7f00);
  1201. *fir = buf[i];
  1202. buf[i] = av_clipl_int32((int64_t)*iir + (1 << 15)) >> 16;
  1203. }
  1204. }
  1205. /**
  1206. * Estimate autocorrelation of the input vector.
  1207. *
  1208. * @param buf input buffer
  1209. * @param autocorr autocorrelation coefficients vector
  1210. */
  1211. static void comp_autocorr(int16_t *buf, int16_t *autocorr)
  1212. {
  1213. int i, scale, temp;
  1214. int16_t vector[LPC_FRAME];
  1215. scale_vector(vector, buf, LPC_FRAME);
  1216. /* Apply the Hamming window */
  1217. for (i = 0; i < LPC_FRAME; i++)
  1218. vector[i] = (vector[i] * hamming_window[i] + (1 << 14)) >> 15;
  1219. /* Compute the first autocorrelation coefficient */
  1220. temp = ff_dot_product(vector, vector, LPC_FRAME);
  1221. /* Apply a white noise correlation factor of (1025/1024) */
  1222. temp += temp >> 10;
  1223. /* Normalize */
  1224. scale = normalize_bits_int32(temp);
  1225. autocorr[0] = av_clipl_int32((int64_t)(temp << scale) +
  1226. (1 << 15)) >> 16;
  1227. /* Compute the remaining coefficients */
  1228. if (!autocorr[0]) {
  1229. memset(autocorr + 1, 0, LPC_ORDER * sizeof(int16_t));
  1230. } else {
  1231. for (i = 1; i <= LPC_ORDER; i++) {
  1232. temp = ff_dot_product(vector, vector + i, LPC_FRAME - i);
  1233. temp = MULL2((temp << scale), binomial_window[i - 1]);
  1234. autocorr[i] = av_clipl_int32((int64_t)temp + (1 << 15)) >> 16;
  1235. }
  1236. }
  1237. }
  1238. /**
  1239. * Use Levinson-Durbin recursion to compute LPC coefficients from
  1240. * autocorrelation values.
  1241. *
  1242. * @param lpc LPC coefficients vector
  1243. * @param autocorr autocorrelation coefficients vector
  1244. * @param error prediction error
  1245. */
  1246. static void levinson_durbin(int16_t *lpc, int16_t *autocorr, int16_t error)
  1247. {
  1248. int16_t vector[LPC_ORDER];
  1249. int16_t partial_corr;
  1250. int i, j, temp;
  1251. memset(lpc, 0, LPC_ORDER * sizeof(int16_t));
  1252. for (i = 0; i < LPC_ORDER; i++) {
  1253. /* Compute the partial correlation coefficient */
  1254. temp = 0;
  1255. for (j = 0; j < i; j++)
  1256. temp -= lpc[j] * autocorr[i - j - 1];
  1257. temp = ((autocorr[i] << 13) + temp) << 3;
  1258. if (FFABS(temp) >= (error << 16))
  1259. break;
  1260. partial_corr = temp / (error << 1);
  1261. lpc[i] = av_clipl_int32((int64_t)(partial_corr << 14) +
  1262. (1 << 15)) >> 16;
  1263. /* Update the prediction error */
  1264. temp = MULL2(temp, partial_corr);
  1265. error = av_clipl_int32((int64_t)(error << 16) - temp +
  1266. (1 << 15)) >> 16;
  1267. memcpy(vector, lpc, i * sizeof(int16_t));
  1268. for (j = 0; j < i; j++) {
  1269. temp = partial_corr * vector[i - j - 1] << 1;
  1270. lpc[j] = av_clipl_int32((int64_t)(lpc[j] << 16) - temp +
  1271. (1 << 15)) >> 16;
  1272. }
  1273. }
  1274. }
  1275. /**
  1276. * Calculate LPC coefficients for the current frame.
  1277. *
  1278. * @param buf current frame
  1279. * @param prev_data 2 trailing subframes of the previous frame
  1280. * @param lpc LPC coefficients vector
  1281. */
  1282. static void comp_lpc_coeff(int16_t *buf, int16_t *lpc)
  1283. {
  1284. int16_t autocorr[(LPC_ORDER + 1) * SUBFRAMES];
  1285. int16_t *autocorr_ptr = autocorr;
  1286. int16_t *lpc_ptr = lpc;
  1287. int i, j;
  1288. for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
  1289. comp_autocorr(buf + i, autocorr_ptr);
  1290. levinson_durbin(lpc_ptr, autocorr_ptr + 1, autocorr_ptr[0]);
  1291. lpc_ptr += LPC_ORDER;
  1292. autocorr_ptr += LPC_ORDER + 1;
  1293. }
  1294. }
  1295. static void lpc2lsp(int16_t *lpc, int16_t *prev_lsp, int16_t *lsp)
  1296. {
  1297. int f[LPC_ORDER + 2]; ///< coefficients of the sum and difference
  1298. ///< polynomials (F1, F2) ordered as
  1299. ///< f1[0], f2[0], ...., f1[5], f2[5]
  1300. int max, shift, cur_val, prev_val, count, p;
  1301. int i, j;
  1302. int64_t temp;
  1303. /* Initialize f1[0] and f2[0] to 1 in Q25 */
  1304. for (i = 0; i < LPC_ORDER; i++)
  1305. lsp[i] = (lpc[i] * bandwidth_expand[i] + (1 << 14)) >> 15;
  1306. /* Apply bandwidth expansion on the LPC coefficients */
  1307. f[0] = f[1] = 1 << 25;
  1308. /* Compute the remaining coefficients */
  1309. for (i = 0; i < LPC_ORDER / 2; i++) {
  1310. /* f1 */
  1311. f[2 * i + 2] = -f[2 * i] - ((lsp[i] + lsp[LPC_ORDER - 1 - i]) << 12);
  1312. /* f2 */
  1313. f[2 * i + 3] = f[2 * i + 1] - ((lsp[i] - lsp[LPC_ORDER - 1 - i]) << 12);
  1314. }
  1315. /* Divide f1[5] and f2[5] by 2 for use in polynomial evaluation */
  1316. f[LPC_ORDER] >>= 1;
  1317. f[LPC_ORDER + 1] >>= 1;
  1318. /* Normalize and shorten */
  1319. max = FFABS(f[0]);
  1320. for (i = 1; i < LPC_ORDER + 2; i++)
  1321. max = FFMAX(max, FFABS(f[i]));
  1322. shift = normalize_bits_int32(max);
  1323. for (i = 0; i < LPC_ORDER + 2; i++)
  1324. f[i] = av_clipl_int32((int64_t)(f[i] << shift) + (1 << 15)) >> 16;
  1325. /**
  1326. * Evaluate F1 and F2 at uniform intervals of pi/256 along the
  1327. * unit circle and check for zero crossings.
  1328. */
  1329. p = 0;
  1330. temp = 0;
  1331. for (i = 0; i <= LPC_ORDER / 2; i++)
  1332. temp += f[2 * i] * cos_tab[0];
  1333. prev_val = av_clipl_int32(temp << 1);
  1334. count = 0;
  1335. for ( i = 1; i < COS_TBL_SIZE / 2; i++) {
  1336. /* Evaluate */
  1337. temp = 0;
  1338. for (j = 0; j <= LPC_ORDER / 2; j++)
  1339. temp += f[LPC_ORDER - 2 * j + p] * cos_tab[i * j % COS_TBL_SIZE];
  1340. cur_val = av_clipl_int32(temp << 1);
  1341. /* Check for sign change, indicating a zero crossing */
  1342. if ((cur_val ^ prev_val) < 0) {
  1343. int abs_cur = FFABS(cur_val);
  1344. int abs_prev = FFABS(prev_val);
  1345. int sum = abs_cur + abs_prev;
  1346. shift = normalize_bits_int32(sum);
  1347. sum <<= shift;
  1348. abs_prev = abs_prev << shift >> 8;
  1349. lsp[count++] = ((i - 1) << 7) + (abs_prev >> 1) / (sum >> 16);
  1350. if (count == LPC_ORDER)
  1351. break;
  1352. /* Switch between sum and difference polynomials */
  1353. p ^= 1;
  1354. /* Evaluate */
  1355. temp = 0;
  1356. for (j = 0; j <= LPC_ORDER / 2; j++){
  1357. temp += f[LPC_ORDER - 2 * j + p] *
  1358. cos_tab[i * j % COS_TBL_SIZE];
  1359. }
  1360. cur_val = av_clipl_int32(temp<<1);
  1361. }
  1362. prev_val = cur_val;
  1363. }
  1364. if (count != LPC_ORDER)
  1365. memcpy(lsp, prev_lsp, LPC_ORDER * sizeof(int16_t));
  1366. }
  1367. /**
  1368. * Quantize the current LSP subvector.
  1369. *
  1370. * @param num band number
  1371. * @param offset offset of the current subvector in an LPC_ORDER vector
  1372. * @param size size of the current subvector
  1373. */
  1374. #define get_index(num, offset, size) \
  1375. {\
  1376. int error, max = -1;\
  1377. int16_t temp[4];\
  1378. int i, j;\
  1379. for (i = 0; i < LSP_CB_SIZE; i++) {\
  1380. for (j = 0; j < size; j++){\
  1381. temp[j] = (weight[j + (offset)] * lsp_band##num[i][j] +\
  1382. (1 << 14)) >> 15;\
  1383. }\
  1384. error = dot_product(lsp + (offset), temp, size) << 1;\
  1385. error -= dot_product(lsp_band##num[i], temp, size);\
  1386. if (error > max) {\
  1387. max = error;\
  1388. lsp_index[num] = i;\
  1389. }\
  1390. }\
  1391. }
  1392. /**
  1393. * Vector quantize the LSP frequencies.
  1394. *
  1395. * @param lsp the current lsp vector
  1396. * @param prev_lsp the previous lsp vector
  1397. */
  1398. static void lsp_quantize(uint8_t *lsp_index, int16_t *lsp, int16_t *prev_lsp)
  1399. {
  1400. int16_t weight[LPC_ORDER];
  1401. int16_t min, max;
  1402. int shift, i;
  1403. /* Calculate the VQ weighting vector */
  1404. weight[0] = (1 << 20) / (lsp[1] - lsp[0]);
  1405. weight[LPC_ORDER - 1] = (1 << 20) /
  1406. (lsp[LPC_ORDER - 1] - lsp[LPC_ORDER - 2]);
  1407. for (i = 1; i < LPC_ORDER - 1; i++) {
  1408. min = FFMIN(lsp[i] - lsp[i - 1], lsp[i + 1] - lsp[i]);
  1409. if (min > 0x20)
  1410. weight[i] = (1 << 20) / min;
  1411. else
  1412. weight[i] = INT16_MAX;
  1413. }
  1414. /* Normalize */
  1415. max = 0;
  1416. for (i = 0; i < LPC_ORDER; i++)
  1417. max = FFMAX(weight[i], max);
  1418. shift = normalize_bits_int16(max);
  1419. for (i = 0; i < LPC_ORDER; i++) {
  1420. weight[i] <<= shift;
  1421. }
  1422. /* Compute the VQ target vector */
  1423. for (i = 0; i < LPC_ORDER; i++) {
  1424. lsp[i] -= dc_lsp[i] +
  1425. (((prev_lsp[i] - dc_lsp[i]) * 12288 + (1 << 14)) >> 15);
  1426. }
  1427. get_index(0, 0, 3);
  1428. get_index(1, 3, 3);
  1429. get_index(2, 6, 4);
  1430. }
  1431. /**
  1432. * Apply the formant perceptual weighting filter.
  1433. *
  1434. * @param flt_coef filter coefficients
  1435. * @param unq_lpc unquantized lpc vector
  1436. */
  1437. static void perceptual_filter(G723_1_Context *p, int16_t *flt_coef,
  1438. int16_t *unq_lpc, int16_t *buf)
  1439. {
  1440. int16_t vector[FRAME_LEN + LPC_ORDER];
  1441. int i, j, k, l = 0;
  1442. memcpy(buf, p->iir_mem, sizeof(int16_t) * LPC_ORDER);
  1443. memcpy(vector, p->fir_mem, sizeof(int16_t) * LPC_ORDER);
  1444. memcpy(vector + LPC_ORDER, buf + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
  1445. for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
  1446. for (k = 0; k < LPC_ORDER; k++) {
  1447. flt_coef[k + 2 * l] = (unq_lpc[k + l] * percept_flt_tbl[0][k] +
  1448. (1 << 14)) >> 15;
  1449. flt_coef[k + 2 * l + LPC_ORDER] = (unq_lpc[k + l] *
  1450. percept_flt_tbl[1][k] +
  1451. (1 << 14)) >> 15;
  1452. }
  1453. iir_filter(flt_coef + 2 * l, flt_coef + 2 * l + LPC_ORDER, vector + i,
  1454. buf + i, 0);
  1455. l += LPC_ORDER;
  1456. }
  1457. memcpy(p->iir_mem, buf + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
  1458. memcpy(p->fir_mem, vector + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
  1459. }
  1460. /**
  1461. * Estimate the open loop pitch period.
  1462. *
  1463. * @param buf perceptually weighted speech
  1464. * @param start estimation is carried out from this position
  1465. */
  1466. static int estimate_pitch(int16_t *buf, int start)
  1467. {
  1468. int max_exp = 32;
  1469. int max_ccr = 0x4000;
  1470. int max_eng = 0x7fff;
  1471. int index = PITCH_MIN;
  1472. int offset = start - PITCH_MIN + 1;
  1473. int ccr, eng, orig_eng, ccr_eng, exp;
  1474. int diff, temp;
  1475. int i;
  1476. orig_eng = ff_dot_product(buf + offset, buf + offset, HALF_FRAME_LEN);
  1477. for (i = PITCH_MIN; i <= PITCH_MAX - 3; i++) {
  1478. offset--;
  1479. /* Update energy and compute correlation */
  1480. orig_eng += buf[offset] * buf[offset] -
  1481. buf[offset + HALF_FRAME_LEN] * buf[offset + HALF_FRAME_LEN];
  1482. ccr = ff_dot_product(buf + start, buf + offset, HALF_FRAME_LEN);
  1483. if (ccr <= 0)
  1484. continue;
  1485. /* Split into mantissa and exponent to maintain precision */
  1486. exp = normalize_bits_int32(ccr);
  1487. ccr = av_clipl_int32((int64_t)(ccr << exp) + (1 << 15)) >> 16;
  1488. exp <<= 1;
  1489. ccr *= ccr;
  1490. temp = normalize_bits_int32(ccr);
  1491. ccr = ccr << temp >> 16;
  1492. exp += temp;
  1493. temp = normalize_bits_int32(orig_eng);
  1494. eng = av_clipl_int32((int64_t)(orig_eng << temp) + (1 << 15)) >> 16;
  1495. exp -= temp;
  1496. if (ccr >= eng) {
  1497. exp--;
  1498. ccr >>= 1;
  1499. }
  1500. if (exp > max_exp)
  1501. continue;
  1502. if (exp + 1 < max_exp)
  1503. goto update;
  1504. /* Equalize exponents before comparison */
  1505. if (exp + 1 == max_exp)
  1506. temp = max_ccr >> 1;
  1507. else
  1508. temp = max_ccr;
  1509. ccr_eng = ccr * max_eng;
  1510. diff = ccr_eng - eng * temp;
  1511. if (diff > 0 && (i - index < PITCH_MIN || diff > ccr_eng >> 2)) {
  1512. update:
  1513. index = i;
  1514. max_exp = exp;
  1515. max_ccr = ccr;
  1516. max_eng = eng;
  1517. }
  1518. }
  1519. return index;
  1520. }
  1521. /**
  1522. * Compute harmonic noise filter parameters.
  1523. *
  1524. * @param buf perceptually weighted speech
  1525. * @param pitch_lag open loop pitch period
  1526. * @param hf harmonic filter parameters
  1527. */
  1528. static void comp_harmonic_coeff(int16_t *buf, int16_t pitch_lag, HFParam *hf)
  1529. {
  1530. int ccr, eng, max_ccr, max_eng;
  1531. int exp, max, diff;
  1532. int energy[15];
  1533. int i, j;
  1534. for (i = 0, j = pitch_lag - 3; j <= pitch_lag + 3; i++, j++) {
  1535. /* Compute residual energy */
  1536. energy[i << 1] = ff_dot_product(buf - j, buf - j, SUBFRAME_LEN);
  1537. /* Compute correlation */
  1538. energy[(i << 1) + 1] = ff_dot_product(buf, buf - j, SUBFRAME_LEN);
  1539. }
  1540. /* Compute target energy */
  1541. energy[14] = ff_dot_product(buf, buf, SUBFRAME_LEN);
  1542. /* Normalize */
  1543. max = 0;
  1544. for (i = 0; i < 15; i++)
  1545. max = FFMAX(max, FFABS(energy[i]));
  1546. exp = normalize_bits_int32(max);
  1547. for (i = 0; i < 15; i++) {
  1548. energy[i] = av_clipl_int32((int64_t)(energy[i] << exp) +
  1549. (1 << 15)) >> 16;
  1550. }
  1551. hf->index = -1;
  1552. hf->gain = 0;
  1553. max_ccr = 1;
  1554. max_eng = 0x7fff;
  1555. for (i = 0; i <= 6; i++) {
  1556. eng = energy[i << 1];
  1557. ccr = energy[(i << 1) + 1];
  1558. if (ccr <= 0)
  1559. continue;
  1560. ccr = (ccr * ccr + (1 << 14)) >> 15;
  1561. diff = ccr * max_eng - eng * max_ccr;
  1562. if (diff > 0) {
  1563. max_ccr = ccr;
  1564. max_eng = eng;
  1565. hf->index = i;
  1566. }
  1567. }
  1568. if (hf->index == -1) {
  1569. hf->index = pitch_lag;
  1570. return;
  1571. }
  1572. eng = energy[14] * max_eng;
  1573. eng = (eng >> 2) + (eng >> 3);
  1574. ccr = energy[(hf->index << 1) + 1] * energy[(hf->index << 1) + 1];
  1575. if (eng < ccr) {
  1576. eng = energy[(hf->index << 1) + 1];
  1577. if (eng >= max_eng)
  1578. hf->gain = 0x2800;
  1579. else
  1580. hf->gain = ((eng << 15) / max_eng * 0x2800 + (1 << 14)) >> 15;
  1581. }
  1582. hf->index += pitch_lag - 3;
  1583. }
  1584. /**
  1585. * Apply the harmonic noise shaping filter.
  1586. *
  1587. * @param hf filter parameters
  1588. */
  1589. static void harmonic_filter(HFParam *hf, const int16_t *src, int16_t *dest)
  1590. {
  1591. int i;
  1592. for (i = 0; i < SUBFRAME_LEN; i++) {
  1593. int64_t temp = hf->gain * src[i - hf->index] << 1;
  1594. dest[i] = av_clipl_int32((src[i] << 16) - temp + (1 << 15)) >> 16;
  1595. }
  1596. }
  1597. static void harmonic_noise_sub(HFParam *hf, const int16_t *src, int16_t *dest)
  1598. {
  1599. int i;
  1600. for (i = 0; i < SUBFRAME_LEN; i++) {
  1601. int64_t temp = hf->gain * src[i - hf->index] << 1;
  1602. dest[i] = av_clipl_int32(((dest[i] - src[i]) << 16) + temp +
  1603. (1 << 15)) >> 16;
  1604. }
  1605. }
  1606. /**
  1607. * Combined synthesis and formant perceptual weighting filer.
  1608. *
  1609. * @param qnt_lpc quantized lpc coefficients
  1610. * @param perf_lpc perceptual filter coefficients
  1611. * @param perf_fir perceptual filter fir memory
  1612. * @param perf_iir perceptual filter iir memory
  1613. * @param scale the filter output will be scaled by 2^scale
  1614. */
  1615. static void synth_percept_filter(int16_t *qnt_lpc, int16_t *perf_lpc,
  1616. int16_t *perf_fir, int16_t *perf_iir,
  1617. const int16_t *src, int16_t *dest, int scale)
  1618. {
  1619. int i, j;
  1620. int16_t buf_16[SUBFRAME_LEN + LPC_ORDER];
  1621. int64_t buf[SUBFRAME_LEN];
  1622. int16_t *bptr_16 = buf_16 + LPC_ORDER;
  1623. memcpy(buf_16, perf_fir, sizeof(int16_t) * LPC_ORDER);
  1624. memcpy(dest - LPC_ORDER, perf_iir, sizeof(int16_t) * LPC_ORDER);
  1625. for (i = 0; i < SUBFRAME_LEN; i++) {
  1626. int64_t temp = 0;
  1627. for (j = 1; j <= LPC_ORDER; j++)
  1628. temp -= qnt_lpc[j - 1] * bptr_16[i - j];
  1629. buf[i] = (src[i] << 15) + (temp << 3);
  1630. bptr_16[i] = av_clipl_int32(buf[i] + (1 << 15)) >> 16;
  1631. }
  1632. for (i = 0; i < SUBFRAME_LEN; i++) {
  1633. int64_t fir = 0, iir = 0;
  1634. for (j = 1; j <= LPC_ORDER; j++) {
  1635. fir -= perf_lpc[j - 1] * bptr_16[i - j];
  1636. iir += perf_lpc[j + LPC_ORDER - 1] * dest[i - j];
  1637. }
  1638. dest[i] = av_clipl_int32(((buf[i] + (fir << 3)) << scale) + (iir << 3) +
  1639. (1 << 15)) >> 16;
  1640. }
  1641. memcpy(perf_fir, buf_16 + SUBFRAME_LEN, sizeof(int16_t) * LPC_ORDER);
  1642. memcpy(perf_iir, dest + SUBFRAME_LEN - LPC_ORDER,
  1643. sizeof(int16_t) * LPC_ORDER);
  1644. }
  1645. /**
  1646. * Compute the adaptive codebook contribution.
  1647. *
  1648. * @param buf input signal
  1649. * @param index the current subframe index
  1650. */
  1651. static void acb_search(G723_1_Context *p, int16_t *residual,
  1652. int16_t *impulse_resp, const int16_t *buf,
  1653. int index)
  1654. {
  1655. int16_t flt_buf[PITCH_ORDER][SUBFRAME_LEN];
  1656. const int16_t *cb_tbl = adaptive_cb_gain85;
  1657. int ccr_buf[PITCH_ORDER * SUBFRAMES << 2];
  1658. int pitch_lag = p->pitch_lag[index >> 1];
  1659. int acb_lag = 1;
  1660. int acb_gain = 0;
  1661. int odd_frame = index & 1;
  1662. int iter = 3 + odd_frame;
  1663. int count = 0;
  1664. int tbl_size = 85;
  1665. int i, j, k, l, max;
  1666. int64_t temp;
  1667. if (!odd_frame) {
  1668. if (pitch_lag == PITCH_MIN)
  1669. pitch_lag++;
  1670. else
  1671. pitch_lag = FFMIN(pitch_lag, PITCH_MAX - 5);
  1672. }
  1673. for (i = 0; i < iter; i++) {
  1674. get_residual(residual, p->prev_excitation, pitch_lag + i - 1);
  1675. for (j = 0; j < SUBFRAME_LEN; j++) {
  1676. temp = 0;
  1677. for (k = 0; k <= j; k++)
  1678. temp += residual[PITCH_ORDER - 1 + k] * impulse_resp[j - k];
  1679. flt_buf[PITCH_ORDER - 1][j] = av_clipl_int32((temp << 1) +
  1680. (1 << 15)) >> 16;
  1681. }
  1682. for (j = PITCH_ORDER - 2; j >= 0; j--) {
  1683. flt_buf[j][0] = ((residual[j] << 13) + (1 << 14)) >> 15;
  1684. for (k = 1; k < SUBFRAME_LEN; k++) {
  1685. temp = (flt_buf[j + 1][k - 1] << 15) +
  1686. residual[j] * impulse_resp[k];
  1687. flt_buf[j][k] = av_clipl_int32((temp << 1) + (1 << 15)) >> 16;
  1688. }
  1689. }
  1690. /* Compute crosscorrelation with the signal */
  1691. for (j = 0; j < PITCH_ORDER; j++) {
  1692. temp = ff_dot_product(buf, flt_buf[j], SUBFRAME_LEN);
  1693. ccr_buf[count++] = av_clipl_int32(temp << 1);
  1694. }
  1695. /* Compute energies */
  1696. for (j = 0; j < PITCH_ORDER; j++) {
  1697. ccr_buf[count++] = dot_product(flt_buf[j], flt_buf[j],
  1698. SUBFRAME_LEN);
  1699. }
  1700. for (j = 1; j < PITCH_ORDER; j++) {
  1701. for (k = 0; k < j; k++) {
  1702. temp = ff_dot_product(flt_buf[j], flt_buf[k], SUBFRAME_LEN);
  1703. ccr_buf[count++] = av_clipl_int32(temp<<2);
  1704. }
  1705. }
  1706. }
  1707. /* Normalize and shorten */
  1708. max = 0;
  1709. for (i = 0; i < 20 * iter; i++)
  1710. max = FFMAX(max, FFABS(ccr_buf[i]));
  1711. temp = normalize_bits_int32(max);
  1712. for (i = 0; i < 20 * iter; i++){
  1713. ccr_buf[i] = av_clipl_int32((int64_t)(ccr_buf[i] << temp) +
  1714. (1 << 15)) >> 16;
  1715. }
  1716. max = 0;
  1717. for (i = 0; i < iter; i++) {
  1718. /* Select quantization table */
  1719. if (!odd_frame && pitch_lag + i - 1 >= SUBFRAME_LEN - 2 ||
  1720. odd_frame && pitch_lag >= SUBFRAME_LEN - 2) {
  1721. cb_tbl = adaptive_cb_gain170;
  1722. tbl_size = 170;
  1723. }
  1724. for (j = 0, k = 0; j < tbl_size; j++, k += 20) {
  1725. temp = 0;
  1726. for (l = 0; l < 20; l++)
  1727. temp += ccr_buf[20 * i + l] * cb_tbl[k + l];
  1728. temp = av_clipl_int32(temp);
  1729. if (temp > max) {
  1730. max = temp;
  1731. acb_gain = j;
  1732. acb_lag = i;
  1733. }
  1734. }
  1735. }
  1736. if (!odd_frame) {
  1737. pitch_lag += acb_lag - 1;
  1738. acb_lag = 1;
  1739. }
  1740. p->pitch_lag[index >> 1] = pitch_lag;
  1741. p->subframe[index].ad_cb_lag = acb_lag;
  1742. p->subframe[index].ad_cb_gain = acb_gain;
  1743. }
  1744. /**
  1745. * Subtract the adaptive codebook contribution from the input
  1746. * to obtain the residual.
  1747. *
  1748. * @param buf target vector
  1749. */
  1750. static void sub_acb_contrib(const int16_t *residual, const int16_t *impulse_resp,
  1751. int16_t *buf)
  1752. {
  1753. int i, j;
  1754. /* Subtract adaptive CB contribution to obtain the residual */
  1755. for (i = 0; i < SUBFRAME_LEN; i++) {
  1756. int64_t temp = buf[i] << 14;
  1757. for (j = 0; j <= i; j++)
  1758. temp -= residual[j] * impulse_resp[i - j];
  1759. buf[i] = av_clipl_int32((temp << 2) + (1 << 15)) >> 16;
  1760. }
  1761. }
  1762. /**
  1763. * Quantize the residual signal using the fixed codebook (MP-MLQ).
  1764. *
  1765. * @param optim optimized fixed codebook parameters
  1766. * @param buf excitation vector
  1767. */
  1768. static void get_fcb_param(FCBParam *optim, int16_t *impulse_resp,
  1769. int16_t *buf, int pulse_cnt, int pitch_lag)
  1770. {
  1771. FCBParam param;
  1772. int16_t impulse_r[SUBFRAME_LEN];
  1773. int16_t temp_corr[SUBFRAME_LEN];
  1774. int16_t impulse_corr[SUBFRAME_LEN];
  1775. int ccr1[SUBFRAME_LEN];
  1776. int ccr2[SUBFRAME_LEN];
  1777. int amp, err, max, max_amp_index, min, scale, i, j, k, l;
  1778. int64_t temp;
  1779. /* Update impulse response */
  1780. memcpy(impulse_r, impulse_resp, sizeof(int16_t) * SUBFRAME_LEN);
  1781. param.dirac_train = 0;
  1782. if (pitch_lag < SUBFRAME_LEN - 2) {
  1783. param.dirac_train = 1;
  1784. gen_dirac_train(impulse_r, pitch_lag);
  1785. }
  1786. for (i = 0; i < SUBFRAME_LEN; i++)
  1787. temp_corr[i] = impulse_r[i] >> 1;
  1788. /* Compute impulse response autocorrelation */
  1789. temp = dot_product(temp_corr, temp_corr, SUBFRAME_LEN);
  1790. scale = normalize_bits_int32(temp);
  1791. impulse_corr[0] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
  1792. for (i = 1; i < SUBFRAME_LEN; i++) {
  1793. temp = dot_product(temp_corr + i, temp_corr, SUBFRAME_LEN - i);
  1794. impulse_corr[i] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
  1795. }
  1796. /* Compute crosscorrelation of impulse response with residual signal */
  1797. scale -= 4;
  1798. for (i = 0; i < SUBFRAME_LEN; i++){
  1799. temp = dot_product(buf + i, impulse_r, SUBFRAME_LEN - i);
  1800. if (scale < 0)
  1801. ccr1[i] = temp >> -scale;
  1802. else
  1803. ccr1[i] = av_clipl_int32(temp << scale);
  1804. }
  1805. /* Search loop */
  1806. for (i = 0; i < GRID_SIZE; i++) {
  1807. /* Maximize the crosscorrelation */
  1808. max = 0;
  1809. for (j = i; j < SUBFRAME_LEN; j += GRID_SIZE) {
  1810. temp = FFABS(ccr1[j]);
  1811. if (temp >= max) {
  1812. max = temp;
  1813. param.pulse_pos[0] = j;
  1814. }
  1815. }
  1816. /* Quantize the gain (max crosscorrelation/impulse_corr[0]) */
  1817. amp = max;
  1818. min = 1 << 30;
  1819. max_amp_index = GAIN_LEVELS - 2;
  1820. for (j = max_amp_index; j >= 2; j--) {
  1821. temp = av_clipl_int32((int64_t)fixed_cb_gain[j] *
  1822. impulse_corr[0] << 1);
  1823. temp = FFABS(temp - amp);
  1824. if (temp < min) {
  1825. min = temp;
  1826. max_amp_index = j;
  1827. }
  1828. }
  1829. max_amp_index--;
  1830. /* Select additional gain values */
  1831. for (j = 1; j < 5; j++) {
  1832. for (k = i; k < SUBFRAME_LEN; k += GRID_SIZE) {
  1833. temp_corr[k] = 0;
  1834. ccr2[k] = ccr1[k];
  1835. }
  1836. param.amp_index = max_amp_index + j - 2;
  1837. amp = fixed_cb_gain[param.amp_index];
  1838. param.pulse_sign[0] = (ccr2[param.pulse_pos[0]] < 0) ? -amp : amp;
  1839. temp_corr[param.pulse_pos[0]] = 1;
  1840. for (k = 1; k < pulse_cnt; k++) {
  1841. max = -1 << 30;
  1842. for (l = i; l < SUBFRAME_LEN; l += GRID_SIZE) {
  1843. if (temp_corr[l])
  1844. continue;
  1845. temp = impulse_corr[FFABS(l - param.pulse_pos[k - 1])];
  1846. temp = av_clipl_int32((int64_t)temp *
  1847. param.pulse_sign[k - 1] << 1);
  1848. ccr2[l] -= temp;
  1849. temp = FFABS(ccr2[l]);
  1850. if (temp > max) {
  1851. max = temp;
  1852. param.pulse_pos[k] = l;
  1853. }
  1854. }
  1855. param.pulse_sign[k] = (ccr2[param.pulse_pos[k]] < 0) ?
  1856. -amp : amp;
  1857. temp_corr[param.pulse_pos[k]] = 1;
  1858. }
  1859. /* Create the error vector */
  1860. memset(temp_corr, 0, sizeof(int16_t) * SUBFRAME_LEN);
  1861. for (k = 0; k < pulse_cnt; k++)
  1862. temp_corr[param.pulse_pos[k]] = param.pulse_sign[k];
  1863. for (k = SUBFRAME_LEN - 1; k >= 0; k--) {
  1864. temp = 0;
  1865. for (l = 0; l <= k; l++) {
  1866. int prod = av_clipl_int32((int64_t)temp_corr[l] *
  1867. impulse_r[k - l] << 1);
  1868. temp = av_clipl_int32(temp + prod);
  1869. }
  1870. temp_corr[k] = temp << 2 >> 16;
  1871. }
  1872. /* Compute square of error */
  1873. err = 0;
  1874. for (k = 0; k < SUBFRAME_LEN; k++) {
  1875. int64_t prod;
  1876. prod = av_clipl_int32((int64_t)buf[k] * temp_corr[k] << 1);
  1877. err = av_clipl_int32(err - prod);
  1878. prod = av_clipl_int32((int64_t)temp_corr[k] * temp_corr[k]);
  1879. err = av_clipl_int32(err + prod);
  1880. }
  1881. /* Minimize */
  1882. if (err < optim->min_err) {
  1883. optim->min_err = err;
  1884. optim->grid_index = i;
  1885. optim->amp_index = param.amp_index;
  1886. optim->dirac_train = param.dirac_train;
  1887. for (k = 0; k < pulse_cnt; k++) {
  1888. optim->pulse_sign[k] = param.pulse_sign[k];
  1889. optim->pulse_pos[k] = param.pulse_pos[k];
  1890. }
  1891. }
  1892. }
  1893. }
  1894. }
  1895. /**
  1896. * Encode the pulse position and gain of the current subframe.
  1897. *
  1898. * @param optim optimized fixed CB parameters
  1899. * @param buf excitation vector
  1900. */
  1901. static void pack_fcb_param(G723_1_Subframe *subfrm, FCBParam *optim,
  1902. int16_t *buf, int pulse_cnt)
  1903. {
  1904. int i, j;
  1905. j = PULSE_MAX - pulse_cnt;
  1906. subfrm->pulse_sign = 0;
  1907. subfrm->pulse_pos = 0;
  1908. for (i = 0; i < SUBFRAME_LEN >> 1; i++) {
  1909. int val = buf[optim->grid_index + (i << 1)];
  1910. if (!val) {
  1911. subfrm->pulse_pos += combinatorial_table[j][i];
  1912. } else {
  1913. subfrm->pulse_sign <<= 1;
  1914. if (val < 0) subfrm->pulse_sign++;
  1915. j++;
  1916. if (j == PULSE_MAX) break;
  1917. }
  1918. }
  1919. subfrm->amp_index = optim->amp_index;
  1920. subfrm->grid_index = optim->grid_index;
  1921. subfrm->dirac_train = optim->dirac_train;
  1922. }
  1923. /**
  1924. * Compute the fixed codebook excitation.
  1925. *
  1926. * @param buf target vector
  1927. * @param impulse_resp impulse response of the combined filter
  1928. */
  1929. static void fcb_search(G723_1_Context *p, int16_t *impulse_resp,
  1930. int16_t *buf, int index)
  1931. {
  1932. FCBParam optim;
  1933. int pulse_cnt = pulses[index];
  1934. int i;
  1935. optim.min_err = 1 << 30;
  1936. get_fcb_param(&optim, impulse_resp, buf, pulse_cnt, SUBFRAME_LEN);
  1937. if (p->pitch_lag[index >> 1] < SUBFRAME_LEN - 2) {
  1938. get_fcb_param(&optim, impulse_resp, buf, pulse_cnt,
  1939. p->pitch_lag[index >> 1]);
  1940. }
  1941. /* Reconstruct the excitation */
  1942. memset(buf, 0, sizeof(int16_t) * SUBFRAME_LEN);
  1943. for (i = 0; i < pulse_cnt; i++)
  1944. buf[optim.pulse_pos[i]] = optim.pulse_sign[i];
  1945. pack_fcb_param(&p->subframe[index], &optim, buf, pulse_cnt);
  1946. if (optim.dirac_train)
  1947. gen_dirac_train(buf, p->pitch_lag[index >> 1]);
  1948. }
  1949. /**
  1950. * Pack the frame parameters into output bitstream.
  1951. *
  1952. * @param frame output buffer
  1953. * @param size size of the buffer
  1954. */
  1955. static int pack_bitstream(G723_1_Context *p, unsigned char *frame, int size)
  1956. {
  1957. PutBitContext pb;
  1958. int info_bits, i, temp;
  1959. init_put_bits(&pb, frame, size);
  1960. if (p->cur_rate == RATE_6300) {
  1961. info_bits = 0;
  1962. put_bits(&pb, 2, info_bits);
  1963. }
  1964. put_bits(&pb, 8, p->lsp_index[2]);
  1965. put_bits(&pb, 8, p->lsp_index[1]);
  1966. put_bits(&pb, 8, p->lsp_index[0]);
  1967. put_bits(&pb, 7, p->pitch_lag[0] - PITCH_MIN);
  1968. put_bits(&pb, 2, p->subframe[1].ad_cb_lag);
  1969. put_bits(&pb, 7, p->pitch_lag[1] - PITCH_MIN);
  1970. put_bits(&pb, 2, p->subframe[3].ad_cb_lag);
  1971. /* Write 12 bit combined gain */
  1972. for (i = 0; i < SUBFRAMES; i++) {
  1973. temp = p->subframe[i].ad_cb_gain * GAIN_LEVELS +
  1974. p->subframe[i].amp_index;
  1975. if (p->cur_rate == RATE_6300)
  1976. temp += p->subframe[i].dirac_train << 11;
  1977. put_bits(&pb, 12, temp);
  1978. }
  1979. put_bits(&pb, 1, p->subframe[0].grid_index);
  1980. put_bits(&pb, 1, p->subframe[1].grid_index);
  1981. put_bits(&pb, 1, p->subframe[2].grid_index);
  1982. put_bits(&pb, 1, p->subframe[3].grid_index);
  1983. if (p->cur_rate == RATE_6300) {
  1984. skip_put_bits(&pb, 1); /* reserved bit */
  1985. /* Write 13 bit combined position index */
  1986. temp = (p->subframe[0].pulse_pos >> 16) * 810 +
  1987. (p->subframe[1].pulse_pos >> 14) * 90 +
  1988. (p->subframe[2].pulse_pos >> 16) * 9 +
  1989. (p->subframe[3].pulse_pos >> 14);
  1990. put_bits(&pb, 13, temp);
  1991. put_bits(&pb, 16, p->subframe[0].pulse_pos & 0xffff);
  1992. put_bits(&pb, 14, p->subframe[1].pulse_pos & 0x3fff);
  1993. put_bits(&pb, 16, p->subframe[2].pulse_pos & 0xffff);
  1994. put_bits(&pb, 14, p->subframe[3].pulse_pos & 0x3fff);
  1995. put_bits(&pb, 6, p->subframe[0].pulse_sign);
  1996. put_bits(&pb, 5, p->subframe[1].pulse_sign);
  1997. put_bits(&pb, 6, p->subframe[2].pulse_sign);
  1998. put_bits(&pb, 5, p->subframe[3].pulse_sign);
  1999. }
  2000. flush_put_bits(&pb);
  2001. return frame_size[info_bits];
  2002. }
  2003. static int g723_1_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  2004. const AVFrame *frame, int *got_packet_ptr)
  2005. {
  2006. G723_1_Context *p = avctx->priv_data;
  2007. int16_t unq_lpc[LPC_ORDER * SUBFRAMES];
  2008. int16_t qnt_lpc[LPC_ORDER * SUBFRAMES];
  2009. int16_t cur_lsp[LPC_ORDER];
  2010. int16_t weighted_lpc[LPC_ORDER * SUBFRAMES << 1];
  2011. int16_t vector[FRAME_LEN + PITCH_MAX];
  2012. int offset, ret;
  2013. int16_t *in = (const int16_t *)frame->data[0];
  2014. HFParam hf[4];
  2015. int i, j;
  2016. highpass_filter(in, &p->hpf_fir_mem, &p->hpf_iir_mem);
  2017. memcpy(vector, p->prev_data, HALF_FRAME_LEN * sizeof(int16_t));
  2018. memcpy(vector + HALF_FRAME_LEN, in, FRAME_LEN * sizeof(int16_t));
  2019. comp_lpc_coeff(vector, unq_lpc);
  2020. lpc2lsp(&unq_lpc[LPC_ORDER * 3], p->prev_lsp, cur_lsp);
  2021. lsp_quantize(p->lsp_index, cur_lsp, p->prev_lsp);
  2022. /* Update memory */
  2023. memcpy(vector + LPC_ORDER, p->prev_data + SUBFRAME_LEN,
  2024. sizeof(int16_t) * SUBFRAME_LEN);
  2025. memcpy(vector + LPC_ORDER + SUBFRAME_LEN, in,
  2026. sizeof(int16_t) * (HALF_FRAME_LEN + SUBFRAME_LEN));
  2027. memcpy(p->prev_data, in + HALF_FRAME_LEN,
  2028. sizeof(int16_t) * HALF_FRAME_LEN);
  2029. memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
  2030. perceptual_filter(p, weighted_lpc, unq_lpc, vector);
  2031. memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
  2032. memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
  2033. memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
  2034. scale_vector(vector, vector, FRAME_LEN + PITCH_MAX);
  2035. p->pitch_lag[0] = estimate_pitch(vector, PITCH_MAX);
  2036. p->pitch_lag[1] = estimate_pitch(vector, PITCH_MAX + HALF_FRAME_LEN);
  2037. for (i = PITCH_MAX, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
  2038. comp_harmonic_coeff(vector + i, p->pitch_lag[j >> 1], hf + j);
  2039. memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
  2040. memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
  2041. memcpy(p->prev_weight_sig, vector + FRAME_LEN, sizeof(int16_t) * PITCH_MAX);
  2042. for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
  2043. harmonic_filter(hf + j, vector + PITCH_MAX + i, in + i);
  2044. inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, 0);
  2045. lsp_interpolate(qnt_lpc, cur_lsp, p->prev_lsp);
  2046. memcpy(p->prev_lsp, cur_lsp, sizeof(int16_t) * LPC_ORDER);
  2047. offset = 0;
  2048. for (i = 0; i < SUBFRAMES; i++) {
  2049. int16_t impulse_resp[SUBFRAME_LEN];
  2050. int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
  2051. int16_t flt_in[SUBFRAME_LEN];
  2052. int16_t zero[LPC_ORDER], fir[LPC_ORDER], iir[LPC_ORDER];
  2053. /**
  2054. * Compute the combined impulse response of the synthesis filter,
  2055. * formant perceptual weighting filter and harmonic noise shaping filter
  2056. */
  2057. memset(zero, 0, sizeof(int16_t) * LPC_ORDER);
  2058. memset(vector, 0, sizeof(int16_t) * PITCH_MAX);
  2059. memset(flt_in, 0, sizeof(int16_t) * SUBFRAME_LEN);
  2060. flt_in[0] = 1 << 13; /* Unit impulse */
  2061. synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
  2062. zero, zero, flt_in, vector + PITCH_MAX, 1);
  2063. harmonic_filter(hf + i, vector + PITCH_MAX, impulse_resp);
  2064. /* Compute the combined zero input response */
  2065. flt_in[0] = 0;
  2066. memcpy(fir, p->perf_fir_mem, sizeof(int16_t) * LPC_ORDER);
  2067. memcpy(iir, p->perf_iir_mem, sizeof(int16_t) * LPC_ORDER);
  2068. synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
  2069. fir, iir, flt_in, vector + PITCH_MAX, 0);
  2070. memcpy(vector, p->harmonic_mem, sizeof(int16_t) * PITCH_MAX);
  2071. harmonic_noise_sub(hf + i, vector + PITCH_MAX, in);
  2072. acb_search(p, residual, impulse_resp, in, i);
  2073. gen_acb_excitation(residual, p->prev_excitation,p->pitch_lag[i >> 1],
  2074. &p->subframe[i], p->cur_rate);
  2075. sub_acb_contrib(residual, impulse_resp, in);
  2076. fcb_search(p, impulse_resp, in, i);
  2077. /* Reconstruct the excitation */
  2078. gen_acb_excitation(impulse_resp, p->prev_excitation, p->pitch_lag[i >> 1],
  2079. &p->subframe[i], RATE_6300);
  2080. memmove(p->prev_excitation, p->prev_excitation + SUBFRAME_LEN,
  2081. sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
  2082. for (j = 0; j < SUBFRAME_LEN; j++)
  2083. in[j] = av_clip_int16((in[j] << 1) + impulse_resp[j]);
  2084. memcpy(p->prev_excitation + PITCH_MAX - SUBFRAME_LEN, in,
  2085. sizeof(int16_t) * SUBFRAME_LEN);
  2086. /* Update filter memories */
  2087. synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
  2088. p->perf_fir_mem, p->perf_iir_mem,
  2089. in, vector + PITCH_MAX, 0);
  2090. memmove(p->harmonic_mem, p->harmonic_mem + SUBFRAME_LEN,
  2091. sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
  2092. memcpy(p->harmonic_mem + PITCH_MAX - SUBFRAME_LEN, vector + PITCH_MAX,
  2093. sizeof(int16_t) * SUBFRAME_LEN);
  2094. in += SUBFRAME_LEN;
  2095. offset += LPC_ORDER;
  2096. }
  2097. if ((ret = ff_alloc_packet2(avctx, avpkt, 24)) < 0)
  2098. return ret;
  2099. *got_packet_ptr = 1;
  2100. avpkt->size = pack_bitstream(p, avpkt->data, avpkt->size);
  2101. return 0;
  2102. }
  2103. AVCodec ff_g723_1_encoder = {
  2104. .name = "g723_1",
  2105. .type = AVMEDIA_TYPE_AUDIO,
  2106. .id = AV_CODEC_ID_G723_1,
  2107. .priv_data_size = sizeof(G723_1_Context),
  2108. .init = g723_1_encode_init,
  2109. .encode2 = g723_1_encode_frame,
  2110. .long_name = NULL_IF_CONFIG_SMALL("G.723.1"),
  2111. .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,
  2112. AV_SAMPLE_FMT_NONE},
  2113. };
  2114. #endif