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.

1187 lines
37KB

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