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.

1071 lines
34KB

  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. #include "avcodec.h"
  27. #define ALT_BITSTREAM_READER_LE
  28. #include "get_bits.h"
  29. #include "acelp_vectors.h"
  30. #include "celp_filters.h"
  31. #include "celp_math.h"
  32. #include "lsp.h"
  33. #include "libavutil/lzo.h"
  34. #include "g723_1_data.h"
  35. typedef struct g723_1_context {
  36. G723_1_Subframe subframe[4];
  37. FrameType cur_frame_type;
  38. FrameType past_frame_type;
  39. Rate cur_rate;
  40. uint8_t lsp_index[LSP_BANDS];
  41. int pitch_lag[2];
  42. int erased_frames;
  43. int16_t prev_lsp[LPC_ORDER];
  44. int16_t prev_excitation[PITCH_MAX];
  45. int16_t excitation[PITCH_MAX + FRAME_LEN];
  46. int16_t synth_mem[LPC_ORDER];
  47. int16_t fir_mem[LPC_ORDER];
  48. int iir_mem[LPC_ORDER];
  49. int random_seed;
  50. int interp_index;
  51. int interp_gain;
  52. int sid_gain;
  53. int cur_gain;
  54. int reflection_coef;
  55. int pf_gain; ///< formant postfilter
  56. ///< gain scaling unit memory
  57. } G723_1_Context;
  58. static av_cold int g723_1_decode_init(AVCodecContext *avctx)
  59. {
  60. G723_1_Context *p = avctx->priv_data;
  61. avctx->sample_fmt = SAMPLE_FMT_S16;
  62. p->pf_gain = 1 << 12;
  63. memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(int16_t));
  64. return 0;
  65. }
  66. /**
  67. * Unpack the frame into parameters.
  68. *
  69. * @param p the context
  70. * @param buf pointer to the input buffer
  71. * @param buf_size size of the input buffer
  72. */
  73. static int unpack_bitstream(G723_1_Context *p, const uint8_t *buf,
  74. int buf_size)
  75. {
  76. GetBitContext gb;
  77. int ad_cb_len;
  78. int temp, info_bits, i;
  79. init_get_bits(&gb, buf, buf_size * 8);
  80. /* Extract frame type and rate info */
  81. info_bits = get_bits(&gb, 2);
  82. if (info_bits == 3) {
  83. p->cur_frame_type = UntransmittedFrame;
  84. return 0;
  85. }
  86. /* Extract 24 bit lsp indices, 8 bit for each band */
  87. p->lsp_index[2] = get_bits(&gb, 8);
  88. p->lsp_index[1] = get_bits(&gb, 8);
  89. p->lsp_index[0] = get_bits(&gb, 8);
  90. if (info_bits == 2) {
  91. p->cur_frame_type = SIDFrame;
  92. p->subframe[0].amp_index = get_bits(&gb, 6);
  93. return 0;
  94. }
  95. /* Extract the info common to both rates */
  96. p->cur_rate = info_bits ? Rate5k3 : Rate6k3;
  97. p->cur_frame_type = ActiveFrame;
  98. p->pitch_lag[0] = get_bits(&gb, 7);
  99. if (p->pitch_lag[0] > 123) /* test if forbidden code */
  100. return -1;
  101. p->pitch_lag[0] += PITCH_MIN;
  102. p->subframe[1].ad_cb_lag = get_bits(&gb, 2);
  103. p->pitch_lag[1] = get_bits(&gb, 7);
  104. if (p->pitch_lag[1] > 123)
  105. return -1;
  106. p->pitch_lag[1] += PITCH_MIN;
  107. p->subframe[3].ad_cb_lag = get_bits(&gb, 2);
  108. p->subframe[0].ad_cb_lag = 1;
  109. p->subframe[2].ad_cb_lag = 1;
  110. for (i = 0; i < SUBFRAMES; i++) {
  111. /* Extract combined gain */
  112. temp = get_bits(&gb, 12);
  113. ad_cb_len = 170;
  114. p->subframe[i].dirac_train = 0;
  115. if (p->cur_rate == Rate6k3 && p->pitch_lag[i >> 1] < SUBFRAME_LEN - 2) {
  116. p->subframe[i].dirac_train = temp >> 11;
  117. temp &= 0x7ff;
  118. ad_cb_len = 85;
  119. }
  120. p->subframe[i].ad_cb_gain = FASTDIV(temp, GAIN_LEVELS);
  121. if (p->subframe[i].ad_cb_gain < ad_cb_len) {
  122. p->subframe[i].amp_index = temp - p->subframe[i].ad_cb_gain *
  123. GAIN_LEVELS;
  124. } else {
  125. return -1;
  126. }
  127. }
  128. p->subframe[0].grid_index = get_bits1(&gb);
  129. p->subframe[1].grid_index = get_bits1(&gb);
  130. p->subframe[2].grid_index = get_bits1(&gb);
  131. p->subframe[3].grid_index = get_bits1(&gb);
  132. if (p->cur_rate == Rate6k3) {
  133. skip_bits1(&gb); /* skip reserved bit */
  134. /* Compute pulse_pos index using the 13-bit combined position index */
  135. temp = get_bits(&gb, 13);
  136. p->subframe[0].pulse_pos = temp / 810;
  137. temp -= p->subframe[0].pulse_pos * 810;
  138. p->subframe[1].pulse_pos = FASTDIV(temp, 90);
  139. temp -= p->subframe[1].pulse_pos * 90;
  140. p->subframe[2].pulse_pos = FASTDIV(temp, 9);
  141. p->subframe[3].pulse_pos = temp - p->subframe[2].pulse_pos * 9;
  142. p->subframe[0].pulse_pos = (p->subframe[0].pulse_pos << 16) +
  143. get_bits(&gb, 16);
  144. p->subframe[1].pulse_pos = (p->subframe[1].pulse_pos << 14) +
  145. get_bits(&gb, 14);
  146. p->subframe[2].pulse_pos = (p->subframe[2].pulse_pos << 16) +
  147. get_bits(&gb, 16);
  148. p->subframe[3].pulse_pos = (p->subframe[3].pulse_pos << 14) +
  149. get_bits(&gb, 14);
  150. p->subframe[0].pulse_sign = get_bits(&gb, 6);
  151. p->subframe[1].pulse_sign = get_bits(&gb, 5);
  152. p->subframe[2].pulse_sign = get_bits(&gb, 6);
  153. p->subframe[3].pulse_sign = get_bits(&gb, 5);
  154. } else { /* Rate5k3 */
  155. p->subframe[0].pulse_pos = get_bits(&gb, 12);
  156. p->subframe[1].pulse_pos = get_bits(&gb, 12);
  157. p->subframe[2].pulse_pos = get_bits(&gb, 12);
  158. p->subframe[3].pulse_pos = get_bits(&gb, 12);
  159. p->subframe[0].pulse_sign = get_bits(&gb, 4);
  160. p->subframe[1].pulse_sign = get_bits(&gb, 4);
  161. p->subframe[2].pulse_sign = get_bits(&gb, 4);
  162. p->subframe[3].pulse_sign = get_bits(&gb, 4);
  163. }
  164. return 0;
  165. }
  166. /**
  167. * Bitexact implementation of sqrt(val/2).
  168. */
  169. static int16_t square_root(int val)
  170. {
  171. return (ff_sqrt(val << 1) >> 1) & (~1);
  172. }
  173. /**
  174. * Calculate the number of left-shifts required for normalizing the input.
  175. *
  176. * @param num input number
  177. * @param width width of the input, 16 bits(0) / 32 bits(1)
  178. */
  179. static int normalize_bits(int num, int width)
  180. {
  181. int i = 0;
  182. int bits = (width) ? 31 : 15;
  183. if (num) {
  184. if (num == -1)
  185. return bits;
  186. if (num < 0)
  187. num = ~num;
  188. i= bits - av_log2(num) - 1;
  189. i= FFMAX(i, 0);
  190. }
  191. return i;
  192. }
  193. /**
  194. * Scale vector contents based on the largest of their absolutes.
  195. */
  196. static int scale_vector(int16_t *vector, int length)
  197. {
  198. int bits, scale, max = 0;
  199. int i;
  200. const int16_t shift_table[16] = {
  201. 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  202. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000, 0x7fff
  203. };
  204. for (i = 0; i < length; i++)
  205. max = FFMAX(max, FFABS(vector[i]));
  206. bits = normalize_bits(max, 0);
  207. scale = shift_table[bits];
  208. for (i = 0; i < length; i++)
  209. vector[i] = (vector[i] * scale) >> 3;
  210. return bits - 3;
  211. }
  212. /**
  213. * Perform inverse quantization of LSP frequencies.
  214. *
  215. * @param cur_lsp the current LSP vector
  216. * @param prev_lsp the previous LSP vector
  217. * @param lsp_index VQ indices
  218. * @param bad_frame bad frame flag
  219. */
  220. static void inverse_quant(int16_t *cur_lsp, int16_t *prev_lsp,
  221. uint8_t *lsp_index, int bad_frame)
  222. {
  223. int min_dist, pred;
  224. int i, j, temp, stable;
  225. /* Check for frame erasure */
  226. if (!bad_frame) {
  227. min_dist = 0x100;
  228. pred = 12288;
  229. } else {
  230. min_dist = 0x200;
  231. pred = 23552;
  232. lsp_index[0] = lsp_index[1] = lsp_index[2] = 0;
  233. }
  234. /* Get the VQ table entry corresponding to the transmitted index */
  235. cur_lsp[0] = lsp_band0[lsp_index[0]][0];
  236. cur_lsp[1] = lsp_band0[lsp_index[0]][1];
  237. cur_lsp[2] = lsp_band0[lsp_index[0]][2];
  238. cur_lsp[3] = lsp_band1[lsp_index[1]][0];
  239. cur_lsp[4] = lsp_band1[lsp_index[1]][1];
  240. cur_lsp[5] = lsp_band1[lsp_index[1]][2];
  241. cur_lsp[6] = lsp_band2[lsp_index[2]][0];
  242. cur_lsp[7] = lsp_band2[lsp_index[2]][1];
  243. cur_lsp[8] = lsp_band2[lsp_index[2]][2];
  244. cur_lsp[9] = lsp_band2[lsp_index[2]][3];
  245. /* Add predicted vector & DC component to the previously quantized vector */
  246. for (i = 0; i < LPC_ORDER; i++) {
  247. temp = ((prev_lsp[i] - dc_lsp[i]) * pred + (1 << 14)) >> 15;
  248. cur_lsp[i] += dc_lsp[i] + temp;
  249. }
  250. for (i = 0; i < LPC_ORDER; i++) {
  251. cur_lsp[0] = FFMAX(cur_lsp[0], 0x180);
  252. cur_lsp[LPC_ORDER - 1] = FFMIN(cur_lsp[LPC_ORDER - 1], 0x7e00);
  253. /* Stability check */
  254. for (j = 1; j < LPC_ORDER; j++) {
  255. temp = min_dist + cur_lsp[j - 1] - cur_lsp[j];
  256. if (temp > 0) {
  257. temp >>= 1;
  258. cur_lsp[j - 1] -= temp;
  259. cur_lsp[j] += temp;
  260. }
  261. }
  262. stable = 1;
  263. for (j = 1; j < LPC_ORDER; j++) {
  264. temp = cur_lsp[j - 1] + min_dist - cur_lsp[j] - 4;
  265. if (temp > 0) {
  266. stable = 0;
  267. break;
  268. }
  269. }
  270. if (stable)
  271. break;
  272. }
  273. if (!stable)
  274. memcpy(cur_lsp, prev_lsp, LPC_ORDER * sizeof(int16_t));
  275. }
  276. /**
  277. * Bitexact implementation of 2ab scaled by 1/2^16.
  278. *
  279. * @param a 32 bit multiplicand
  280. * @param b 16 bit multiplier
  281. */
  282. #define MULL2(a, b) \
  283. MULL(a,b,15)
  284. /**
  285. * Convert LSP frequencies to LPC coefficients.
  286. *
  287. * @param lpc buffer for LPC coefficients
  288. */
  289. static void lsp2lpc(int16_t *lpc)
  290. {
  291. int f1[LPC_ORDER / 2 + 1];
  292. int f2[LPC_ORDER / 2 + 1];
  293. int i, j;
  294. /* Calculate negative cosine */
  295. for (j = 0; j < LPC_ORDER; j++) {
  296. int index = lpc[j] >> 7;
  297. int offset = lpc[j] & 0x7f;
  298. int64_t temp1 = cos_tab[index] << 16;
  299. int temp2 = (cos_tab[index + 1] - cos_tab[index]) *
  300. ((offset << 8) + 0x80) << 1;
  301. lpc[j] = -(av_clipl_int32(((temp1 + temp2) << 1) + (1 << 15)) >> 16);
  302. }
  303. /*
  304. * Compute sum and difference polynomial coefficients
  305. * (bitexact alternative to lsp2poly() in lsp.c)
  306. */
  307. /* Initialize with values in Q28 */
  308. f1[0] = 1 << 28;
  309. f1[1] = (lpc[0] << 14) + (lpc[2] << 14);
  310. f1[2] = lpc[0] * lpc[2] + (2 << 28);
  311. f2[0] = 1 << 28;
  312. f2[1] = (lpc[1] << 14) + (lpc[3] << 14);
  313. f2[2] = lpc[1] * lpc[3] + (2 << 28);
  314. /*
  315. * Calculate and scale the coefficients by 1/2 in
  316. * each iteration for a final scaling factor of Q25
  317. */
  318. for (i = 2; i < LPC_ORDER / 2; i++) {
  319. f1[i + 1] = f1[i - 1] + MULL2(f1[i], lpc[2 * i]);
  320. f2[i + 1] = f2[i - 1] + MULL2(f2[i], lpc[2 * i + 1]);
  321. for (j = i; j >= 2; j--) {
  322. f1[j] = MULL2(f1[j - 1], lpc[2 * i]) +
  323. (f1[j] >> 1) + (f1[j - 2] >> 1);
  324. f2[j] = MULL2(f2[j - 1], lpc[2 * i + 1]) +
  325. (f2[j] >> 1) + (f2[j - 2] >> 1);
  326. }
  327. f1[0] >>= 1;
  328. f2[0] >>= 1;
  329. f1[1] = ((lpc[2 * i] << 16 >> i) + f1[1]) >> 1;
  330. f2[1] = ((lpc[2 * i + 1] << 16 >> i) + f2[1]) >> 1;
  331. }
  332. /* Convert polynomial coefficients to LPC coefficients */
  333. for (i = 0; i < LPC_ORDER / 2; i++) {
  334. int64_t ff1 = f1[i + 1] + f1[i];
  335. int64_t ff2 = f2[i + 1] - f2[i];
  336. lpc[i] = av_clipl_int32(((ff1 + ff2) << 3) + (1 << 15)) >> 16;
  337. lpc[LPC_ORDER - i - 1] = av_clipl_int32(((ff1 - ff2) << 3) +
  338. (1 << 15)) >> 16;
  339. }
  340. }
  341. /**
  342. * Quantize LSP frequencies by interpolation and convert them to
  343. * the corresponding LPC coefficients.
  344. *
  345. * @param lpc buffer for LPC coefficients
  346. * @param cur_lsp the current LSP vector
  347. * @param prev_lsp the previous LSP vector
  348. */
  349. static void lsp_interpolate(int16_t *lpc, int16_t *cur_lsp, int16_t *prev_lsp)
  350. {
  351. int i;
  352. int16_t *lpc_ptr = lpc;
  353. /* cur_lsp * 0.25 + prev_lsp * 0.75 */
  354. ff_acelp_weighted_vector_sum(lpc, cur_lsp, prev_lsp,
  355. 4096, 12288, 1 << 13, 14, LPC_ORDER);
  356. ff_acelp_weighted_vector_sum(lpc + LPC_ORDER, cur_lsp, prev_lsp,
  357. 8192, 8192, 1 << 13, 14, LPC_ORDER);
  358. ff_acelp_weighted_vector_sum(lpc + 2 * LPC_ORDER, cur_lsp, prev_lsp,
  359. 12288, 4096, 1 << 13, 14, LPC_ORDER);
  360. memcpy(lpc + 3 * LPC_ORDER, cur_lsp, LPC_ORDER * sizeof(int16_t));
  361. for (i = 0; i < SUBFRAMES; i++) {
  362. lsp2lpc(lpc_ptr);
  363. lpc_ptr += LPC_ORDER;
  364. }
  365. }
  366. /**
  367. * Generate a train of dirac functions with period as pitch lag.
  368. */
  369. static void gen_dirac_train(int16_t *buf, int pitch_lag)
  370. {
  371. int16_t vector[SUBFRAME_LEN];
  372. int i, j;
  373. memcpy(vector, buf, SUBFRAME_LEN * sizeof(int16_t));
  374. for (i = pitch_lag; i < SUBFRAME_LEN; i += pitch_lag) {
  375. for (j = 0; j < SUBFRAME_LEN - i; j++)
  376. buf[i + j] += vector[j];
  377. }
  378. }
  379. /**
  380. * Generate fixed codebook excitation vector.
  381. *
  382. * @param vector decoded excitation vector
  383. * @param subfrm current subframe
  384. * @param cur_rate current bitrate
  385. * @param pitch_lag closed loop pitch lag
  386. * @param index current subframe index
  387. */
  388. static void gen_fcb_excitation(int16_t *vector, G723_1_Subframe subfrm,
  389. Rate cur_rate, int pitch_lag, int index)
  390. {
  391. int temp, i, j;
  392. memset(vector, 0, SUBFRAME_LEN * sizeof(int16_t));
  393. if (cur_rate == Rate6k3) {
  394. if (subfrm.pulse_pos >= max_pos[index])
  395. return;
  396. /* Decode amplitudes and positions */
  397. j = PULSE_MAX - pulses[index];
  398. temp = subfrm.pulse_pos;
  399. for (i = 0; i < SUBFRAME_LEN / GRID_SIZE; i++) {
  400. temp -= combinatorial_table[j][i];
  401. if (temp >= 0)
  402. continue;
  403. temp += combinatorial_table[j++][i];
  404. if (subfrm.pulse_sign & (1 << (PULSE_MAX - j))) {
  405. vector[subfrm.grid_index + GRID_SIZE * i] =
  406. -fixed_cb_gain[subfrm.amp_index];
  407. } else {
  408. vector[subfrm.grid_index + GRID_SIZE * i] =
  409. fixed_cb_gain[subfrm.amp_index];
  410. }
  411. if (j == PULSE_MAX)
  412. break;
  413. }
  414. if (subfrm.dirac_train == 1)
  415. gen_dirac_train(vector, pitch_lag);
  416. } else { /* Rate5k3 */
  417. int cb_gain = fixed_cb_gain[subfrm.amp_index];
  418. int cb_shift = subfrm.grid_index;
  419. int cb_sign = subfrm.pulse_sign;
  420. int cb_pos = subfrm.pulse_pos;
  421. int offset, beta, lag;
  422. for (i = 0; i < 8; i += 2) {
  423. offset = ((cb_pos & 7) << 3) + cb_shift + i;
  424. vector[offset] = (cb_sign & 1) ? cb_gain : -cb_gain;
  425. cb_pos >>= 3;
  426. cb_sign >>= 1;
  427. }
  428. /* Enhance harmonic components */
  429. lag = pitch_contrib[subfrm.ad_cb_gain << 1] + pitch_lag +
  430. subfrm.ad_cb_lag - 1;
  431. beta = pitch_contrib[(subfrm.ad_cb_gain << 1) + 1];
  432. if (lag < SUBFRAME_LEN - 2) {
  433. for (i = lag; i < SUBFRAME_LEN; i++)
  434. vector[i] += beta * vector[i - lag] >> 15;
  435. }
  436. }
  437. }
  438. /**
  439. * Get delayed contribution from the previous excitation vector.
  440. */
  441. static void get_residual(int16_t *residual, int16_t *prev_excitation, int lag)
  442. {
  443. int offset = PITCH_MAX - PITCH_ORDER / 2 - lag;
  444. int i;
  445. residual[0] = prev_excitation[offset];
  446. residual[1] = prev_excitation[offset + 1];
  447. offset += 2;
  448. for (i = 2; i < SUBFRAME_LEN + PITCH_ORDER - 1; i++)
  449. residual[i] = prev_excitation[offset + (i - 2) % lag];
  450. }
  451. /**
  452. * Generate adaptive codebook excitation.
  453. */
  454. static void gen_acb_excitation(int16_t *vector, int16_t *prev_excitation,
  455. int pitch_lag, G723_1_Subframe subfrm,
  456. Rate cur_rate)
  457. {
  458. int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
  459. const int16_t *cb_ptr;
  460. int lag = pitch_lag + subfrm.ad_cb_lag - 1;
  461. int i;
  462. int64_t sum;
  463. get_residual(residual, prev_excitation, lag);
  464. /* Select quantization table */
  465. if (cur_rate == Rate6k3 && pitch_lag < SUBFRAME_LEN - 2) {
  466. cb_ptr = adaptive_cb_gain85;
  467. } else
  468. cb_ptr = adaptive_cb_gain170;
  469. /* Calculate adaptive vector */
  470. cb_ptr += subfrm.ad_cb_gain * 20;
  471. for (i = 0; i < SUBFRAME_LEN; i++) {
  472. sum = ff_dot_product(residual + i, cb_ptr, PITCH_ORDER);
  473. vector[i] = av_clipl_int32((sum << 2) + (1 << 15)) >> 16;
  474. }
  475. }
  476. /**
  477. * Estimate maximum auto-correlation around pitch lag.
  478. *
  479. * @param p the context
  480. * @param offset offset of the excitation vector
  481. * @param ccr_max pointer to the maximum auto-correlation
  482. * @param pitch_lag decoded pitch lag
  483. * @param length length of autocorrelation
  484. * @param dir forward lag(1) / backward lag(-1)
  485. */
  486. static int autocorr_max(G723_1_Context *p, int offset, int *ccr_max,
  487. int pitch_lag, int length, int dir)
  488. {
  489. int limit, ccr, lag = 0;
  490. int16_t *buf = p->excitation + offset;
  491. int i;
  492. pitch_lag = FFMIN(PITCH_MAX - 3, pitch_lag);
  493. limit = FFMIN(FRAME_LEN + PITCH_MAX - offset - length, pitch_lag + 3);
  494. for (i = pitch_lag - 3; i <= limit; i++) {
  495. ccr = ff_dot_product(buf, buf + dir * i, length)<<1;
  496. if (ccr > *ccr_max) {
  497. *ccr_max = ccr;
  498. lag = i;
  499. }
  500. }
  501. return lag;
  502. }
  503. /**
  504. * Calculate pitch postfilter optimal and scaling gains.
  505. *
  506. * @param lag pitch postfilter forward/backward lag
  507. * @param ppf pitch postfilter parameters
  508. * @param cur_rate current bitrate
  509. * @param tgt_eng target energy
  510. * @param ccr cross-correlation
  511. * @param res_eng residual energy
  512. */
  513. static void comp_ppf_gains(int lag, PPFParam *ppf, Rate cur_rate,
  514. int tgt_eng, int ccr, int res_eng)
  515. {
  516. int pf_residual; /* square of postfiltered residual */
  517. int64_t temp1, temp2;
  518. ppf->index = lag;
  519. temp1 = tgt_eng * res_eng >> 1;
  520. temp2 = ccr * ccr << 1;
  521. if (temp2 > temp1) {
  522. if (ccr >= res_eng) {
  523. ppf->opt_gain = ppf_gain_weight[cur_rate];
  524. } else {
  525. ppf->opt_gain = (ccr << 15) / res_eng *
  526. ppf_gain_weight[cur_rate] >> 15;
  527. }
  528. /* pf_res^2 = tgt_eng + 2*ccr*gain + res_eng*gain^2 */
  529. temp1 = (tgt_eng << 15) + (ccr * ppf->opt_gain << 1);
  530. temp2 = (ppf->opt_gain * ppf->opt_gain >> 15) * res_eng;
  531. pf_residual = av_clipl_int32(temp1 + temp2 + (1 << 15)) >> 16;
  532. if (tgt_eng >= pf_residual << 1) {
  533. temp1 = 0x7fff;
  534. } else {
  535. temp1 = (tgt_eng << 14) / pf_residual;
  536. }
  537. /* scaling_gain = sqrt(tgt_eng/pf_res^2) */
  538. ppf->sc_gain = square_root(temp1 << 16);
  539. } else {
  540. ppf->opt_gain = 0;
  541. ppf->sc_gain = 0x7fff;
  542. }
  543. ppf->opt_gain = av_clip_int16(ppf->opt_gain * ppf->sc_gain >> 15);
  544. }
  545. /**
  546. * Calculate pitch postfilter parameters.
  547. *
  548. * @param p the context
  549. * @param offset offset of the excitation vector
  550. * @param pitch_lag decoded pitch lag
  551. * @param ppf pitch postfilter parameters
  552. * @param cur_rate current bitrate
  553. */
  554. static void comp_ppf_coeff(G723_1_Context *p, int offset, int pitch_lag,
  555. PPFParam *ppf, Rate cur_rate)
  556. {
  557. int16_t scale;
  558. int i;
  559. int64_t temp1, temp2;
  560. /*
  561. * 0 - target energy
  562. * 1 - forward cross-correlation
  563. * 2 - forward residual energy
  564. * 3 - backward cross-correlation
  565. * 4 - backward residual energy
  566. */
  567. int energy[5] = {0, 0, 0, 0, 0};
  568. int16_t *buf = p->excitation + offset;
  569. int fwd_lag = autocorr_max(p, offset, &energy[1], pitch_lag,
  570. SUBFRAME_LEN, 1);
  571. int back_lag = autocorr_max(p, offset, &energy[3], pitch_lag,
  572. SUBFRAME_LEN, -1);
  573. ppf->index = 0;
  574. ppf->opt_gain = 0;
  575. ppf->sc_gain = 0x7fff;
  576. /* Case 0, Section 3.6 */
  577. if (!back_lag && !fwd_lag)
  578. return;
  579. /* Compute target energy */
  580. energy[0] = ff_dot_product(buf, buf, SUBFRAME_LEN)<<1;
  581. /* Compute forward residual energy */
  582. if (fwd_lag)
  583. energy[2] = ff_dot_product(buf + fwd_lag, buf + fwd_lag,
  584. SUBFRAME_LEN)<<1;
  585. /* Compute backward residual energy */
  586. if (back_lag)
  587. energy[4] = ff_dot_product(buf - back_lag, buf - back_lag,
  588. SUBFRAME_LEN)<<1;
  589. /* Normalize and shorten */
  590. temp1 = 0;
  591. for (i = 0; i < 5; i++)
  592. temp1 = FFMAX(energy[i], temp1);
  593. scale = normalize_bits(temp1, 1);
  594. for (i = 0; i < 5; i++)
  595. energy[i] = av_clipl_int32(energy[i] << scale) >> 16;
  596. if (fwd_lag && !back_lag) { /* Case 1 */
  597. comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
  598. energy[2]);
  599. } else if (!fwd_lag) { /* Case 2 */
  600. comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
  601. energy[4]);
  602. } else { /* Case 3 */
  603. /*
  604. * Select the largest of energy[1]^2/energy[2]
  605. * and energy[3]^2/energy[4]
  606. */
  607. temp1 = energy[4] * ((energy[1] * energy[1] + (1 << 14)) >> 15);
  608. temp2 = energy[2] * ((energy[3] * energy[3] + (1 << 14)) >> 15);
  609. if (temp1 >= temp2) {
  610. comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
  611. energy[2]);
  612. } else {
  613. comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
  614. energy[4]);
  615. }
  616. }
  617. }
  618. /**
  619. * Classify frames as voiced/unvoiced.
  620. *
  621. * @param p the context
  622. * @param pitch_lag decoded pitch_lag
  623. * @param exc_eng excitation energy estimation
  624. * @param scale scaling factor of exc_eng
  625. *
  626. * @return residual interpolation index if voiced, 0 otherwise
  627. */
  628. static int comp_interp_index(G723_1_Context *p, int pitch_lag,
  629. int *exc_eng, int *scale)
  630. {
  631. int offset = PITCH_MAX + 2 * SUBFRAME_LEN;
  632. int16_t *buf = p->excitation + offset;
  633. int index, ccr, tgt_eng, best_eng, temp;
  634. *scale = scale_vector(p->excitation, FRAME_LEN + PITCH_MAX);
  635. /* Compute maximum backward cross-correlation */
  636. ccr = 0;
  637. index = autocorr_max(p, offset, &ccr, pitch_lag, SUBFRAME_LEN * 2, -1);
  638. ccr = av_clipl_int32((int64_t)ccr + (1 << 15)) >> 16;
  639. /* Compute target energy */
  640. tgt_eng = ff_dot_product(buf, buf, SUBFRAME_LEN * 2)<<1;
  641. *exc_eng = av_clipl_int32(tgt_eng + (1 << 15)) >> 16;
  642. if (ccr <= 0)
  643. return 0;
  644. /* Compute best energy */
  645. best_eng = ff_dot_product(buf - index, buf - index,
  646. SUBFRAME_LEN * 2)<<1;
  647. best_eng = av_clipl_int32((int64_t)best_eng + (1 << 15)) >> 16;
  648. temp = best_eng * *exc_eng >> 3;
  649. if (temp < ccr * ccr) {
  650. return index;
  651. } else
  652. return 0;
  653. }
  654. /**
  655. * Peform residual interpolation based on frame classification.
  656. *
  657. * @param buf decoded excitation vector
  658. * @param out output vector
  659. * @param lag decoded pitch lag
  660. * @param gain interpolated gain
  661. * @param rseed seed for random number generator
  662. */
  663. static void residual_interp(int16_t *buf, int16_t *out, int lag,
  664. int gain, int *rseed)
  665. {
  666. int i;
  667. if (lag) { /* Voiced */
  668. int16_t *vector_ptr = buf + PITCH_MAX;
  669. /* Attenuate */
  670. for (i = 0; i < lag; i++)
  671. vector_ptr[i - lag] = vector_ptr[i - lag] * 3 >> 2;
  672. av_memcpy_backptr((uint8_t*)vector_ptr, lag * sizeof(int16_t),
  673. FRAME_LEN * sizeof(int16_t));
  674. memcpy(out, vector_ptr, FRAME_LEN * sizeof(int16_t));
  675. } else { /* Unvoiced */
  676. for (i = 0; i < FRAME_LEN; i++) {
  677. *rseed = *rseed * 521 + 259;
  678. out[i] = gain * *rseed >> 15;
  679. }
  680. memset(buf, 0, (FRAME_LEN + PITCH_MAX) * sizeof(int16_t));
  681. }
  682. }
  683. /**
  684. * Perform IIR filtering.
  685. *
  686. * @param fir_coef FIR coefficients
  687. * @param iir_coef IIR coefficients
  688. * @param src source vector
  689. * @param dest destination vector
  690. * @param width width of the output, 16 bits(0) / 32 bits(1)
  691. */
  692. #define iir_filter(fir_coef, iir_coef, src, dest, width)\
  693. {\
  694. int m, n;\
  695. int res_shift = 16 & ~-(width);\
  696. int in_shift = 16 - res_shift;\
  697. \
  698. for (m = 0; m < SUBFRAME_LEN; m++) {\
  699. int64_t filter = 0;\
  700. for (n = 1; n <= LPC_ORDER; n++) {\
  701. filter -= (fir_coef)[n - 1] * (src)[m - n] -\
  702. (iir_coef)[n - 1] * ((dest)[m - n] >> in_shift);\
  703. }\
  704. \
  705. (dest)[m] = av_clipl_int32(((src)[m] << 16) + (filter << 3) +\
  706. (1 << 15)) >> res_shift;\
  707. }\
  708. }
  709. /**
  710. * Adjust gain of postfiltered signal.
  711. *
  712. * @param p the context
  713. * @param buf postfiltered output vector
  714. * @param energy input energy coefficient
  715. */
  716. static void gain_scale(G723_1_Context *p, int16_t * buf, int energy)
  717. {
  718. int num, denom, gain, bits1, bits2;
  719. int i;
  720. num = energy;
  721. denom = 0;
  722. for (i = 0; i < SUBFRAME_LEN; i++) {
  723. int64_t temp = buf[i] >> 2;
  724. temp = av_clipl_int32(MUL64(temp, temp) << 1);
  725. denom = av_clipl_int32(denom + temp);
  726. }
  727. if (num && denom) {
  728. bits1 = normalize_bits(num, 1);
  729. bits2 = normalize_bits(denom, 1);
  730. num = num << bits1 >> 1;
  731. denom <<= bits2;
  732. bits2 = 5 + bits1 - bits2;
  733. bits2 = FFMAX(0, bits2);
  734. gain = (num >> 1) / (denom >> 16);
  735. gain = square_root(gain << 16 >> bits2);
  736. } else {
  737. gain = 1 << 12;
  738. }
  739. for (i = 0; i < SUBFRAME_LEN; i++) {
  740. p->pf_gain = ((p->pf_gain << 4) - p->pf_gain + gain + (1 << 3)) >> 4;
  741. buf[i] = av_clip_int16((buf[i] * (p->pf_gain + (p->pf_gain >> 4)) +
  742. (1 << 10)) >> 11);
  743. }
  744. }
  745. /**
  746. * Perform formant filtering.
  747. *
  748. * @param p the context
  749. * @param lpc quantized lpc coefficients
  750. * @param buf output buffer
  751. */
  752. static void formant_postfilter(G723_1_Context *p, int16_t *lpc, int16_t *buf)
  753. {
  754. int16_t filter_coef[2][LPC_ORDER], *buf_ptr;
  755. int filter_signal[LPC_ORDER + FRAME_LEN], *signal_ptr;
  756. int i, j, k;
  757. memcpy(buf, p->fir_mem, LPC_ORDER * sizeof(int16_t));
  758. memcpy(filter_signal, p->iir_mem, LPC_ORDER * sizeof(int));
  759. for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
  760. for (k = 0; k < LPC_ORDER; k++) {
  761. filter_coef[0][k] = (-lpc[k] * postfilter_tbl[0][k] +
  762. (1 << 14)) >> 15;
  763. filter_coef[1][k] = (-lpc[k] * postfilter_tbl[1][k] +
  764. (1 << 14)) >> 15;
  765. }
  766. iir_filter(filter_coef[0], filter_coef[1], buf + i,
  767. filter_signal + i, 1);
  768. }
  769. memcpy(p->fir_mem, buf + FRAME_LEN, LPC_ORDER * sizeof(int16_t));
  770. memcpy(p->iir_mem, filter_signal + FRAME_LEN, LPC_ORDER * sizeof(int));
  771. buf_ptr = buf + LPC_ORDER;
  772. signal_ptr = filter_signal + LPC_ORDER;
  773. for (i = 0; i < SUBFRAMES; i++) {
  774. int16_t temp_vector[SUBFRAME_LEN];
  775. int16_t temp;
  776. int auto_corr[2];
  777. int scale, energy;
  778. /* Normalize */
  779. memcpy(temp_vector, buf_ptr, SUBFRAME_LEN * sizeof(int16_t));
  780. scale = scale_vector(temp_vector, SUBFRAME_LEN);
  781. /* Compute auto correlation coefficients */
  782. auto_corr[0] = ff_dot_product(temp_vector, temp_vector + 1,
  783. SUBFRAME_LEN - 1)<<1;
  784. auto_corr[1] = ff_dot_product(temp_vector, temp_vector,
  785. SUBFRAME_LEN)<<1;
  786. /* Compute reflection coefficient */
  787. temp = auto_corr[1] >> 16;
  788. if (temp) {
  789. temp = (auto_corr[0] >> 2) / temp;
  790. }
  791. p->reflection_coef = ((p->reflection_coef << 2) - p->reflection_coef +
  792. temp + 2) >> 2;
  793. temp = (p->reflection_coef * 0xffffc >> 3) & 0xfffc;
  794. /* Compensation filter */
  795. for (j = 0; j < SUBFRAME_LEN; j++) {
  796. buf_ptr[j] = av_clipl_int32(signal_ptr[j] +
  797. ((signal_ptr[j - 1] >> 16) *
  798. temp << 1)) >> 16;
  799. }
  800. /* Compute normalized signal energy */
  801. temp = 2 * scale + 4;
  802. if (temp < 0) {
  803. energy = av_clipl_int32((int64_t)auto_corr[1] << -temp);
  804. } else
  805. energy = auto_corr[1] >> temp;
  806. gain_scale(p, buf_ptr, energy);
  807. buf_ptr += SUBFRAME_LEN;
  808. signal_ptr += SUBFRAME_LEN;
  809. }
  810. }
  811. static int g723_1_decode_frame(AVCodecContext *avctx, void *data,
  812. int *data_size, AVPacket *avpkt)
  813. {
  814. G723_1_Context *p = avctx->priv_data;
  815. const uint8_t *buf = avpkt->data;
  816. int buf_size = avpkt->size;
  817. int16_t *out = data;
  818. int dec_mode = buf[0] & 3;
  819. PPFParam ppf[SUBFRAMES];
  820. int16_t cur_lsp[LPC_ORDER];
  821. int16_t lpc[SUBFRAMES * LPC_ORDER];
  822. int16_t acb_vector[SUBFRAME_LEN];
  823. int16_t *vector_ptr;
  824. int bad_frame = 0, i, j;
  825. if (!buf_size || buf_size < frame_size[dec_mode]) {
  826. *data_size = 0;
  827. return buf_size;
  828. }
  829. if (unpack_bitstream(p, buf, buf_size) < 0) {
  830. bad_frame = 1;
  831. p->cur_frame_type = p->past_frame_type == ActiveFrame ?
  832. ActiveFrame : UntransmittedFrame;
  833. }
  834. *data_size = FRAME_LEN * sizeof(int16_t);
  835. if(p->cur_frame_type == ActiveFrame) {
  836. if (!bad_frame) {
  837. p->erased_frames = 0;
  838. } else if(p->erased_frames != 3)
  839. p->erased_frames++;
  840. inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, bad_frame);
  841. lsp_interpolate(lpc, cur_lsp, p->prev_lsp);
  842. /* Save the lsp_vector for the next frame */
  843. memcpy(p->prev_lsp, cur_lsp, LPC_ORDER * sizeof(int16_t));
  844. /* Generate the excitation for the frame */
  845. memcpy(p->excitation, p->prev_excitation, PITCH_MAX * sizeof(int16_t));
  846. vector_ptr = p->excitation + PITCH_MAX;
  847. if (!p->erased_frames) {
  848. /* Update interpolation gain memory */
  849. p->interp_gain = fixed_cb_gain[(p->subframe[2].amp_index +
  850. p->subframe[3].amp_index) >> 1];
  851. for (i = 0; i < SUBFRAMES; i++) {
  852. gen_fcb_excitation(vector_ptr, p->subframe[i], p->cur_rate,
  853. p->pitch_lag[i >> 1], i);
  854. gen_acb_excitation(acb_vector, &p->excitation[SUBFRAME_LEN * i],
  855. p->pitch_lag[i >> 1], p->subframe[i],
  856. p->cur_rate);
  857. /* Get the total excitation */
  858. for (j = 0; j < SUBFRAME_LEN; j++) {
  859. vector_ptr[j] = av_clip_int16(vector_ptr[j] << 1);
  860. vector_ptr[j] = av_clip_int16(vector_ptr[j] +
  861. acb_vector[j]);
  862. }
  863. vector_ptr += SUBFRAME_LEN;
  864. }
  865. vector_ptr = p->excitation + PITCH_MAX;
  866. /* Save the excitation */
  867. memcpy(out, vector_ptr, FRAME_LEN * sizeof(int16_t));
  868. p->interp_index = comp_interp_index(p, p->pitch_lag[1],
  869. &p->sid_gain, &p->cur_gain);
  870. for (i = PITCH_MAX, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
  871. comp_ppf_coeff(p, i, p->pitch_lag[j >> 1],
  872. ppf + j, p->cur_rate);
  873. /* Restore the original excitation */
  874. memcpy(p->excitation, p->prev_excitation,
  875. PITCH_MAX * sizeof(int16_t));
  876. memcpy(vector_ptr, out, FRAME_LEN * sizeof(int16_t));
  877. /* Peform pitch postfiltering */
  878. for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
  879. ff_acelp_weighted_vector_sum(out + LPC_ORDER + i, vector_ptr + i,
  880. vector_ptr + i + ppf[j].index,
  881. ppf[j].sc_gain, ppf[j].opt_gain,
  882. 1 << 14, 15, SUBFRAME_LEN);
  883. } else {
  884. p->interp_gain = (p->interp_gain * 3 + 2) >> 2;
  885. if (p->erased_frames == 3) {
  886. /* Mute output */
  887. memset(p->excitation, 0,
  888. (FRAME_LEN + PITCH_MAX) * sizeof(int16_t));
  889. memset(out, 0, (FRAME_LEN + LPC_ORDER) * sizeof(int16_t));
  890. } else {
  891. /* Regenerate frame */
  892. residual_interp(p->excitation, out + LPC_ORDER, p->interp_index,
  893. p->interp_gain, &p->random_seed);
  894. }
  895. }
  896. /* Save the excitation for the next frame */
  897. memcpy(p->prev_excitation, p->excitation + FRAME_LEN,
  898. PITCH_MAX * sizeof(int16_t));
  899. } else {
  900. memset(out, 0, *data_size);
  901. av_log(avctx, AV_LOG_WARNING,
  902. "G.723.1: Comfort noise generation not supported yet\n");
  903. return frame_size[dec_mode];
  904. }
  905. p->past_frame_type = p->cur_frame_type;
  906. memcpy(out, p->synth_mem, LPC_ORDER * sizeof(int16_t));
  907. for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
  908. ff_celp_lp_synthesis_filter(out + i, &lpc[j * LPC_ORDER],
  909. out + i, SUBFRAME_LEN, LPC_ORDER,
  910. 0, 1, 1 << 12);
  911. memcpy(p->synth_mem, out + FRAME_LEN, LPC_ORDER * sizeof(int16_t));
  912. formant_postfilter(p, lpc, out);
  913. memmove(out, out + LPC_ORDER, *data_size);
  914. return frame_size[dec_mode];
  915. }
  916. AVCodec ff_g723_1_decoder = {
  917. .name = "g723_1",
  918. .type = AVMEDIA_TYPE_AUDIO,
  919. .id = CODEC_ID_G723_1,
  920. .priv_data_size = sizeof(G723_1_Context),
  921. .init = g723_1_decode_init,
  922. .decode = g723_1_decode_frame,
  923. .long_name = NULL_IF_CONFIG_SMALL("G.723.1"),
  924. .capabilities = CODEC_CAP_SUBFRAMES,
  925. };