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.

1170 lines
36KB

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