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