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