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.

805 lines
26KB

  1. /*
  2. * QCELP decoder
  3. * Copyright (c) 2007 Reynaldo H. Verdejo Pinochet
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * QCELP decoder
  24. * @author Reynaldo H. Verdejo Pinochet
  25. * @remark Libav merging spearheaded by Kenan Gillet
  26. * @remark Development mentored by Benjamin Larson
  27. */
  28. #include <stddef.h>
  29. #include "libavutil/channel_layout.h"
  30. #include "avcodec.h"
  31. #include "internal.h"
  32. #include "get_bits.h"
  33. #include "dsputil.h"
  34. #include "qcelpdata.h"
  35. #include "celp_filters.h"
  36. #include "acelp_filters.h"
  37. #include "acelp_vectors.h"
  38. #include "lsp.h"
  39. #undef NDEBUG
  40. #include <assert.h>
  41. typedef enum {
  42. I_F_Q = -1, /**< insufficient frame quality */
  43. SILENCE,
  44. RATE_OCTAVE,
  45. RATE_QUARTER,
  46. RATE_HALF,
  47. RATE_FULL
  48. } qcelp_packet_rate;
  49. typedef struct {
  50. AVFrame avframe;
  51. GetBitContext gb;
  52. qcelp_packet_rate bitrate;
  53. QCELPFrame frame; /**< unpacked data frame */
  54. uint8_t erasure_count;
  55. uint8_t octave_count; /**< count the consecutive RATE_OCTAVE frames */
  56. float prev_lspf[10];
  57. float predictor_lspf[10];/**< LSP predictor for RATE_OCTAVE and I_F_Q */
  58. float pitch_synthesis_filter_mem[303];
  59. float pitch_pre_filter_mem[303];
  60. float rnd_fir_filter_mem[180];
  61. float formant_mem[170];
  62. float last_codebook_gain;
  63. int prev_g1[2];
  64. int prev_bitrate;
  65. float pitch_gain[4];
  66. uint8_t pitch_lag[4];
  67. uint16_t first16bits;
  68. uint8_t warned_buf_mismatch_bitrate;
  69. /* postfilter */
  70. float postfilter_synth_mem[10];
  71. float postfilter_agc_mem;
  72. float postfilter_tilt_mem;
  73. } QCELPContext;
  74. /**
  75. * Initialize the speech codec according to the specification.
  76. *
  77. * TIA/EIA/IS-733 2.4.9
  78. */
  79. static av_cold int qcelp_decode_init(AVCodecContext *avctx)
  80. {
  81. QCELPContext *q = avctx->priv_data;
  82. int i;
  83. avctx->channels = 1;
  84. avctx->channel_layout = AV_CH_LAYOUT_MONO;
  85. avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
  86. for (i = 0; i < 10; i++)
  87. q->prev_lspf[i] = (i + 1) / 11.;
  88. avcodec_get_frame_defaults(&q->avframe);
  89. avctx->coded_frame = &q->avframe;
  90. return 0;
  91. }
  92. /**
  93. * Decode the 10 quantized LSP frequencies from the LSPV/LSP
  94. * transmission codes of any bitrate and check for badly received packets.
  95. *
  96. * @param q the context
  97. * @param lspf line spectral pair frequencies
  98. *
  99. * @return 0 on success, -1 if the packet is badly received
  100. *
  101. * TIA/EIA/IS-733 2.4.3.2.6.2-2, 2.4.8.7.3
  102. */
  103. static int decode_lspf(QCELPContext *q, float *lspf)
  104. {
  105. int i;
  106. float tmp_lspf, smooth, erasure_coeff;
  107. const float *predictors;
  108. if (q->bitrate == RATE_OCTAVE || q->bitrate == I_F_Q) {
  109. predictors = q->prev_bitrate != RATE_OCTAVE &&
  110. q->prev_bitrate != I_F_Q ? q->prev_lspf
  111. : q->predictor_lspf;
  112. if (q->bitrate == RATE_OCTAVE) {
  113. q->octave_count++;
  114. for (i = 0; i < 10; i++) {
  115. q->predictor_lspf[i] =
  116. lspf[i] = (q->frame.lspv[i] ? QCELP_LSP_SPREAD_FACTOR
  117. : -QCELP_LSP_SPREAD_FACTOR) +
  118. predictors[i] * QCELP_LSP_OCTAVE_PREDICTOR +
  119. (i + 1) * ((1 - QCELP_LSP_OCTAVE_PREDICTOR) / 11);
  120. }
  121. smooth = q->octave_count < 10 ? .875 : 0.1;
  122. } else {
  123. erasure_coeff = QCELP_LSP_OCTAVE_PREDICTOR;
  124. assert(q->bitrate == I_F_Q);
  125. if (q->erasure_count > 1)
  126. erasure_coeff *= q->erasure_count < 4 ? 0.9 : 0.7;
  127. for (i = 0; i < 10; i++) {
  128. q->predictor_lspf[i] =
  129. lspf[i] = (i + 1) * (1 - erasure_coeff) / 11 +
  130. erasure_coeff * predictors[i];
  131. }
  132. smooth = 0.125;
  133. }
  134. // Check the stability of the LSP frequencies.
  135. lspf[0] = FFMAX(lspf[0], QCELP_LSP_SPREAD_FACTOR);
  136. for (i = 1; i < 10; i++)
  137. lspf[i] = FFMAX(lspf[i], lspf[i - 1] + QCELP_LSP_SPREAD_FACTOR);
  138. lspf[9] = FFMIN(lspf[9], 1.0 - QCELP_LSP_SPREAD_FACTOR);
  139. for (i = 9; i > 0; i--)
  140. lspf[i - 1] = FFMIN(lspf[i - 1], lspf[i] - QCELP_LSP_SPREAD_FACTOR);
  141. // Low-pass filter the LSP frequencies.
  142. ff_weighted_vector_sumf(lspf, lspf, q->prev_lspf, smooth, 1.0 - smooth, 10);
  143. } else {
  144. q->octave_count = 0;
  145. tmp_lspf = 0.;
  146. for (i = 0; i < 5; i++) {
  147. lspf[2 * i + 0] = tmp_lspf += qcelp_lspvq[i][q->frame.lspv[i]][0] * 0.0001;
  148. lspf[2 * i + 1] = tmp_lspf += qcelp_lspvq[i][q->frame.lspv[i]][1] * 0.0001;
  149. }
  150. // Check for badly received packets.
  151. if (q->bitrate == RATE_QUARTER) {
  152. if (lspf[9] <= .70 || lspf[9] >= .97)
  153. return -1;
  154. for (i = 3; i < 10; i++)
  155. if (fabs(lspf[i] - lspf[i - 2]) < .08)
  156. return -1;
  157. } else {
  158. if (lspf[9] <= .66 || lspf[9] >= .985)
  159. return -1;
  160. for (i = 4; i < 10; i++)
  161. if (fabs(lspf[i] - lspf[i - 4]) < .0931)
  162. return -1;
  163. }
  164. }
  165. return 0;
  166. }
  167. /**
  168. * Convert codebook transmission codes to GAIN and INDEX.
  169. *
  170. * @param q the context
  171. * @param gain array holding the decoded gain
  172. *
  173. * TIA/EIA/IS-733 2.4.6.2
  174. */
  175. static void decode_gain_and_index(QCELPContext *q, float *gain)
  176. {
  177. int i, subframes_count, g1[16];
  178. float slope;
  179. if (q->bitrate >= RATE_QUARTER) {
  180. switch (q->bitrate) {
  181. case RATE_FULL: subframes_count = 16; break;
  182. case RATE_HALF: subframes_count = 4; break;
  183. default: subframes_count = 5;
  184. }
  185. for (i = 0; i < subframes_count; i++) {
  186. g1[i] = 4 * q->frame.cbgain[i];
  187. if (q->bitrate == RATE_FULL && !((i + 1) & 3)) {
  188. g1[i] += av_clip((g1[i - 1] + g1[i - 2] + g1[i - 3]) / 3 - 6, 0, 32);
  189. }
  190. gain[i] = qcelp_g12ga[g1[i]];
  191. if (q->frame.cbsign[i]) {
  192. gain[i] = -gain[i];
  193. q->frame.cindex[i] = (q->frame.cindex[i] - 89) & 127;
  194. }
  195. }
  196. q->prev_g1[0] = g1[i - 2];
  197. q->prev_g1[1] = g1[i - 1];
  198. q->last_codebook_gain = qcelp_g12ga[g1[i - 1]];
  199. if (q->bitrate == RATE_QUARTER) {
  200. // Provide smoothing of the unvoiced excitation energy.
  201. gain[7] = gain[4];
  202. gain[6] = 0.4 * gain[3] + 0.6 * gain[4];
  203. gain[5] = gain[3];
  204. gain[4] = 0.8 * gain[2] + 0.2 * gain[3];
  205. gain[3] = 0.2 * gain[1] + 0.8 * gain[2];
  206. gain[2] = gain[1];
  207. gain[1] = 0.6 * gain[0] + 0.4 * gain[1];
  208. }
  209. } else if (q->bitrate != SILENCE) {
  210. if (q->bitrate == RATE_OCTAVE) {
  211. g1[0] = 2 * q->frame.cbgain[0] +
  212. av_clip((q->prev_g1[0] + q->prev_g1[1]) / 2 - 5, 0, 54);
  213. subframes_count = 8;
  214. } else {
  215. assert(q->bitrate == I_F_Q);
  216. g1[0] = q->prev_g1[1];
  217. switch (q->erasure_count) {
  218. case 1 : break;
  219. case 2 : g1[0] -= 1; break;
  220. case 3 : g1[0] -= 2; break;
  221. default: g1[0] -= 6;
  222. }
  223. if (g1[0] < 0)
  224. g1[0] = 0;
  225. subframes_count = 4;
  226. }
  227. // This interpolation is done to produce smoother background noise.
  228. slope = 0.5 * (qcelp_g12ga[g1[0]] - q->last_codebook_gain) / subframes_count;
  229. for (i = 1; i <= subframes_count; i++)
  230. gain[i - 1] = q->last_codebook_gain + slope * i;
  231. q->last_codebook_gain = gain[i - 2];
  232. q->prev_g1[0] = q->prev_g1[1];
  233. q->prev_g1[1] = g1[0];
  234. }
  235. }
  236. /**
  237. * If the received packet is Rate 1/4 a further sanity check is made of the
  238. * codebook gain.
  239. *
  240. * @param cbgain the unpacked cbgain array
  241. * @return -1 if the sanity check fails, 0 otherwise
  242. *
  243. * TIA/EIA/IS-733 2.4.8.7.3
  244. */
  245. static int codebook_sanity_check_for_rate_quarter(const uint8_t *cbgain)
  246. {
  247. int i, diff, prev_diff = 0;
  248. for (i = 1; i < 5; i++) {
  249. diff = cbgain[i] - cbgain[i-1];
  250. if (FFABS(diff) > 10)
  251. return -1;
  252. else if (FFABS(diff - prev_diff) > 12)
  253. return -1;
  254. prev_diff = diff;
  255. }
  256. return 0;
  257. }
  258. /**
  259. * Compute the scaled codebook vector Cdn From INDEX and GAIN
  260. * for all rates.
  261. *
  262. * The specification lacks some information here.
  263. *
  264. * TIA/EIA/IS-733 has an omission on the codebook index determination
  265. * formula for RATE_FULL and RATE_HALF frames at section 2.4.8.1.1. It says
  266. * you have to subtract the decoded index parameter from the given scaled
  267. * codebook vector index 'n' to get the desired circular codebook index, but
  268. * it does not mention that you have to clamp 'n' to [0-9] in order to get
  269. * RI-compliant results.
  270. *
  271. * The reason for this mistake seems to be the fact they forgot to mention you
  272. * have to do these calculations per codebook subframe and adjust given
  273. * equation values accordingly.
  274. *
  275. * @param q the context
  276. * @param gain array holding the 4 pitch subframe gain values
  277. * @param cdn_vector array for the generated scaled codebook vector
  278. */
  279. static void compute_svector(QCELPContext *q, const float *gain,
  280. float *cdn_vector)
  281. {
  282. int i, j, k;
  283. uint16_t cbseed, cindex;
  284. float *rnd, tmp_gain, fir_filter_value;
  285. switch (q->bitrate) {
  286. case RATE_FULL:
  287. for (i = 0; i < 16; i++) {
  288. tmp_gain = gain[i] * QCELP_RATE_FULL_CODEBOOK_RATIO;
  289. cindex = -q->frame.cindex[i];
  290. for (j = 0; j < 10; j++)
  291. *cdn_vector++ = tmp_gain * qcelp_rate_full_codebook[cindex++ & 127];
  292. }
  293. break;
  294. case RATE_HALF:
  295. for (i = 0; i < 4; i++) {
  296. tmp_gain = gain[i] * QCELP_RATE_HALF_CODEBOOK_RATIO;
  297. cindex = -q->frame.cindex[i];
  298. for (j = 0; j < 40; j++)
  299. *cdn_vector++ = tmp_gain * qcelp_rate_half_codebook[cindex++ & 127];
  300. }
  301. break;
  302. case RATE_QUARTER:
  303. cbseed = (0x0003 & q->frame.lspv[4]) << 14 |
  304. (0x003F & q->frame.lspv[3]) << 8 |
  305. (0x0060 & q->frame.lspv[2]) << 1 |
  306. (0x0007 & q->frame.lspv[1]) << 3 |
  307. (0x0038 & q->frame.lspv[0]) >> 3;
  308. rnd = q->rnd_fir_filter_mem + 20;
  309. for (i = 0; i < 8; i++) {
  310. tmp_gain = gain[i] * (QCELP_SQRT1887 / 32768.0);
  311. for (k = 0; k < 20; k++) {
  312. cbseed = 521 * cbseed + 259;
  313. *rnd = (int16_t) cbseed;
  314. // FIR filter
  315. fir_filter_value = 0.0;
  316. for (j = 0; j < 10; j++)
  317. fir_filter_value += qcelp_rnd_fir_coefs[j] *
  318. (rnd[-j] + rnd[-20+j]);
  319. fir_filter_value += qcelp_rnd_fir_coefs[10] * rnd[-10];
  320. *cdn_vector++ = tmp_gain * fir_filter_value;
  321. rnd++;
  322. }
  323. }
  324. memcpy(q->rnd_fir_filter_mem, q->rnd_fir_filter_mem + 160,
  325. 20 * sizeof(float));
  326. break;
  327. case RATE_OCTAVE:
  328. cbseed = q->first16bits;
  329. for (i = 0; i < 8; i++) {
  330. tmp_gain = gain[i] * (QCELP_SQRT1887 / 32768.0);
  331. for (j = 0; j < 20; j++) {
  332. cbseed = 521 * cbseed + 259;
  333. *cdn_vector++ = tmp_gain * (int16_t) cbseed;
  334. }
  335. }
  336. break;
  337. case I_F_Q:
  338. cbseed = -44; // random codebook index
  339. for (i = 0; i < 4; i++) {
  340. tmp_gain = gain[i] * QCELP_RATE_FULL_CODEBOOK_RATIO;
  341. for (j = 0; j < 40; j++)
  342. *cdn_vector++ = tmp_gain * qcelp_rate_full_codebook[cbseed++ & 127];
  343. }
  344. break;
  345. case SILENCE:
  346. memset(cdn_vector, 0, 160 * sizeof(float));
  347. break;
  348. }
  349. }
  350. /**
  351. * Apply generic gain control.
  352. *
  353. * @param v_out output vector
  354. * @param v_in gain-controlled vector
  355. * @param v_ref vector to control gain of
  356. *
  357. * TIA/EIA/IS-733 2.4.8.3, 2.4.8.6
  358. */
  359. static void apply_gain_ctrl(float *v_out, const float *v_ref, const float *v_in)
  360. {
  361. int i;
  362. for (i = 0; i < 160; i += 40)
  363. ff_scale_vector_to_given_sum_of_squares(v_out + i, v_in + i,
  364. ff_scalarproduct_float_c(v_ref + i,
  365. v_ref + i,
  366. 40),
  367. 40);
  368. }
  369. /**
  370. * Apply filter in pitch-subframe steps.
  371. *
  372. * @param memory buffer for the previous state of the filter
  373. * - must be able to contain 303 elements
  374. * - the 143 first elements are from the previous state
  375. * - the next 160 are for output
  376. * @param v_in input filter vector
  377. * @param gain per-subframe gain array, each element is between 0.0 and 2.0
  378. * @param lag per-subframe lag array, each element is
  379. * - between 16 and 143 if its corresponding pfrac is 0,
  380. * - between 16 and 139 otherwise
  381. * @param pfrac per-subframe boolean array, 1 if the lag is fractional, 0
  382. * otherwise
  383. *
  384. * @return filter output vector
  385. */
  386. static const float *do_pitchfilter(float memory[303], const float v_in[160],
  387. const float gain[4], const uint8_t *lag,
  388. const uint8_t pfrac[4])
  389. {
  390. int i, j;
  391. float *v_lag, *v_out;
  392. const float *v_len;
  393. v_out = memory + 143; // Output vector starts at memory[143].
  394. for (i = 0; i < 4; i++) {
  395. if (gain[i]) {
  396. v_lag = memory + 143 + 40 * i - lag[i];
  397. for (v_len = v_in + 40; v_in < v_len; v_in++) {
  398. if (pfrac[i]) { // If it is a fractional lag...
  399. for (j = 0, *v_out = 0.; j < 4; j++)
  400. *v_out += qcelp_hammsinc_table[j] * (v_lag[j - 4] + v_lag[3 - j]);
  401. } else
  402. *v_out = *v_lag;
  403. *v_out = *v_in + gain[i] * *v_out;
  404. v_lag++;
  405. v_out++;
  406. }
  407. } else {
  408. memcpy(v_out, v_in, 40 * sizeof(float));
  409. v_in += 40;
  410. v_out += 40;
  411. }
  412. }
  413. memmove(memory, memory + 160, 143 * sizeof(float));
  414. return memory + 143;
  415. }
  416. /**
  417. * Apply pitch synthesis filter and pitch prefilter to the scaled codebook vector.
  418. * TIA/EIA/IS-733 2.4.5.2, 2.4.8.7.2
  419. *
  420. * @param q the context
  421. * @param cdn_vector the scaled codebook vector
  422. */
  423. static void apply_pitch_filters(QCELPContext *q, float *cdn_vector)
  424. {
  425. int i;
  426. const float *v_synthesis_filtered, *v_pre_filtered;
  427. if (q->bitrate >= RATE_HALF || q->bitrate == SILENCE ||
  428. (q->bitrate == I_F_Q && (q->prev_bitrate >= RATE_HALF))) {
  429. if (q->bitrate >= RATE_HALF) {
  430. // Compute gain & lag for the whole frame.
  431. for (i = 0; i < 4; i++) {
  432. q->pitch_gain[i] = q->frame.plag[i] ? (q->frame.pgain[i] + 1) * 0.25 : 0.0;
  433. q->pitch_lag[i] = q->frame.plag[i] + 16;
  434. }
  435. } else {
  436. float max_pitch_gain;
  437. if (q->bitrate == I_F_Q) {
  438. if (q->erasure_count < 3)
  439. max_pitch_gain = 0.9 - 0.3 * (q->erasure_count - 1);
  440. else
  441. max_pitch_gain = 0.0;
  442. } else {
  443. assert(q->bitrate == SILENCE);
  444. max_pitch_gain = 1.0;
  445. }
  446. for (i = 0; i < 4; i++)
  447. q->pitch_gain[i] = FFMIN(q->pitch_gain[i], max_pitch_gain);
  448. memset(q->frame.pfrac, 0, sizeof(q->frame.pfrac));
  449. }
  450. // pitch synthesis filter
  451. v_synthesis_filtered = do_pitchfilter(q->pitch_synthesis_filter_mem,
  452. cdn_vector, q->pitch_gain,
  453. q->pitch_lag, q->frame.pfrac);
  454. // pitch prefilter update
  455. for (i = 0; i < 4; i++)
  456. q->pitch_gain[i] = 0.5 * FFMIN(q->pitch_gain[i], 1.0);
  457. v_pre_filtered = do_pitchfilter(q->pitch_pre_filter_mem,
  458. v_synthesis_filtered,
  459. q->pitch_gain, q->pitch_lag,
  460. q->frame.pfrac);
  461. apply_gain_ctrl(cdn_vector, v_synthesis_filtered, v_pre_filtered);
  462. } else {
  463. memcpy(q->pitch_synthesis_filter_mem, cdn_vector + 17, 143 * sizeof(float));
  464. memcpy(q->pitch_pre_filter_mem, cdn_vector + 17, 143 * sizeof(float));
  465. memset(q->pitch_gain, 0, sizeof(q->pitch_gain));
  466. memset(q->pitch_lag, 0, sizeof(q->pitch_lag));
  467. }
  468. }
  469. /**
  470. * Reconstruct LPC coefficients from the line spectral pair frequencies
  471. * and perform bandwidth expansion.
  472. *
  473. * @param lspf line spectral pair frequencies
  474. * @param lpc linear predictive coding coefficients
  475. *
  476. * @note: bandwidth_expansion_coeff could be precalculated into a table
  477. * but it seems to be slower on x86
  478. *
  479. * TIA/EIA/IS-733 2.4.3.3.5
  480. */
  481. static void lspf2lpc(const float *lspf, float *lpc)
  482. {
  483. double lsp[10];
  484. double bandwidth_expansion_coeff = QCELP_BANDWIDTH_EXPANSION_COEFF;
  485. int i;
  486. for (i = 0; i < 10; i++)
  487. lsp[i] = cos(M_PI * lspf[i]);
  488. ff_acelp_lspd2lpc(lsp, lpc, 5);
  489. for (i = 0; i < 10; i++) {
  490. lpc[i] *= bandwidth_expansion_coeff;
  491. bandwidth_expansion_coeff *= QCELP_BANDWIDTH_EXPANSION_COEFF;
  492. }
  493. }
  494. /**
  495. * Interpolate LSP frequencies and compute LPC coefficients
  496. * for a given bitrate & pitch subframe.
  497. *
  498. * TIA/EIA/IS-733 2.4.3.3.4, 2.4.8.7.2
  499. *
  500. * @param q the context
  501. * @param curr_lspf LSP frequencies vector of the current frame
  502. * @param lpc float vector for the resulting LPC
  503. * @param subframe_num frame number in decoded stream
  504. */
  505. static void interpolate_lpc(QCELPContext *q, const float *curr_lspf,
  506. float *lpc, const int subframe_num)
  507. {
  508. float interpolated_lspf[10];
  509. float weight;
  510. if (q->bitrate >= RATE_QUARTER)
  511. weight = 0.25 * (subframe_num + 1);
  512. else if (q->bitrate == RATE_OCTAVE && !subframe_num)
  513. weight = 0.625;
  514. else
  515. weight = 1.0;
  516. if (weight != 1.0) {
  517. ff_weighted_vector_sumf(interpolated_lspf, curr_lspf, q->prev_lspf,
  518. weight, 1.0 - weight, 10);
  519. lspf2lpc(interpolated_lspf, lpc);
  520. } else if (q->bitrate >= RATE_QUARTER ||
  521. (q->bitrate == I_F_Q && !subframe_num))
  522. lspf2lpc(curr_lspf, lpc);
  523. else if (q->bitrate == SILENCE && !subframe_num)
  524. lspf2lpc(q->prev_lspf, lpc);
  525. }
  526. static qcelp_packet_rate buf_size2bitrate(const int buf_size)
  527. {
  528. switch (buf_size) {
  529. case 35: return RATE_FULL;
  530. case 17: return RATE_HALF;
  531. case 8: return RATE_QUARTER;
  532. case 4: return RATE_OCTAVE;
  533. case 1: return SILENCE;
  534. }
  535. return I_F_Q;
  536. }
  537. /**
  538. * Determine the bitrate from the frame size and/or the first byte of the frame.
  539. *
  540. * @param avctx the AV codec context
  541. * @param buf_size length of the buffer
  542. * @param buf the bufffer
  543. *
  544. * @return the bitrate on success,
  545. * I_F_Q if the bitrate cannot be satisfactorily determined
  546. *
  547. * TIA/EIA/IS-733 2.4.8.7.1
  548. */
  549. static qcelp_packet_rate determine_bitrate(AVCodecContext *avctx,
  550. const int buf_size,
  551. const uint8_t **buf)
  552. {
  553. qcelp_packet_rate bitrate;
  554. if ((bitrate = buf_size2bitrate(buf_size)) >= 0) {
  555. if (bitrate > **buf) {
  556. QCELPContext *q = avctx->priv_data;
  557. if (!q->warned_buf_mismatch_bitrate) {
  558. av_log(avctx, AV_LOG_WARNING,
  559. "Claimed bitrate and buffer size mismatch.\n");
  560. q->warned_buf_mismatch_bitrate = 1;
  561. }
  562. bitrate = **buf;
  563. } else if (bitrate < **buf) {
  564. av_log(avctx, AV_LOG_ERROR,
  565. "Buffer is too small for the claimed bitrate.\n");
  566. return I_F_Q;
  567. }
  568. (*buf)++;
  569. } else if ((bitrate = buf_size2bitrate(buf_size + 1)) >= 0) {
  570. av_log(avctx, AV_LOG_WARNING,
  571. "Bitrate byte is missing, guessing the bitrate from packet size.\n");
  572. } else
  573. return I_F_Q;
  574. if (bitrate == SILENCE) {
  575. //FIXME: Remove experimental warning when tested with samples.
  576. av_log_ask_for_sample(avctx, "'Blank frame handling is experimental.");
  577. }
  578. return bitrate;
  579. }
  580. static void warn_insufficient_frame_quality(AVCodecContext *avctx,
  581. const char *message)
  582. {
  583. av_log(avctx, AV_LOG_WARNING, "Frame #%d, IFQ: %s\n",
  584. avctx->frame_number, message);
  585. }
  586. static void postfilter(QCELPContext *q, float *samples, float *lpc)
  587. {
  588. static const float pow_0_775[10] = {
  589. 0.775000, 0.600625, 0.465484, 0.360750, 0.279582,
  590. 0.216676, 0.167924, 0.130141, 0.100859, 0.078166
  591. }, pow_0_625[10] = {
  592. 0.625000, 0.390625, 0.244141, 0.152588, 0.095367,
  593. 0.059605, 0.037253, 0.023283, 0.014552, 0.009095
  594. };
  595. float lpc_s[10], lpc_p[10], pole_out[170], zero_out[160];
  596. int n;
  597. for (n = 0; n < 10; n++) {
  598. lpc_s[n] = lpc[n] * pow_0_625[n];
  599. lpc_p[n] = lpc[n] * pow_0_775[n];
  600. }
  601. ff_celp_lp_zero_synthesis_filterf(zero_out, lpc_s,
  602. q->formant_mem + 10, 160, 10);
  603. memcpy(pole_out, q->postfilter_synth_mem, sizeof(float) * 10);
  604. ff_celp_lp_synthesis_filterf(pole_out + 10, lpc_p, zero_out, 160, 10);
  605. memcpy(q->postfilter_synth_mem, pole_out + 160, sizeof(float) * 10);
  606. ff_tilt_compensation(&q->postfilter_tilt_mem, 0.3, pole_out + 10, 160);
  607. ff_adaptive_gain_control(samples, pole_out + 10,
  608. ff_scalarproduct_float_c(q->formant_mem + 10,
  609. q->formant_mem + 10, 160),
  610. 160, 0.9375, &q->postfilter_agc_mem);
  611. }
  612. static int qcelp_decode_frame(AVCodecContext *avctx, void *data,
  613. int *got_frame_ptr, AVPacket *avpkt)
  614. {
  615. const uint8_t *buf = avpkt->data;
  616. int buf_size = avpkt->size;
  617. QCELPContext *q = avctx->priv_data;
  618. float *outbuffer;
  619. int i, ret;
  620. float quantized_lspf[10], lpc[10];
  621. float gain[16];
  622. float *formant_mem;
  623. /* get output buffer */
  624. q->avframe.nb_samples = 160;
  625. if ((ret = avctx->get_buffer(avctx, &q->avframe)) < 0) {
  626. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  627. return ret;
  628. }
  629. outbuffer = (float *)q->avframe.data[0];
  630. if ((q->bitrate = determine_bitrate(avctx, buf_size, &buf)) == I_F_Q) {
  631. warn_insufficient_frame_quality(avctx, "bitrate cannot be determined.");
  632. goto erasure;
  633. }
  634. if (q->bitrate == RATE_OCTAVE &&
  635. (q->first16bits = AV_RB16(buf)) == 0xFFFF) {
  636. warn_insufficient_frame_quality(avctx, "Bitrate is 1/8 and first 16 bits are on.");
  637. goto erasure;
  638. }
  639. if (q->bitrate > SILENCE) {
  640. const QCELPBitmap *bitmaps = qcelp_unpacking_bitmaps_per_rate[q->bitrate];
  641. const QCELPBitmap *bitmaps_end = qcelp_unpacking_bitmaps_per_rate[q->bitrate] +
  642. qcelp_unpacking_bitmaps_lengths[q->bitrate];
  643. uint8_t *unpacked_data = (uint8_t *)&q->frame;
  644. init_get_bits(&q->gb, buf, 8 * buf_size);
  645. memset(&q->frame, 0, sizeof(QCELPFrame));
  646. for (; bitmaps < bitmaps_end; bitmaps++)
  647. unpacked_data[bitmaps->index] |= get_bits(&q->gb, bitmaps->bitlen) << bitmaps->bitpos;
  648. // Check for erasures/blanks on rates 1, 1/4 and 1/8.
  649. if (q->frame.reserved) {
  650. warn_insufficient_frame_quality(avctx, "Wrong data in reserved frame area.");
  651. goto erasure;
  652. }
  653. if (q->bitrate == RATE_QUARTER &&
  654. codebook_sanity_check_for_rate_quarter(q->frame.cbgain)) {
  655. warn_insufficient_frame_quality(avctx, "Codebook gain sanity check failed.");
  656. goto erasure;
  657. }
  658. if (q->bitrate >= RATE_HALF) {
  659. for (i = 0; i < 4; i++) {
  660. if (q->frame.pfrac[i] && q->frame.plag[i] >= 124) {
  661. warn_insufficient_frame_quality(avctx, "Cannot initialize pitch filter.");
  662. goto erasure;
  663. }
  664. }
  665. }
  666. }
  667. decode_gain_and_index(q, gain);
  668. compute_svector(q, gain, outbuffer);
  669. if (decode_lspf(q, quantized_lspf) < 0) {
  670. warn_insufficient_frame_quality(avctx, "Badly received packets in frame.");
  671. goto erasure;
  672. }
  673. apply_pitch_filters(q, outbuffer);
  674. if (q->bitrate == I_F_Q) {
  675. erasure:
  676. q->bitrate = I_F_Q;
  677. q->erasure_count++;
  678. decode_gain_and_index(q, gain);
  679. compute_svector(q, gain, outbuffer);
  680. decode_lspf(q, quantized_lspf);
  681. apply_pitch_filters(q, outbuffer);
  682. } else
  683. q->erasure_count = 0;
  684. formant_mem = q->formant_mem + 10;
  685. for (i = 0; i < 4; i++) {
  686. interpolate_lpc(q, quantized_lspf, lpc, i);
  687. ff_celp_lp_synthesis_filterf(formant_mem, lpc, outbuffer + i * 40, 40, 10);
  688. formant_mem += 40;
  689. }
  690. // postfilter, as per TIA/EIA/IS-733 2.4.8.6
  691. postfilter(q, outbuffer, lpc);
  692. memcpy(q->formant_mem, q->formant_mem + 160, 10 * sizeof(float));
  693. memcpy(q->prev_lspf, quantized_lspf, sizeof(q->prev_lspf));
  694. q->prev_bitrate = q->bitrate;
  695. *got_frame_ptr = 1;
  696. *(AVFrame *)data = q->avframe;
  697. return buf_size;
  698. }
  699. AVCodec ff_qcelp_decoder = {
  700. .name = "qcelp",
  701. .type = AVMEDIA_TYPE_AUDIO,
  702. .id = AV_CODEC_ID_QCELP,
  703. .init = qcelp_decode_init,
  704. .decode = qcelp_decode_frame,
  705. .capabilities = CODEC_CAP_DR1,
  706. .priv_data_size = sizeof(QCELPContext),
  707. .long_name = NULL_IF_CONFIG_SMALL("QCELP / PureVoice"),
  708. };