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