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.

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