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.

536 lines
18KB

  1. /*
  2. * Real Audio 1.0 (14.4K) encoder
  3. * Copyright (c) 2010 Francesco Lavra <francescolavra@interfree.it>
  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. * Real Audio 1.0 (14.4K) encoder
  24. * @author Francesco Lavra <francescolavra@interfree.it>
  25. */
  26. #include <float.h>
  27. #include "avcodec.h"
  28. #include "put_bits.h"
  29. #include "celp_filters.h"
  30. #include "ra144.h"
  31. static av_cold int ra144_encode_close(AVCodecContext *avctx)
  32. {
  33. RA144Context *ractx = avctx->priv_data;
  34. ff_lpc_end(&ractx->lpc_ctx);
  35. av_freep(&avctx->coded_frame);
  36. return 0;
  37. }
  38. static av_cold int ra144_encode_init(AVCodecContext * avctx)
  39. {
  40. RA144Context *ractx;
  41. int ret;
  42. if (avctx->channels != 1) {
  43. av_log(avctx, AV_LOG_ERROR, "invalid number of channels: %d\n",
  44. avctx->channels);
  45. return -1;
  46. }
  47. avctx->frame_size = NBLOCKS * BLOCKSIZE;
  48. avctx->bit_rate = 8000;
  49. ractx = avctx->priv_data;
  50. ractx->lpc_coef[0] = ractx->lpc_tables[0];
  51. ractx->lpc_coef[1] = ractx->lpc_tables[1];
  52. ractx->avctx = avctx;
  53. ret = ff_lpc_init(&ractx->lpc_ctx, avctx->frame_size, LPC_ORDER,
  54. FF_LPC_TYPE_LEVINSON);
  55. if (ret < 0)
  56. goto error;
  57. avctx->coded_frame = avcodec_alloc_frame();
  58. if (!avctx->coded_frame) {
  59. ret = AVERROR(ENOMEM);
  60. goto error;
  61. }
  62. return 0;
  63. error:
  64. ra144_encode_close(avctx);
  65. return ret;
  66. }
  67. /**
  68. * Quantize a value by searching a sorted table for the element with the
  69. * nearest value
  70. *
  71. * @param value value to quantize
  72. * @param table array containing the quantization table
  73. * @param size size of the quantization table
  74. * @return index of the quantization table corresponding to the element with the
  75. * nearest value
  76. */
  77. static int quantize(int value, const int16_t *table, unsigned int size)
  78. {
  79. unsigned int low = 0, high = size - 1;
  80. while (1) {
  81. int index = (low + high) >> 1;
  82. int error = table[index] - value;
  83. if (index == low)
  84. return table[high] + error > value ? low : high;
  85. if (error > 0) {
  86. high = index;
  87. } else {
  88. low = index;
  89. }
  90. }
  91. }
  92. /**
  93. * Orthogonalize a vector to another vector
  94. *
  95. * @param v vector to orthogonalize
  96. * @param u vector against which orthogonalization is performed
  97. */
  98. static void orthogonalize(float *v, const float *u)
  99. {
  100. int i;
  101. float num = 0, den = 0;
  102. for (i = 0; i < BLOCKSIZE; i++) {
  103. num += v[i] * u[i];
  104. den += u[i] * u[i];
  105. }
  106. num /= den;
  107. for (i = 0; i < BLOCKSIZE; i++)
  108. v[i] -= num * u[i];
  109. }
  110. /**
  111. * Calculate match score and gain of an LPC-filtered vector with respect to
  112. * input data, possibly othogonalizing it to up to 2 other vectors
  113. *
  114. * @param work array used to calculate the filtered vector
  115. * @param coefs coefficients of the LPC filter
  116. * @param vect original vector
  117. * @param ortho1 first vector against which orthogonalization is performed
  118. * @param ortho2 second vector against which orthogonalization is performed
  119. * @param data input data
  120. * @param score pointer to variable where match score is returned
  121. * @param gain pointer to variable where gain is returned
  122. */
  123. static void get_match_score(float *work, const float *coefs, float *vect,
  124. const float *ortho1, const float *ortho2,
  125. const float *data, float *score, float *gain)
  126. {
  127. float c, g;
  128. int i;
  129. ff_celp_lp_synthesis_filterf(work, coefs, vect, BLOCKSIZE, LPC_ORDER);
  130. if (ortho1)
  131. orthogonalize(work, ortho1);
  132. if (ortho2)
  133. orthogonalize(work, ortho2);
  134. c = g = 0;
  135. for (i = 0; i < BLOCKSIZE; i++) {
  136. g += work[i] * work[i];
  137. c += data[i] * work[i];
  138. }
  139. if (c <= 0) {
  140. *score = 0;
  141. return;
  142. }
  143. *gain = c / g;
  144. *score = *gain * c;
  145. }
  146. /**
  147. * Create a vector from the adaptive codebook at a given lag value
  148. *
  149. * @param vect array where vector is stored
  150. * @param cb adaptive codebook
  151. * @param lag lag value
  152. */
  153. static void create_adapt_vect(float *vect, const int16_t *cb, int lag)
  154. {
  155. int i;
  156. cb += BUFFERSIZE - lag;
  157. for (i = 0; i < FFMIN(BLOCKSIZE, lag); i++)
  158. vect[i] = cb[i];
  159. if (lag < BLOCKSIZE)
  160. for (i = 0; i < BLOCKSIZE - lag; i++)
  161. vect[lag + i] = cb[i];
  162. }
  163. /**
  164. * Search the adaptive codebook for the best entry and gain and remove its
  165. * contribution from input data
  166. *
  167. * @param adapt_cb array from which the adaptive codebook is extracted
  168. * @param work array used to calculate LPC-filtered vectors
  169. * @param coefs coefficients of the LPC filter
  170. * @param data input data
  171. * @return index of the best entry of the adaptive codebook
  172. */
  173. static int adaptive_cb_search(const int16_t *adapt_cb, float *work,
  174. const float *coefs, float *data)
  175. {
  176. int i, best_vect;
  177. float score, gain, best_score, best_gain;
  178. float exc[BLOCKSIZE];
  179. gain = best_score = 0;
  180. for (i = BLOCKSIZE / 2; i <= BUFFERSIZE; i++) {
  181. create_adapt_vect(exc, adapt_cb, i);
  182. get_match_score(work, coefs, exc, NULL, NULL, data, &score, &gain);
  183. if (score > best_score) {
  184. best_score = score;
  185. best_vect = i;
  186. best_gain = gain;
  187. }
  188. }
  189. if (!best_score)
  190. return 0;
  191. /**
  192. * Re-calculate the filtered vector from the vector with maximum match score
  193. * and remove its contribution from input data.
  194. */
  195. create_adapt_vect(exc, adapt_cb, best_vect);
  196. ff_celp_lp_synthesis_filterf(work, coefs, exc, BLOCKSIZE, LPC_ORDER);
  197. for (i = 0; i < BLOCKSIZE; i++)
  198. data[i] -= best_gain * work[i];
  199. return best_vect - BLOCKSIZE / 2 + 1;
  200. }
  201. /**
  202. * Find the best vector of a fixed codebook by applying an LPC filter to
  203. * codebook entries, possibly othogonalizing them to up to 2 other vectors and
  204. * matching the results with input data
  205. *
  206. * @param work array used to calculate the filtered vectors
  207. * @param coefs coefficients of the LPC filter
  208. * @param cb fixed codebook
  209. * @param ortho1 first vector against which orthogonalization is performed
  210. * @param ortho2 second vector against which orthogonalization is performed
  211. * @param data input data
  212. * @param idx pointer to variable where the index of the best codebook entry is
  213. * returned
  214. * @param gain pointer to variable where the gain of the best codebook entry is
  215. * returned
  216. */
  217. static void find_best_vect(float *work, const float *coefs,
  218. const int8_t cb[][BLOCKSIZE], const float *ortho1,
  219. const float *ortho2, float *data, int *idx,
  220. float *gain)
  221. {
  222. int i, j;
  223. float g, score, best_score;
  224. float vect[BLOCKSIZE];
  225. *idx = *gain = best_score = 0;
  226. for (i = 0; i < FIXED_CB_SIZE; i++) {
  227. for (j = 0; j < BLOCKSIZE; j++)
  228. vect[j] = cb[i][j];
  229. get_match_score(work, coefs, vect, ortho1, ortho2, data, &score, &g);
  230. if (score > best_score) {
  231. best_score = score;
  232. *idx = i;
  233. *gain = g;
  234. }
  235. }
  236. }
  237. /**
  238. * Search the two fixed codebooks for the best entry and gain
  239. *
  240. * @param work array used to calculate LPC-filtered vectors
  241. * @param coefs coefficients of the LPC filter
  242. * @param data input data
  243. * @param cba_idx index of the best entry of the adaptive codebook
  244. * @param cb1_idx pointer to variable where the index of the best entry of the
  245. * first fixed codebook is returned
  246. * @param cb2_idx pointer to variable where the index of the best entry of the
  247. * second fixed codebook is returned
  248. */
  249. static void fixed_cb_search(float *work, const float *coefs, float *data,
  250. int cba_idx, int *cb1_idx, int *cb2_idx)
  251. {
  252. int i, ortho_cb1;
  253. float gain;
  254. float cba_vect[BLOCKSIZE], cb1_vect[BLOCKSIZE];
  255. float vect[BLOCKSIZE];
  256. /**
  257. * The filtered vector from the adaptive codebook can be retrieved from
  258. * work, because this function is called just after adaptive_cb_search().
  259. */
  260. if (cba_idx)
  261. memcpy(cba_vect, work, sizeof(cba_vect));
  262. find_best_vect(work, coefs, ff_cb1_vects, cba_idx ? cba_vect : NULL, NULL,
  263. data, cb1_idx, &gain);
  264. /**
  265. * Re-calculate the filtered vector from the vector with maximum match score
  266. * and remove its contribution from input data.
  267. */
  268. if (gain) {
  269. for (i = 0; i < BLOCKSIZE; i++)
  270. vect[i] = ff_cb1_vects[*cb1_idx][i];
  271. ff_celp_lp_synthesis_filterf(work, coefs, vect, BLOCKSIZE, LPC_ORDER);
  272. if (cba_idx)
  273. orthogonalize(work, cba_vect);
  274. for (i = 0; i < BLOCKSIZE; i++)
  275. data[i] -= gain * work[i];
  276. memcpy(cb1_vect, work, sizeof(cb1_vect));
  277. ortho_cb1 = 1;
  278. } else
  279. ortho_cb1 = 0;
  280. find_best_vect(work, coefs, ff_cb2_vects, cba_idx ? cba_vect : NULL,
  281. ortho_cb1 ? cb1_vect : NULL, data, cb2_idx, &gain);
  282. }
  283. /**
  284. * Encode a subblock of the current frame
  285. *
  286. * @param ractx encoder context
  287. * @param sblock_data input data of the subblock
  288. * @param lpc_coefs coefficients of the LPC filter
  289. * @param rms RMS of the reflection coefficients
  290. * @param pb pointer to PutBitContext of the current frame
  291. */
  292. static void ra144_encode_subblock(RA144Context *ractx,
  293. const int16_t *sblock_data,
  294. const int16_t *lpc_coefs, unsigned int rms,
  295. PutBitContext *pb)
  296. {
  297. float data[BLOCKSIZE], work[LPC_ORDER + BLOCKSIZE];
  298. float coefs[LPC_ORDER];
  299. float zero[BLOCKSIZE], cba[BLOCKSIZE], cb1[BLOCKSIZE], cb2[BLOCKSIZE];
  300. int16_t cba_vect[BLOCKSIZE];
  301. int cba_idx, cb1_idx, cb2_idx, gain;
  302. int i, n, m[3];
  303. float g[3];
  304. float error, best_error;
  305. for (i = 0; i < LPC_ORDER; i++) {
  306. work[i] = ractx->curr_sblock[BLOCKSIZE + i];
  307. coefs[i] = lpc_coefs[i] * (1/4096.0);
  308. }
  309. /**
  310. * Calculate the zero-input response of the LPC filter and subtract it from
  311. * input data.
  312. */
  313. memset(data, 0, sizeof(data));
  314. ff_celp_lp_synthesis_filterf(work + LPC_ORDER, coefs, data, BLOCKSIZE,
  315. LPC_ORDER);
  316. for (i = 0; i < BLOCKSIZE; i++) {
  317. zero[i] = work[LPC_ORDER + i];
  318. data[i] = sblock_data[i] - zero[i];
  319. }
  320. /**
  321. * Codebook search is performed without taking into account the contribution
  322. * of the previous subblock, since it has been just subtracted from input
  323. * data.
  324. */
  325. memset(work, 0, LPC_ORDER * sizeof(*work));
  326. cba_idx = adaptive_cb_search(ractx->adapt_cb, work + LPC_ORDER, coefs,
  327. data);
  328. if (cba_idx) {
  329. /**
  330. * The filtered vector from the adaptive codebook can be retrieved from
  331. * work, see implementation of adaptive_cb_search().
  332. */
  333. memcpy(cba, work + LPC_ORDER, sizeof(cba));
  334. ff_copy_and_dup(cba_vect, ractx->adapt_cb, cba_idx + BLOCKSIZE / 2 - 1);
  335. m[0] = (ff_irms(cba_vect) * rms) >> 12;
  336. }
  337. fixed_cb_search(work + LPC_ORDER, coefs, data, cba_idx, &cb1_idx, &cb2_idx);
  338. for (i = 0; i < BLOCKSIZE; i++) {
  339. cb1[i] = ff_cb1_vects[cb1_idx][i];
  340. cb2[i] = ff_cb2_vects[cb2_idx][i];
  341. }
  342. ff_celp_lp_synthesis_filterf(work + LPC_ORDER, coefs, cb1, BLOCKSIZE,
  343. LPC_ORDER);
  344. memcpy(cb1, work + LPC_ORDER, sizeof(cb1));
  345. m[1] = (ff_cb1_base[cb1_idx] * rms) >> 8;
  346. ff_celp_lp_synthesis_filterf(work + LPC_ORDER, coefs, cb2, BLOCKSIZE,
  347. LPC_ORDER);
  348. memcpy(cb2, work + LPC_ORDER, sizeof(cb2));
  349. m[2] = (ff_cb2_base[cb2_idx] * rms) >> 8;
  350. best_error = FLT_MAX;
  351. gain = 0;
  352. for (n = 0; n < 256; n++) {
  353. g[1] = ((ff_gain_val_tab[n][1] * m[1]) >> ff_gain_exp_tab[n]) *
  354. (1/4096.0);
  355. g[2] = ((ff_gain_val_tab[n][2] * m[2]) >> ff_gain_exp_tab[n]) *
  356. (1/4096.0);
  357. error = 0;
  358. if (cba_idx) {
  359. g[0] = ((ff_gain_val_tab[n][0] * m[0]) >> ff_gain_exp_tab[n]) *
  360. (1/4096.0);
  361. for (i = 0; i < BLOCKSIZE; i++) {
  362. data[i] = zero[i] + g[0] * cba[i] + g[1] * cb1[i] +
  363. g[2] * cb2[i];
  364. error += (data[i] - sblock_data[i]) *
  365. (data[i] - sblock_data[i]);
  366. }
  367. } else {
  368. for (i = 0; i < BLOCKSIZE; i++) {
  369. data[i] = zero[i] + g[1] * cb1[i] + g[2] * cb2[i];
  370. error += (data[i] - sblock_data[i]) *
  371. (data[i] - sblock_data[i]);
  372. }
  373. }
  374. if (error < best_error) {
  375. best_error = error;
  376. gain = n;
  377. }
  378. }
  379. put_bits(pb, 7, cba_idx);
  380. put_bits(pb, 8, gain);
  381. put_bits(pb, 7, cb1_idx);
  382. put_bits(pb, 7, cb2_idx);
  383. ff_subblock_synthesis(ractx, lpc_coefs, cba_idx, cb1_idx, cb2_idx, rms,
  384. gain);
  385. }
  386. static int ra144_encode_frame(AVCodecContext *avctx, uint8_t *frame,
  387. int buf_size, void *data)
  388. {
  389. static const uint8_t sizes[LPC_ORDER] = {64, 32, 32, 16, 16, 8, 8, 8, 8, 4};
  390. static const uint8_t bit_sizes[LPC_ORDER] = {6, 5, 5, 4, 4, 3, 3, 3, 3, 2};
  391. RA144Context *ractx;
  392. PutBitContext pb;
  393. int32_t lpc_data[NBLOCKS * BLOCKSIZE];
  394. int32_t lpc_coefs[LPC_ORDER][MAX_LPC_ORDER];
  395. int shift[LPC_ORDER];
  396. int16_t block_coefs[NBLOCKS][LPC_ORDER];
  397. int lpc_refl[LPC_ORDER]; /**< reflection coefficients of the frame */
  398. unsigned int refl_rms[NBLOCKS]; /**< RMS of the reflection coefficients */
  399. const int16_t *samples = data;
  400. int energy = 0;
  401. int i, idx;
  402. if (buf_size < FRAMESIZE) {
  403. av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");
  404. return 0;
  405. }
  406. ractx = avctx->priv_data;
  407. /**
  408. * Since the LPC coefficients are calculated on a frame centered over the
  409. * fourth subframe, to encode a given frame, data from the next frame is
  410. * needed. In each call to this function, the previous frame (whose data are
  411. * saved in the encoder context) is encoded, and data from the current frame
  412. * are saved in the encoder context to be used in the next function call.
  413. */
  414. for (i = 0; i < (2 * BLOCKSIZE + BLOCKSIZE / 2); i++) {
  415. lpc_data[i] = ractx->curr_block[BLOCKSIZE + BLOCKSIZE / 2 + i];
  416. energy += (lpc_data[i] * lpc_data[i]) >> 4;
  417. }
  418. for (i = 2 * BLOCKSIZE + BLOCKSIZE / 2; i < NBLOCKS * BLOCKSIZE; i++) {
  419. lpc_data[i] = *((int16_t *)data + i - 2 * BLOCKSIZE - BLOCKSIZE / 2) >>
  420. 2;
  421. energy += (lpc_data[i] * lpc_data[i]) >> 4;
  422. }
  423. energy = ff_energy_tab[quantize(ff_t_sqrt(energy >> 5) >> 10, ff_energy_tab,
  424. 32)];
  425. ff_lpc_calc_coefs(&ractx->lpc_ctx, lpc_data, NBLOCKS * BLOCKSIZE, LPC_ORDER,
  426. LPC_ORDER, 16, lpc_coefs, shift, FF_LPC_TYPE_LEVINSON,
  427. 0, ORDER_METHOD_EST, 12, 0);
  428. for (i = 0; i < LPC_ORDER; i++)
  429. block_coefs[NBLOCKS - 1][i] = -(lpc_coefs[LPC_ORDER - 1][i] <<
  430. (12 - shift[LPC_ORDER - 1]));
  431. /**
  432. * TODO: apply perceptual weighting of the input speech through bandwidth
  433. * expansion of the LPC filter.
  434. */
  435. if (ff_eval_refl(lpc_refl, block_coefs[NBLOCKS - 1], avctx)) {
  436. /**
  437. * The filter is unstable: use the coefficients of the previous frame.
  438. */
  439. ff_int_to_int16(block_coefs[NBLOCKS - 1], ractx->lpc_coef[1]);
  440. if (ff_eval_refl(lpc_refl, block_coefs[NBLOCKS - 1], avctx)) {
  441. /* the filter is still unstable. set reflection coeffs to zero. */
  442. memset(lpc_refl, 0, sizeof(lpc_refl));
  443. }
  444. }
  445. init_put_bits(&pb, frame, buf_size);
  446. for (i = 0; i < LPC_ORDER; i++) {
  447. idx = quantize(lpc_refl[i], ff_lpc_refl_cb[i], sizes[i]);
  448. put_bits(&pb, bit_sizes[i], idx);
  449. lpc_refl[i] = ff_lpc_refl_cb[i][idx];
  450. }
  451. ractx->lpc_refl_rms[0] = ff_rms(lpc_refl);
  452. ff_eval_coefs(ractx->lpc_coef[0], lpc_refl);
  453. refl_rms[0] = ff_interp(ractx, block_coefs[0], 1, 1, ractx->old_energy);
  454. refl_rms[1] = ff_interp(ractx, block_coefs[1], 2,
  455. energy <= ractx->old_energy,
  456. ff_t_sqrt(energy * ractx->old_energy) >> 12);
  457. refl_rms[2] = ff_interp(ractx, block_coefs[2], 3, 0, energy);
  458. refl_rms[3] = ff_rescale_rms(ractx->lpc_refl_rms[0], energy);
  459. ff_int_to_int16(block_coefs[NBLOCKS - 1], ractx->lpc_coef[0]);
  460. put_bits(&pb, 5, quantize(energy, ff_energy_tab, 32));
  461. for (i = 0; i < NBLOCKS; i++)
  462. ra144_encode_subblock(ractx, ractx->curr_block + i * BLOCKSIZE,
  463. block_coefs[i], refl_rms[i], &pb);
  464. flush_put_bits(&pb);
  465. ractx->old_energy = energy;
  466. ractx->lpc_refl_rms[1] = ractx->lpc_refl_rms[0];
  467. FFSWAP(unsigned int *, ractx->lpc_coef[0], ractx->lpc_coef[1]);
  468. for (i = 0; i < NBLOCKS * BLOCKSIZE; i++)
  469. ractx->curr_block[i] = samples[i] >> 2;
  470. return FRAMESIZE;
  471. }
  472. AVCodec ff_ra_144_encoder = {
  473. .name = "real_144",
  474. .type = AVMEDIA_TYPE_AUDIO,
  475. .id = CODEC_ID_RA_144,
  476. .priv_data_size = sizeof(RA144Context),
  477. .init = ra144_encode_init,
  478. .encode = ra144_encode_frame,
  479. .close = ra144_encode_close,
  480. .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
  481. AV_SAMPLE_FMT_NONE },
  482. .long_name = NULL_IF_CONFIG_SMALL("RealAudio 1.0 (14.4K)"),
  483. };