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.

559 lines
19KB

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