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.

1382 lines
42KB

  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 Libav.
  7. *
  8. * Libav 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. * Libav 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 Libav; 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 "get_bits.h"
  32. #include "acelp_vectors.h"
  33. #include "celp_filters.h"
  34. #include "g723_1_data.h"
  35. #define CNG_RANDOM_SEED 12345
  36. /**
  37. * G723.1 frame types
  38. */
  39. enum FrameType {
  40. ACTIVE_FRAME, ///< Active speech
  41. SID_FRAME, ///< Silence Insertion Descriptor frame
  42. UNTRANSMITTED_FRAME
  43. };
  44. enum Rate {
  45. RATE_6300,
  46. RATE_5300
  47. };
  48. /**
  49. * G723.1 unpacked data subframe
  50. */
  51. typedef struct {
  52. int ad_cb_lag; ///< adaptive codebook lag
  53. int ad_cb_gain;
  54. int dirac_train;
  55. int pulse_sign;
  56. int grid_index;
  57. int amp_index;
  58. int pulse_pos;
  59. } G723_1_Subframe;
  60. /**
  61. * Pitch postfilter parameters
  62. */
  63. typedef struct {
  64. int index; ///< postfilter backward/forward lag
  65. int16_t opt_gain; ///< optimal gain
  66. int16_t sc_gain; ///< scaling gain
  67. } PPFParam;
  68. typedef struct g723_1_context {
  69. AVClass *class;
  70. AVFrame frame;
  71. G723_1_Subframe subframe[4];
  72. enum FrameType cur_frame_type;
  73. enum FrameType past_frame_type;
  74. enum Rate cur_rate;
  75. uint8_t lsp_index[LSP_BANDS];
  76. int pitch_lag[2];
  77. int erased_frames;
  78. int16_t prev_lsp[LPC_ORDER];
  79. int16_t sid_lsp[LPC_ORDER];
  80. int16_t prev_excitation[PITCH_MAX];
  81. int16_t excitation[PITCH_MAX + FRAME_LEN + 4];
  82. int16_t synth_mem[LPC_ORDER];
  83. int16_t fir_mem[LPC_ORDER];
  84. int iir_mem[LPC_ORDER];
  85. int random_seed;
  86. int cng_random_seed;
  87. int interp_index;
  88. int interp_gain;
  89. int sid_gain;
  90. int cur_gain;
  91. int reflection_coef;
  92. int pf_gain;
  93. int postfilter;
  94. int16_t audio[FRAME_LEN + LPC_ORDER + PITCH_MAX + 4];
  95. } G723_1_Context;
  96. static av_cold int g723_1_decode_init(AVCodecContext *avctx)
  97. {
  98. G723_1_Context *p = avctx->priv_data;
  99. avctx->channel_layout = AV_CH_LAYOUT_MONO;
  100. avctx->sample_fmt = AV_SAMPLE_FMT_S16;
  101. avctx->channels = 1;
  102. avctx->sample_rate = 8000;
  103. p->pf_gain = 1 << 12;
  104. avcodec_get_frame_defaults(&p->frame);
  105. avctx->coded_frame = &p->frame;
  106. memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
  107. memcpy(p->sid_lsp, dc_lsp, LPC_ORDER * sizeof(*p->sid_lsp));
  108. p->cng_random_seed = CNG_RANDOM_SEED;
  109. p->past_frame_type = SID_FRAME;
  110. return 0;
  111. }
  112. /**
  113. * Unpack the frame into parameters.
  114. *
  115. * @param p the context
  116. * @param buf pointer to the input buffer
  117. * @param buf_size size of the input buffer
  118. */
  119. static int unpack_bitstream(G723_1_Context *p, const uint8_t *buf,
  120. int buf_size)
  121. {
  122. GetBitContext gb;
  123. int ad_cb_len;
  124. int temp, info_bits, i;
  125. init_get_bits(&gb, buf, buf_size * 8);
  126. /* Extract frame type and rate info */
  127. info_bits = get_bits(&gb, 2);
  128. if (info_bits == 3) {
  129. p->cur_frame_type = UNTRANSMITTED_FRAME;
  130. return 0;
  131. }
  132. /* Extract 24 bit lsp indices, 8 bit for each band */
  133. p->lsp_index[2] = get_bits(&gb, 8);
  134. p->lsp_index[1] = get_bits(&gb, 8);
  135. p->lsp_index[0] = get_bits(&gb, 8);
  136. if (info_bits == 2) {
  137. p->cur_frame_type = SID_FRAME;
  138. p->subframe[0].amp_index = get_bits(&gb, 6);
  139. return 0;
  140. }
  141. /* Extract the info common to both rates */
  142. p->cur_rate = info_bits ? RATE_5300 : RATE_6300;
  143. p->cur_frame_type = ACTIVE_FRAME;
  144. p->pitch_lag[0] = get_bits(&gb, 7);
  145. if (p->pitch_lag[0] > 123) /* test if forbidden code */
  146. return -1;
  147. p->pitch_lag[0] += PITCH_MIN;
  148. p->subframe[1].ad_cb_lag = get_bits(&gb, 2);
  149. p->pitch_lag[1] = get_bits(&gb, 7);
  150. if (p->pitch_lag[1] > 123)
  151. return -1;
  152. p->pitch_lag[1] += PITCH_MIN;
  153. p->subframe[3].ad_cb_lag = get_bits(&gb, 2);
  154. p->subframe[0].ad_cb_lag = 1;
  155. p->subframe[2].ad_cb_lag = 1;
  156. for (i = 0; i < SUBFRAMES; i++) {
  157. /* Extract combined gain */
  158. temp = get_bits(&gb, 12);
  159. ad_cb_len = 170;
  160. p->subframe[i].dirac_train = 0;
  161. if (p->cur_rate == RATE_6300 && p->pitch_lag[i >> 1] < SUBFRAME_LEN - 2) {
  162. p->subframe[i].dirac_train = temp >> 11;
  163. temp &= 0x7FF;
  164. ad_cb_len = 85;
  165. }
  166. p->subframe[i].ad_cb_gain = FASTDIV(temp, GAIN_LEVELS);
  167. if (p->subframe[i].ad_cb_gain < ad_cb_len) {
  168. p->subframe[i].amp_index = temp - p->subframe[i].ad_cb_gain *
  169. GAIN_LEVELS;
  170. } else {
  171. return -1;
  172. }
  173. }
  174. p->subframe[0].grid_index = get_bits(&gb, 1);
  175. p->subframe[1].grid_index = get_bits(&gb, 1);
  176. p->subframe[2].grid_index = get_bits(&gb, 1);
  177. p->subframe[3].grid_index = get_bits(&gb, 1);
  178. if (p->cur_rate == RATE_6300) {
  179. skip_bits(&gb, 1); /* skip reserved bit */
  180. /* Compute pulse_pos index using the 13-bit combined position index */
  181. temp = get_bits(&gb, 13);
  182. p->subframe[0].pulse_pos = temp / 810;
  183. temp -= p->subframe[0].pulse_pos * 810;
  184. p->subframe[1].pulse_pos = FASTDIV(temp, 90);
  185. temp -= p->subframe[1].pulse_pos * 90;
  186. p->subframe[2].pulse_pos = FASTDIV(temp, 9);
  187. p->subframe[3].pulse_pos = temp - p->subframe[2].pulse_pos * 9;
  188. p->subframe[0].pulse_pos = (p->subframe[0].pulse_pos << 16) +
  189. get_bits(&gb, 16);
  190. p->subframe[1].pulse_pos = (p->subframe[1].pulse_pos << 14) +
  191. get_bits(&gb, 14);
  192. p->subframe[2].pulse_pos = (p->subframe[2].pulse_pos << 16) +
  193. get_bits(&gb, 16);
  194. p->subframe[3].pulse_pos = (p->subframe[3].pulse_pos << 14) +
  195. get_bits(&gb, 14);
  196. p->subframe[0].pulse_sign = get_bits(&gb, 6);
  197. p->subframe[1].pulse_sign = get_bits(&gb, 5);
  198. p->subframe[2].pulse_sign = get_bits(&gb, 6);
  199. p->subframe[3].pulse_sign = get_bits(&gb, 5);
  200. } else { /* 5300 bps */
  201. p->subframe[0].pulse_pos = get_bits(&gb, 12);
  202. p->subframe[1].pulse_pos = get_bits(&gb, 12);
  203. p->subframe[2].pulse_pos = get_bits(&gb, 12);
  204. p->subframe[3].pulse_pos = get_bits(&gb, 12);
  205. p->subframe[0].pulse_sign = get_bits(&gb, 4);
  206. p->subframe[1].pulse_sign = get_bits(&gb, 4);
  207. p->subframe[2].pulse_sign = get_bits(&gb, 4);
  208. p->subframe[3].pulse_sign = get_bits(&gb, 4);
  209. }
  210. return 0;
  211. }
  212. /**
  213. * Bitexact implementation of sqrt(val/2).
  214. */
  215. static int16_t square_root(int val)
  216. {
  217. int16_t res = 0;
  218. int16_t exp = 0x4000;
  219. int i;
  220. for (i = 0; i < 14; i ++) {
  221. int res_exp = res + exp;
  222. if (val >= res_exp * res_exp << 1)
  223. res += exp;
  224. exp >>= 1;
  225. }
  226. return res;
  227. }
  228. /**
  229. * Calculate the number of left-shifts required for normalizing the input.
  230. *
  231. * @param num input number
  232. * @param width width of the input, 16 bits(0) / 32 bits(1)
  233. */
  234. static int normalize_bits(int num, int width)
  235. {
  236. return width - av_log2(num) - 1;
  237. }
  238. /**
  239. * Scale vector contents based on the largest of their absolutes.
  240. */
  241. static int scale_vector(int16_t *dst, const int16_t *vector, int length)
  242. {
  243. int bits, max = 0;
  244. int i;
  245. for (i = 0; i < length; i++)
  246. max |= FFABS(vector[i]);
  247. max = FFMIN(max, 0x7FFF);
  248. bits = normalize_bits(max, 15);
  249. for (i = 0; i < length; i++)
  250. dst[i] = vector[i] << bits >> 3;
  251. return bits - 3;
  252. }
  253. /**
  254. * Perform inverse quantization of LSP frequencies.
  255. *
  256. * @param cur_lsp the current LSP vector
  257. * @param prev_lsp the previous LSP vector
  258. * @param lsp_index VQ indices
  259. * @param bad_frame bad frame flag
  260. */
  261. static void inverse_quant(int16_t *cur_lsp, int16_t *prev_lsp,
  262. uint8_t *lsp_index, int bad_frame)
  263. {
  264. int min_dist, pred;
  265. int i, j, temp, stable;
  266. /* Check for frame erasure */
  267. if (!bad_frame) {
  268. min_dist = 0x100;
  269. pred = 12288;
  270. } else {
  271. min_dist = 0x200;
  272. pred = 23552;
  273. lsp_index[0] = lsp_index[1] = lsp_index[2] = 0;
  274. }
  275. /* Get the VQ table entry corresponding to the transmitted index */
  276. cur_lsp[0] = lsp_band0[lsp_index[0]][0];
  277. cur_lsp[1] = lsp_band0[lsp_index[0]][1];
  278. cur_lsp[2] = lsp_band0[lsp_index[0]][2];
  279. cur_lsp[3] = lsp_band1[lsp_index[1]][0];
  280. cur_lsp[4] = lsp_band1[lsp_index[1]][1];
  281. cur_lsp[5] = lsp_band1[lsp_index[1]][2];
  282. cur_lsp[6] = lsp_band2[lsp_index[2]][0];
  283. cur_lsp[7] = lsp_band2[lsp_index[2]][1];
  284. cur_lsp[8] = lsp_band2[lsp_index[2]][2];
  285. cur_lsp[9] = lsp_band2[lsp_index[2]][3];
  286. /* Add predicted vector & DC component to the previously quantized vector */
  287. for (i = 0; i < LPC_ORDER; i++) {
  288. temp = ((prev_lsp[i] - dc_lsp[i]) * pred + (1 << 14)) >> 15;
  289. cur_lsp[i] += dc_lsp[i] + temp;
  290. }
  291. for (i = 0; i < LPC_ORDER; i++) {
  292. cur_lsp[0] = FFMAX(cur_lsp[0], 0x180);
  293. cur_lsp[LPC_ORDER - 1] = FFMIN(cur_lsp[LPC_ORDER - 1], 0x7e00);
  294. /* Stability check */
  295. for (j = 1; j < LPC_ORDER; j++) {
  296. temp = min_dist + cur_lsp[j - 1] - cur_lsp[j];
  297. if (temp > 0) {
  298. temp >>= 1;
  299. cur_lsp[j - 1] -= temp;
  300. cur_lsp[j] += temp;
  301. }
  302. }
  303. stable = 1;
  304. for (j = 1; j < LPC_ORDER; j++) {
  305. temp = cur_lsp[j - 1] + min_dist - cur_lsp[j] - 4;
  306. if (temp > 0) {
  307. stable = 0;
  308. break;
  309. }
  310. }
  311. if (stable)
  312. break;
  313. }
  314. if (!stable)
  315. memcpy(cur_lsp, prev_lsp, LPC_ORDER * sizeof(*cur_lsp));
  316. }
  317. /**
  318. * Bitexact implementation of 2ab scaled by 1/2^16.
  319. *
  320. * @param a 32 bit multiplicand
  321. * @param b 16 bit multiplier
  322. */
  323. #define MULL2(a, b) \
  324. ((((a) >> 16) * (b) << 1) + (((a) & 0xffff) * (b) >> 15))
  325. /**
  326. * Convert LSP frequencies to LPC coefficients.
  327. *
  328. * @param lpc buffer for LPC coefficients
  329. */
  330. static void lsp2lpc(int16_t *lpc)
  331. {
  332. int f1[LPC_ORDER / 2 + 1];
  333. int f2[LPC_ORDER / 2 + 1];
  334. int i, j;
  335. /* Calculate negative cosine */
  336. for (j = 0; j < LPC_ORDER; j++) {
  337. int index = lpc[j] >> 7;
  338. int offset = lpc[j] & 0x7f;
  339. int temp1 = cos_tab[index] << 16;
  340. int temp2 = (cos_tab[index + 1] - cos_tab[index]) *
  341. ((offset << 8) + 0x80) << 1;
  342. lpc[j] = -(av_sat_dadd32(1 << 15, temp1 + temp2) >> 16);
  343. }
  344. /*
  345. * Compute sum and difference polynomial coefficients
  346. * (bitexact alternative to lsp2poly() in lsp.c)
  347. */
  348. /* Initialize with values in Q28 */
  349. f1[0] = 1 << 28;
  350. f1[1] = (lpc[0] << 14) + (lpc[2] << 14);
  351. f1[2] = lpc[0] * lpc[2] + (2 << 28);
  352. f2[0] = 1 << 28;
  353. f2[1] = (lpc[1] << 14) + (lpc[3] << 14);
  354. f2[2] = lpc[1] * lpc[3] + (2 << 28);
  355. /*
  356. * Calculate and scale the coefficients by 1/2 in
  357. * each iteration for a final scaling factor of Q25
  358. */
  359. for (i = 2; i < LPC_ORDER / 2; i++) {
  360. f1[i + 1] = f1[i - 1] + MULL2(f1[i], lpc[2 * i]);
  361. f2[i + 1] = f2[i - 1] + MULL2(f2[i], lpc[2 * i + 1]);
  362. for (j = i; j >= 2; j--) {
  363. f1[j] = MULL2(f1[j - 1], lpc[2 * i]) +
  364. (f1[j] >> 1) + (f1[j - 2] >> 1);
  365. f2[j] = MULL2(f2[j - 1], lpc[2 * i + 1]) +
  366. (f2[j] >> 1) + (f2[j - 2] >> 1);
  367. }
  368. f1[0] >>= 1;
  369. f2[0] >>= 1;
  370. f1[1] = ((lpc[2 * i] << 16 >> i) + f1[1]) >> 1;
  371. f2[1] = ((lpc[2 * i + 1] << 16 >> i) + f2[1]) >> 1;
  372. }
  373. /* Convert polynomial coefficients to LPC coefficients */
  374. for (i = 0; i < LPC_ORDER / 2; i++) {
  375. int64_t ff1 = f1[i + 1] + f1[i];
  376. int64_t ff2 = f2[i + 1] - f2[i];
  377. lpc[i] = av_clipl_int32(((ff1 + ff2) << 3) + (1 << 15)) >> 16;
  378. lpc[LPC_ORDER - i - 1] = av_clipl_int32(((ff1 - ff2) << 3) +
  379. (1 << 15)) >> 16;
  380. }
  381. }
  382. /**
  383. * Quantize LSP frequencies by interpolation and convert them to
  384. * the corresponding LPC coefficients.
  385. *
  386. * @param lpc buffer for LPC coefficients
  387. * @param cur_lsp the current LSP vector
  388. * @param prev_lsp the previous LSP vector
  389. */
  390. static void lsp_interpolate(int16_t *lpc, int16_t *cur_lsp, int16_t *prev_lsp)
  391. {
  392. int i;
  393. int16_t *lpc_ptr = lpc;
  394. /* cur_lsp * 0.25 + prev_lsp * 0.75 */
  395. ff_acelp_weighted_vector_sum(lpc, cur_lsp, prev_lsp,
  396. 4096, 12288, 1 << 13, 14, LPC_ORDER);
  397. ff_acelp_weighted_vector_sum(lpc + LPC_ORDER, cur_lsp, prev_lsp,
  398. 8192, 8192, 1 << 13, 14, LPC_ORDER);
  399. ff_acelp_weighted_vector_sum(lpc + 2 * LPC_ORDER, cur_lsp, prev_lsp,
  400. 12288, 4096, 1 << 13, 14, LPC_ORDER);
  401. memcpy(lpc + 3 * LPC_ORDER, cur_lsp, LPC_ORDER * sizeof(*lpc));
  402. for (i = 0; i < SUBFRAMES; i++) {
  403. lsp2lpc(lpc_ptr);
  404. lpc_ptr += LPC_ORDER;
  405. }
  406. }
  407. /**
  408. * Generate a train of dirac functions with period as pitch lag.
  409. */
  410. static void gen_dirac_train(int16_t *buf, int pitch_lag)
  411. {
  412. int16_t vector[SUBFRAME_LEN];
  413. int i, j;
  414. memcpy(vector, buf, SUBFRAME_LEN * sizeof(*vector));
  415. for (i = pitch_lag; i < SUBFRAME_LEN; i += pitch_lag) {
  416. for (j = 0; j < SUBFRAME_LEN - i; j++)
  417. buf[i + j] += vector[j];
  418. }
  419. }
  420. /**
  421. * Generate fixed codebook excitation vector.
  422. *
  423. * @param vector decoded excitation vector
  424. * @param subfrm current subframe
  425. * @param cur_rate current bitrate
  426. * @param pitch_lag closed loop pitch lag
  427. * @param index current subframe index
  428. */
  429. static void gen_fcb_excitation(int16_t *vector, G723_1_Subframe *subfrm,
  430. enum Rate cur_rate, int pitch_lag, int index)
  431. {
  432. int temp, i, j;
  433. memset(vector, 0, SUBFRAME_LEN * sizeof(*vector));
  434. if (cur_rate == RATE_6300) {
  435. if (subfrm->pulse_pos >= max_pos[index])
  436. return;
  437. /* Decode amplitudes and positions */
  438. j = PULSE_MAX - pulses[index];
  439. temp = subfrm->pulse_pos;
  440. for (i = 0; i < SUBFRAME_LEN / GRID_SIZE; i++) {
  441. temp -= combinatorial_table[j][i];
  442. if (temp >= 0)
  443. continue;
  444. temp += combinatorial_table[j++][i];
  445. if (subfrm->pulse_sign & (1 << (PULSE_MAX - j))) {
  446. vector[subfrm->grid_index + GRID_SIZE * i] =
  447. -fixed_cb_gain[subfrm->amp_index];
  448. } else {
  449. vector[subfrm->grid_index + GRID_SIZE * i] =
  450. fixed_cb_gain[subfrm->amp_index];
  451. }
  452. if (j == PULSE_MAX)
  453. break;
  454. }
  455. if (subfrm->dirac_train == 1)
  456. gen_dirac_train(vector, pitch_lag);
  457. } else { /* 5300 bps */
  458. int cb_gain = fixed_cb_gain[subfrm->amp_index];
  459. int cb_shift = subfrm->grid_index;
  460. int cb_sign = subfrm->pulse_sign;
  461. int cb_pos = subfrm->pulse_pos;
  462. int offset, beta, lag;
  463. for (i = 0; i < 8; i += 2) {
  464. offset = ((cb_pos & 7) << 3) + cb_shift + i;
  465. vector[offset] = (cb_sign & 1) ? cb_gain : -cb_gain;
  466. cb_pos >>= 3;
  467. cb_sign >>= 1;
  468. }
  469. /* Enhance harmonic components */
  470. lag = pitch_contrib[subfrm->ad_cb_gain << 1] + pitch_lag +
  471. subfrm->ad_cb_lag - 1;
  472. beta = pitch_contrib[(subfrm->ad_cb_gain << 1) + 1];
  473. if (lag < SUBFRAME_LEN - 2) {
  474. for (i = lag; i < SUBFRAME_LEN; i++)
  475. vector[i] += beta * vector[i - lag] >> 15;
  476. }
  477. }
  478. }
  479. /**
  480. * Get delayed contribution from the previous excitation vector.
  481. */
  482. static void get_residual(int16_t *residual, int16_t *prev_excitation, int lag)
  483. {
  484. int offset = PITCH_MAX - PITCH_ORDER / 2 - lag;
  485. int i;
  486. residual[0] = prev_excitation[offset];
  487. residual[1] = prev_excitation[offset + 1];
  488. offset += 2;
  489. for (i = 2; i < SUBFRAME_LEN + PITCH_ORDER - 1; i++)
  490. residual[i] = prev_excitation[offset + (i - 2) % lag];
  491. }
  492. static int dot_product(const int16_t *a, const int16_t *b, int length)
  493. {
  494. int i, sum = 0;
  495. for (i = 0; i < length; i++) {
  496. int prod = a[i] * b[i];
  497. sum = av_sat_dadd32(sum, prod);
  498. }
  499. return sum;
  500. }
  501. /**
  502. * Generate adaptive codebook excitation.
  503. */
  504. static void gen_acb_excitation(int16_t *vector, int16_t *prev_excitation,
  505. int pitch_lag, G723_1_Subframe *subfrm,
  506. enum Rate cur_rate)
  507. {
  508. int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
  509. const int16_t *cb_ptr;
  510. int lag = pitch_lag + subfrm->ad_cb_lag - 1;
  511. int i;
  512. int sum;
  513. get_residual(residual, prev_excitation, lag);
  514. /* Select quantization table */
  515. if (cur_rate == RATE_6300 && pitch_lag < SUBFRAME_LEN - 2)
  516. cb_ptr = adaptive_cb_gain85;
  517. else
  518. cb_ptr = adaptive_cb_gain170;
  519. /* Calculate adaptive vector */
  520. cb_ptr += subfrm->ad_cb_gain * 20;
  521. for (i = 0; i < SUBFRAME_LEN; i++) {
  522. sum = dot_product(residual + i, cb_ptr, PITCH_ORDER);
  523. vector[i] = av_sat_dadd32(1 << 15, sum) >> 16;
  524. }
  525. }
  526. /**
  527. * Estimate maximum auto-correlation around pitch lag.
  528. *
  529. * @param buf buffer with offset applied
  530. * @param offset offset of the excitation vector
  531. * @param ccr_max pointer to the maximum auto-correlation
  532. * @param pitch_lag decoded pitch lag
  533. * @param length length of autocorrelation
  534. * @param dir forward lag(1) / backward lag(-1)
  535. */
  536. static int autocorr_max(const int16_t *buf, int offset, int *ccr_max,
  537. int pitch_lag, int length, int dir)
  538. {
  539. int limit, ccr, lag = 0;
  540. int i;
  541. pitch_lag = FFMIN(PITCH_MAX - 3, pitch_lag);
  542. if (dir > 0)
  543. limit = FFMIN(FRAME_LEN + PITCH_MAX - offset - length, pitch_lag + 3);
  544. else
  545. limit = pitch_lag + 3;
  546. for (i = pitch_lag - 3; i <= limit; i++) {
  547. ccr = dot_product(buf, buf + dir * i, length);
  548. if (ccr > *ccr_max) {
  549. *ccr_max = ccr;
  550. lag = i;
  551. }
  552. }
  553. return lag;
  554. }
  555. /**
  556. * Calculate pitch postfilter optimal and scaling gains.
  557. *
  558. * @param lag pitch postfilter forward/backward lag
  559. * @param ppf pitch postfilter parameters
  560. * @param cur_rate current bitrate
  561. * @param tgt_eng target energy
  562. * @param ccr cross-correlation
  563. * @param res_eng residual energy
  564. */
  565. static void comp_ppf_gains(int lag, PPFParam *ppf, enum Rate cur_rate,
  566. int tgt_eng, int ccr, int res_eng)
  567. {
  568. int pf_residual; /* square of postfiltered residual */
  569. int temp1, temp2;
  570. ppf->index = lag;
  571. temp1 = tgt_eng * res_eng >> 1;
  572. temp2 = ccr * ccr << 1;
  573. if (temp2 > temp1) {
  574. if (ccr >= res_eng) {
  575. ppf->opt_gain = ppf_gain_weight[cur_rate];
  576. } else {
  577. ppf->opt_gain = (ccr << 15) / res_eng *
  578. ppf_gain_weight[cur_rate] >> 15;
  579. }
  580. /* pf_res^2 = tgt_eng + 2*ccr*gain + res_eng*gain^2 */
  581. temp1 = (tgt_eng << 15) + (ccr * ppf->opt_gain << 1);
  582. temp2 = (ppf->opt_gain * ppf->opt_gain >> 15) * res_eng;
  583. pf_residual = av_sat_add32(temp1, temp2 + (1 << 15)) >> 16;
  584. if (tgt_eng >= pf_residual << 1) {
  585. temp1 = 0x7fff;
  586. } else {
  587. temp1 = (tgt_eng << 14) / pf_residual;
  588. }
  589. /* scaling_gain = sqrt(tgt_eng/pf_res^2) */
  590. ppf->sc_gain = square_root(temp1 << 16);
  591. } else {
  592. ppf->opt_gain = 0;
  593. ppf->sc_gain = 0x7fff;
  594. }
  595. ppf->opt_gain = av_clip_int16(ppf->opt_gain * ppf->sc_gain >> 15);
  596. }
  597. /**
  598. * Calculate pitch postfilter parameters.
  599. *
  600. * @param p the context
  601. * @param offset offset of the excitation vector
  602. * @param pitch_lag decoded pitch lag
  603. * @param ppf pitch postfilter parameters
  604. * @param cur_rate current bitrate
  605. */
  606. static void comp_ppf_coeff(G723_1_Context *p, int offset, int pitch_lag,
  607. PPFParam *ppf, enum Rate cur_rate)
  608. {
  609. int16_t scale;
  610. int i;
  611. int temp1, temp2;
  612. /*
  613. * 0 - target energy
  614. * 1 - forward cross-correlation
  615. * 2 - forward residual energy
  616. * 3 - backward cross-correlation
  617. * 4 - backward residual energy
  618. */
  619. int energy[5] = {0, 0, 0, 0, 0};
  620. int16_t *buf = p->audio + LPC_ORDER + offset;
  621. int fwd_lag = autocorr_max(buf, offset, &energy[1], pitch_lag,
  622. SUBFRAME_LEN, 1);
  623. int back_lag = autocorr_max(buf, offset, &energy[3], pitch_lag,
  624. SUBFRAME_LEN, -1);
  625. ppf->index = 0;
  626. ppf->opt_gain = 0;
  627. ppf->sc_gain = 0x7fff;
  628. /* Case 0, Section 3.6 */
  629. if (!back_lag && !fwd_lag)
  630. return;
  631. /* Compute target energy */
  632. energy[0] = dot_product(buf, buf, SUBFRAME_LEN);
  633. /* Compute forward residual energy */
  634. if (fwd_lag)
  635. energy[2] = dot_product(buf + fwd_lag, buf + fwd_lag, SUBFRAME_LEN);
  636. /* Compute backward residual energy */
  637. if (back_lag)
  638. energy[4] = dot_product(buf - back_lag, buf - back_lag, SUBFRAME_LEN);
  639. /* Normalize and shorten */
  640. temp1 = 0;
  641. for (i = 0; i < 5; i++)
  642. temp1 = FFMAX(energy[i], temp1);
  643. scale = normalize_bits(temp1, 31);
  644. for (i = 0; i < 5; i++)
  645. energy[i] = (energy[i] << scale) >> 16;
  646. if (fwd_lag && !back_lag) { /* Case 1 */
  647. comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
  648. energy[2]);
  649. } else if (!fwd_lag) { /* Case 2 */
  650. comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
  651. energy[4]);
  652. } else { /* Case 3 */
  653. /*
  654. * Select the largest of energy[1]^2/energy[2]
  655. * and energy[3]^2/energy[4]
  656. */
  657. temp1 = energy[4] * ((energy[1] * energy[1] + (1 << 14)) >> 15);
  658. temp2 = energy[2] * ((energy[3] * energy[3] + (1 << 14)) >> 15);
  659. if (temp1 >= temp2) {
  660. comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
  661. energy[2]);
  662. } else {
  663. comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
  664. energy[4]);
  665. }
  666. }
  667. }
  668. /**
  669. * Classify frames as voiced/unvoiced.
  670. *
  671. * @param p the context
  672. * @param pitch_lag decoded pitch_lag
  673. * @param exc_eng excitation energy estimation
  674. * @param scale scaling factor of exc_eng
  675. *
  676. * @return residual interpolation index if voiced, 0 otherwise
  677. */
  678. static int comp_interp_index(G723_1_Context *p, int pitch_lag,
  679. int *exc_eng, int *scale)
  680. {
  681. int offset = PITCH_MAX + 2 * SUBFRAME_LEN;
  682. int16_t *buf = p->audio + LPC_ORDER;
  683. int index, ccr, tgt_eng, best_eng, temp;
  684. *scale = scale_vector(buf, p->excitation, FRAME_LEN + PITCH_MAX);
  685. buf += offset;
  686. /* Compute maximum backward cross-correlation */
  687. ccr = 0;
  688. index = autocorr_max(buf, offset, &ccr, pitch_lag, SUBFRAME_LEN * 2, -1);
  689. ccr = av_sat_add32(ccr, 1 << 15) >> 16;
  690. /* Compute target energy */
  691. tgt_eng = dot_product(buf, buf, SUBFRAME_LEN * 2);
  692. *exc_eng = av_sat_add32(tgt_eng, 1 << 15) >> 16;
  693. if (ccr <= 0)
  694. return 0;
  695. /* Compute best energy */
  696. best_eng = dot_product(buf - index, buf - index, SUBFRAME_LEN * 2);
  697. best_eng = av_sat_add32(best_eng, 1 << 15) >> 16;
  698. temp = best_eng * *exc_eng >> 3;
  699. if (temp < ccr * ccr)
  700. return index;
  701. else
  702. return 0;
  703. }
  704. /**
  705. * Peform residual interpolation based on frame classification.
  706. *
  707. * @param buf decoded excitation vector
  708. * @param out output vector
  709. * @param lag decoded pitch lag
  710. * @param gain interpolated gain
  711. * @param rseed seed for random number generator
  712. */
  713. static void residual_interp(int16_t *buf, int16_t *out, int lag,
  714. int gain, int *rseed)
  715. {
  716. int i;
  717. if (lag) { /* Voiced */
  718. int16_t *vector_ptr = buf + PITCH_MAX;
  719. /* Attenuate */
  720. for (i = 0; i < lag; i++)
  721. out[i] = vector_ptr[i - lag] * 3 >> 2;
  722. av_memcpy_backptr((uint8_t*)(out + lag), lag * sizeof(*out),
  723. (FRAME_LEN - lag) * sizeof(*out));
  724. } else { /* Unvoiced */
  725. for (i = 0; i < FRAME_LEN; i++) {
  726. *rseed = *rseed * 521 + 259;
  727. out[i] = gain * *rseed >> 15;
  728. }
  729. memset(buf, 0, (FRAME_LEN + PITCH_MAX) * sizeof(*buf));
  730. }
  731. }
  732. /**
  733. * Perform IIR filtering.
  734. *
  735. * @param fir_coef FIR coefficients
  736. * @param iir_coef IIR coefficients
  737. * @param src source vector
  738. * @param dest destination vector
  739. */
  740. static inline void iir_filter(int16_t *fir_coef, int16_t *iir_coef,
  741. int16_t *src, int *dest)
  742. {
  743. int m, n;
  744. for (m = 0; m < SUBFRAME_LEN; m++) {
  745. int64_t filter = 0;
  746. for (n = 1; n <= LPC_ORDER; n++) {
  747. filter -= fir_coef[n - 1] * src[m - n] -
  748. iir_coef[n - 1] * (dest[m - n] >> 16);
  749. }
  750. dest[m] = av_clipl_int32((src[m] << 16) + (filter << 3) + (1 << 15));
  751. }
  752. }
  753. /**
  754. * Adjust gain of postfiltered signal.
  755. *
  756. * @param p the context
  757. * @param buf postfiltered output vector
  758. * @param energy input energy coefficient
  759. */
  760. static void gain_scale(G723_1_Context *p, int16_t * buf, int energy)
  761. {
  762. int num, denom, gain, bits1, bits2;
  763. int i;
  764. num = energy;
  765. denom = 0;
  766. for (i = 0; i < SUBFRAME_LEN; i++) {
  767. int temp = buf[i] >> 2;
  768. temp *= temp;
  769. denom = av_sat_dadd32(denom, temp);
  770. }
  771. if (num && denom) {
  772. bits1 = normalize_bits(num, 31);
  773. bits2 = normalize_bits(denom, 31);
  774. num = num << bits1 >> 1;
  775. denom <<= bits2;
  776. bits2 = 5 + bits1 - bits2;
  777. bits2 = FFMAX(0, bits2);
  778. gain = (num >> 1) / (denom >> 16);
  779. gain = square_root(gain << 16 >> bits2);
  780. } else {
  781. gain = 1 << 12;
  782. }
  783. for (i = 0; i < SUBFRAME_LEN; i++) {
  784. p->pf_gain = (15 * p->pf_gain + gain + (1 << 3)) >> 4;
  785. buf[i] = av_clip_int16((buf[i] * (p->pf_gain + (p->pf_gain >> 4)) +
  786. (1 << 10)) >> 11);
  787. }
  788. }
  789. /**
  790. * Perform formant filtering.
  791. *
  792. * @param p the context
  793. * @param lpc quantized lpc coefficients
  794. * @param buf input buffer
  795. * @param dst output buffer
  796. */
  797. static void formant_postfilter(G723_1_Context *p, int16_t *lpc,
  798. int16_t *buf, int16_t *dst)
  799. {
  800. int16_t filter_coef[2][LPC_ORDER];
  801. int filter_signal[LPC_ORDER + FRAME_LEN], *signal_ptr;
  802. int i, j, k;
  803. memcpy(buf, p->fir_mem, LPC_ORDER * sizeof(*buf));
  804. memcpy(filter_signal, p->iir_mem, LPC_ORDER * sizeof(*filter_signal));
  805. for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
  806. for (k = 0; k < LPC_ORDER; k++) {
  807. filter_coef[0][k] = (-lpc[k] * postfilter_tbl[0][k] +
  808. (1 << 14)) >> 15;
  809. filter_coef[1][k] = (-lpc[k] * postfilter_tbl[1][k] +
  810. (1 << 14)) >> 15;
  811. }
  812. iir_filter(filter_coef[0], filter_coef[1], buf + i,
  813. filter_signal + i);
  814. lpc += LPC_ORDER;
  815. }
  816. memcpy(p->fir_mem, buf + FRAME_LEN, LPC_ORDER * sizeof(*p->fir_mem));
  817. memcpy(p->iir_mem, filter_signal + FRAME_LEN,
  818. LPC_ORDER * sizeof(*p->iir_mem));
  819. buf += LPC_ORDER;
  820. signal_ptr = filter_signal + LPC_ORDER;
  821. for (i = 0; i < SUBFRAMES; i++) {
  822. int temp;
  823. int auto_corr[2];
  824. int scale, energy;
  825. /* Normalize */
  826. scale = scale_vector(dst, buf, SUBFRAME_LEN);
  827. /* Compute auto correlation coefficients */
  828. auto_corr[0] = dot_product(dst, dst + 1, SUBFRAME_LEN - 1);
  829. auto_corr[1] = dot_product(dst, dst, SUBFRAME_LEN);
  830. /* Compute reflection coefficient */
  831. temp = auto_corr[1] >> 16;
  832. if (temp) {
  833. temp = (auto_corr[0] >> 2) / temp;
  834. }
  835. p->reflection_coef = (3 * p->reflection_coef + temp + 2) >> 2;
  836. temp = -p->reflection_coef >> 1 & ~3;
  837. /* Compensation filter */
  838. for (j = 0; j < SUBFRAME_LEN; j++) {
  839. dst[j] = av_sat_dadd32(signal_ptr[j],
  840. (signal_ptr[j - 1] >> 16) * temp) >> 16;
  841. }
  842. /* Compute normalized signal energy */
  843. temp = 2 * scale + 4;
  844. if (temp < 0) {
  845. energy = av_clipl_int32((int64_t)auto_corr[1] << -temp);
  846. } else
  847. energy = auto_corr[1] >> temp;
  848. gain_scale(p, dst, energy);
  849. buf += SUBFRAME_LEN;
  850. signal_ptr += SUBFRAME_LEN;
  851. dst += SUBFRAME_LEN;
  852. }
  853. }
  854. static int sid_gain_to_lsp_index(int gain)
  855. {
  856. if (gain < 0x10)
  857. return gain << 6;
  858. else if (gain < 0x20)
  859. return gain - 8 << 7;
  860. else
  861. return gain - 20 << 8;
  862. }
  863. static inline int cng_rand(int *state, int base)
  864. {
  865. *state = (*state * 521 + 259) & 0xFFFF;
  866. return (*state & 0x7FFF) * base >> 15;
  867. }
  868. static int estimate_sid_gain(G723_1_Context *p)
  869. {
  870. int i, shift, seg, seg2, t, val, val_add, x, y;
  871. shift = 16 - p->cur_gain * 2;
  872. if (shift > 0)
  873. t = p->sid_gain << shift;
  874. else
  875. t = p->sid_gain >> -shift;
  876. x = t * cng_filt[0] >> 16;
  877. if (x >= cng_bseg[2])
  878. return 0x3F;
  879. if (x >= cng_bseg[1]) {
  880. shift = 4;
  881. seg = 3;
  882. } else {
  883. shift = 3;
  884. seg = (x >= cng_bseg[0]);
  885. }
  886. seg2 = FFMIN(seg, 3);
  887. val = 1 << shift;
  888. val_add = val >> 1;
  889. for (i = 0; i < shift; i++) {
  890. t = seg * 32 + (val << seg2);
  891. t *= t;
  892. if (x >= t)
  893. val += val_add;
  894. else
  895. val -= val_add;
  896. val_add >>= 1;
  897. }
  898. t = seg * 32 + (val << seg2);
  899. y = t * t - x;
  900. if (y <= 0) {
  901. t = seg * 32 + (val + 1 << seg2);
  902. t = t * t - x;
  903. val = (seg2 - 1 << 4) + val;
  904. if (t >= y)
  905. val++;
  906. } else {
  907. t = seg * 32 + (val - 1 << seg2);
  908. t = t * t - x;
  909. val = (seg2 - 1 << 4) + val;
  910. if (t >= y)
  911. val--;
  912. }
  913. return val;
  914. }
  915. static void generate_noise(G723_1_Context *p)
  916. {
  917. int i, j, idx, t;
  918. int off[SUBFRAMES];
  919. int signs[SUBFRAMES / 2 * 11], pos[SUBFRAMES / 2 * 11];
  920. int tmp[SUBFRAME_LEN * 2];
  921. int16_t *vector_ptr;
  922. int64_t sum;
  923. int b0, c, delta, x, shift;
  924. p->pitch_lag[0] = cng_rand(&p->cng_random_seed, 21) + 123;
  925. p->pitch_lag[1] = cng_rand(&p->cng_random_seed, 19) + 123;
  926. for (i = 0; i < SUBFRAMES; i++) {
  927. p->subframe[i].ad_cb_gain = cng_rand(&p->cng_random_seed, 50) + 1;
  928. p->subframe[i].ad_cb_lag = cng_adaptive_cb_lag[i];
  929. }
  930. for (i = 0; i < SUBFRAMES / 2; i++) {
  931. t = cng_rand(&p->cng_random_seed, 1 << 13);
  932. off[i * 2] = t & 1;
  933. off[i * 2 + 1] = ((t >> 1) & 1) + SUBFRAME_LEN;
  934. t >>= 2;
  935. for (j = 0; j < 11; j++) {
  936. signs[i * 11 + j] = (t & 1) * 2 - 1 << 14;
  937. t >>= 1;
  938. }
  939. }
  940. idx = 0;
  941. for (i = 0; i < SUBFRAMES; i++) {
  942. for (j = 0; j < SUBFRAME_LEN / 2; j++)
  943. tmp[j] = j;
  944. t = SUBFRAME_LEN / 2;
  945. for (j = 0; j < pulses[i]; j++, idx++) {
  946. int idx2 = cng_rand(&p->cng_random_seed, t);
  947. pos[idx] = tmp[idx2] * 2 + off[i];
  948. tmp[idx2] = tmp[--t];
  949. }
  950. }
  951. vector_ptr = p->audio + LPC_ORDER;
  952. memcpy(vector_ptr, p->prev_excitation,
  953. PITCH_MAX * sizeof(*p->excitation));
  954. for (i = 0; i < SUBFRAMES; i += 2) {
  955. gen_acb_excitation(vector_ptr, vector_ptr,
  956. p->pitch_lag[i >> 1], &p->subframe[i],
  957. p->cur_rate);
  958. gen_acb_excitation(vector_ptr + SUBFRAME_LEN,
  959. vector_ptr + SUBFRAME_LEN,
  960. p->pitch_lag[i >> 1], &p->subframe[i + 1],
  961. p->cur_rate);
  962. t = 0;
  963. for (j = 0; j < SUBFRAME_LEN * 2; j++)
  964. t |= FFABS(vector_ptr[j]);
  965. t = FFMIN(t, 0x7FFF);
  966. if (!t) {
  967. shift = 0;
  968. } else {
  969. shift = -10 + av_log2(t);
  970. if (shift < -2)
  971. shift = -2;
  972. }
  973. sum = 0;
  974. if (shift < 0) {
  975. for (j = 0; j < SUBFRAME_LEN * 2; j++) {
  976. t = vector_ptr[j] << -shift;
  977. sum += t * t;
  978. tmp[j] = t;
  979. }
  980. } else {
  981. for (j = 0; j < SUBFRAME_LEN * 2; j++) {
  982. t = vector_ptr[j] >> shift;
  983. sum += t * t;
  984. tmp[j] = t;
  985. }
  986. }
  987. b0 = 0;
  988. for (j = 0; j < 11; j++)
  989. b0 += tmp[pos[(i / 2) * 11 + j]] * signs[(i / 2) * 11 + j];
  990. b0 = b0 * 2 * 2979LL + (1 << 29) >> 30; // approximated division by 11
  991. c = p->cur_gain * (p->cur_gain * SUBFRAME_LEN >> 5);
  992. if (shift * 2 + 3 >= 0)
  993. c >>= shift * 2 + 3;
  994. else
  995. c <<= -(shift * 2 + 3);
  996. c = (av_clipl_int32(sum << 1) - c) * 2979LL >> 15;
  997. delta = b0 * b0 * 2 - c;
  998. if (delta <= 0) {
  999. x = -b0;
  1000. } else {
  1001. delta = square_root(delta);
  1002. x = delta - b0;
  1003. t = delta + b0;
  1004. if (FFABS(t) < FFABS(x))
  1005. x = -t;
  1006. }
  1007. shift++;
  1008. if (shift < 0)
  1009. x >>= -shift;
  1010. else
  1011. x <<= shift;
  1012. x = av_clip(x, -10000, 10000);
  1013. for (j = 0; j < 11; j++) {
  1014. idx = (i / 2) * 11 + j;
  1015. vector_ptr[pos[idx]] = av_clip_int16(vector_ptr[pos[idx]] +
  1016. (x * signs[idx] >> 15));
  1017. }
  1018. /* copy decoded data to serve as a history for the next decoded subframes */
  1019. memcpy(vector_ptr + PITCH_MAX, vector_ptr,
  1020. sizeof(*vector_ptr) * SUBFRAME_LEN * 2);
  1021. vector_ptr += SUBFRAME_LEN * 2;
  1022. }
  1023. /* Save the excitation for the next frame */
  1024. memcpy(p->prev_excitation, p->audio + LPC_ORDER + FRAME_LEN,
  1025. PITCH_MAX * sizeof(*p->excitation));
  1026. }
  1027. static int g723_1_decode_frame(AVCodecContext *avctx, void *data,
  1028. int *got_frame_ptr, AVPacket *avpkt)
  1029. {
  1030. G723_1_Context *p = avctx->priv_data;
  1031. const uint8_t *buf = avpkt->data;
  1032. int buf_size = avpkt->size;
  1033. int dec_mode = buf[0] & 3;
  1034. PPFParam ppf[SUBFRAMES];
  1035. int16_t cur_lsp[LPC_ORDER];
  1036. int16_t lpc[SUBFRAMES * LPC_ORDER];
  1037. int16_t acb_vector[SUBFRAME_LEN];
  1038. int16_t *out;
  1039. int bad_frame = 0, i, j, ret;
  1040. int16_t *audio = p->audio;
  1041. if (buf_size < frame_size[dec_mode]) {
  1042. if (buf_size)
  1043. av_log(avctx, AV_LOG_WARNING,
  1044. "Expected %d bytes, got %d - skipping packet\n",
  1045. frame_size[dec_mode], buf_size);
  1046. *got_frame_ptr = 0;
  1047. return buf_size;
  1048. }
  1049. if (unpack_bitstream(p, buf, buf_size) < 0) {
  1050. bad_frame = 1;
  1051. if (p->past_frame_type == ACTIVE_FRAME)
  1052. p->cur_frame_type = ACTIVE_FRAME;
  1053. else
  1054. p->cur_frame_type = UNTRANSMITTED_FRAME;
  1055. }
  1056. p->frame.nb_samples = FRAME_LEN;
  1057. if ((ret = avctx->get_buffer(avctx, &p->frame)) < 0) {
  1058. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  1059. return ret;
  1060. }
  1061. out = (int16_t *)p->frame.data[0];
  1062. if (p->cur_frame_type == ACTIVE_FRAME) {
  1063. if (!bad_frame)
  1064. p->erased_frames = 0;
  1065. else if (p->erased_frames != 3)
  1066. p->erased_frames++;
  1067. inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, bad_frame);
  1068. lsp_interpolate(lpc, cur_lsp, p->prev_lsp);
  1069. /* Save the lsp_vector for the next frame */
  1070. memcpy(p->prev_lsp, cur_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
  1071. /* Generate the excitation for the frame */
  1072. memcpy(p->excitation, p->prev_excitation,
  1073. PITCH_MAX * sizeof(*p->excitation));
  1074. if (!p->erased_frames) {
  1075. int16_t *vector_ptr = p->excitation + PITCH_MAX;
  1076. /* Update interpolation gain memory */
  1077. p->interp_gain = fixed_cb_gain[(p->subframe[2].amp_index +
  1078. p->subframe[3].amp_index) >> 1];
  1079. for (i = 0; i < SUBFRAMES; i++) {
  1080. gen_fcb_excitation(vector_ptr, &p->subframe[i], p->cur_rate,
  1081. p->pitch_lag[i >> 1], i);
  1082. gen_acb_excitation(acb_vector, &p->excitation[SUBFRAME_LEN * i],
  1083. p->pitch_lag[i >> 1], &p->subframe[i],
  1084. p->cur_rate);
  1085. /* Get the total excitation */
  1086. for (j = 0; j < SUBFRAME_LEN; j++) {
  1087. int v = av_clip_int16(vector_ptr[j] << 1);
  1088. vector_ptr[j] = av_clip_int16(v + acb_vector[j]);
  1089. }
  1090. vector_ptr += SUBFRAME_LEN;
  1091. }
  1092. vector_ptr = p->excitation + PITCH_MAX;
  1093. p->interp_index = comp_interp_index(p, p->pitch_lag[1],
  1094. &p->sid_gain, &p->cur_gain);
  1095. /* Peform pitch postfiltering */
  1096. if (p->postfilter) {
  1097. i = PITCH_MAX;
  1098. for (j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
  1099. comp_ppf_coeff(p, i, p->pitch_lag[j >> 1],
  1100. ppf + j, p->cur_rate);
  1101. for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
  1102. ff_acelp_weighted_vector_sum(p->audio + LPC_ORDER + i,
  1103. vector_ptr + i,
  1104. vector_ptr + i + ppf[j].index,
  1105. ppf[j].sc_gain,
  1106. ppf[j].opt_gain,
  1107. 1 << 14, 15, SUBFRAME_LEN);
  1108. } else {
  1109. audio = vector_ptr - LPC_ORDER;
  1110. }
  1111. /* Save the excitation for the next frame */
  1112. memcpy(p->prev_excitation, p->excitation + FRAME_LEN,
  1113. PITCH_MAX * sizeof(*p->excitation));
  1114. } else {
  1115. p->interp_gain = (p->interp_gain * 3 + 2) >> 2;
  1116. if (p->erased_frames == 3) {
  1117. /* Mute output */
  1118. memset(p->excitation, 0,
  1119. (FRAME_LEN + PITCH_MAX) * sizeof(*p->excitation));
  1120. memset(p->prev_excitation, 0,
  1121. PITCH_MAX * sizeof(*p->excitation));
  1122. memset(p->frame.data[0], 0,
  1123. (FRAME_LEN + LPC_ORDER) * sizeof(int16_t));
  1124. } else {
  1125. int16_t *buf = p->audio + LPC_ORDER;
  1126. /* Regenerate frame */
  1127. residual_interp(p->excitation, buf, p->interp_index,
  1128. p->interp_gain, &p->random_seed);
  1129. /* Save the excitation for the next frame */
  1130. memcpy(p->prev_excitation, buf + (FRAME_LEN - PITCH_MAX),
  1131. PITCH_MAX * sizeof(*p->excitation));
  1132. }
  1133. }
  1134. p->cng_random_seed = CNG_RANDOM_SEED;
  1135. } else {
  1136. if (p->cur_frame_type == SID_FRAME) {
  1137. p->sid_gain = sid_gain_to_lsp_index(p->subframe[0].amp_index);
  1138. inverse_quant(p->sid_lsp, p->prev_lsp, p->lsp_index, 0);
  1139. } else if (p->past_frame_type == ACTIVE_FRAME) {
  1140. p->sid_gain = estimate_sid_gain(p);
  1141. }
  1142. if (p->past_frame_type == ACTIVE_FRAME)
  1143. p->cur_gain = p->sid_gain;
  1144. else
  1145. p->cur_gain = (p->cur_gain * 7 + p->sid_gain) >> 3;
  1146. generate_noise(p);
  1147. lsp_interpolate(lpc, p->sid_lsp, p->prev_lsp);
  1148. /* Save the lsp_vector for the next frame */
  1149. memcpy(p->prev_lsp, p->sid_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
  1150. }
  1151. p->past_frame_type = p->cur_frame_type;
  1152. memcpy(p->audio, p->synth_mem, LPC_ORDER * sizeof(*p->audio));
  1153. for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
  1154. ff_celp_lp_synthesis_filter(p->audio + i, &lpc[j * LPC_ORDER],
  1155. audio + i, SUBFRAME_LEN, LPC_ORDER,
  1156. 0, 1, 1 << 12);
  1157. memcpy(p->synth_mem, p->audio + FRAME_LEN, LPC_ORDER * sizeof(*p->audio));
  1158. if (p->postfilter) {
  1159. formant_postfilter(p, lpc, p->audio, out);
  1160. } else { // if output is not postfiltered it should be scaled by 2
  1161. for (i = 0; i < FRAME_LEN; i++)
  1162. out[i] = av_clip_int16(p->audio[LPC_ORDER + i] << 1);
  1163. }
  1164. *got_frame_ptr = 1;
  1165. *(AVFrame *)data = p->frame;
  1166. return frame_size[dec_mode];
  1167. }
  1168. #define OFFSET(x) offsetof(G723_1_Context, x)
  1169. #define AD AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1170. static const AVOption options[] = {
  1171. { "postfilter", "postfilter on/off", OFFSET(postfilter), AV_OPT_TYPE_INT,
  1172. { .i64 = 1 }, 0, 1, AD },
  1173. { NULL }
  1174. };
  1175. static const AVClass g723_1dec_class = {
  1176. .class_name = "G.723.1 decoder",
  1177. .item_name = av_default_item_name,
  1178. .option = options,
  1179. .version = LIBAVUTIL_VERSION_INT,
  1180. };
  1181. AVCodec ff_g723_1_decoder = {
  1182. .name = "g723_1",
  1183. .type = AVMEDIA_TYPE_AUDIO,
  1184. .id = AV_CODEC_ID_G723_1,
  1185. .priv_data_size = sizeof(G723_1_Context),
  1186. .init = g723_1_decode_init,
  1187. .decode = g723_1_decode_frame,
  1188. .long_name = NULL_IF_CONFIG_SMALL("G.723.1"),
  1189. .capabilities = CODEC_CAP_SUBFRAMES,
  1190. .priv_class = &g723_1dec_class,
  1191. };