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.

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