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.

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