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.

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