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.

2289 lines
72KB

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