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.

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