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.

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