Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ra144enc.c @ 0d8837bd

History | View | Annotate | Download (17.2 KB)

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 "put_bits.h"
32
#include "celp_filters.h"
33
#include "ra144.h"
34

    
35

    
36
static av_cold int ra144_encode_init(AVCodecContext * avctx)
37
{
38
    RA144Context *ractx;
39

    
40
    if (avctx->sample_fmt != AV_SAMPLE_FMT_S16) {
41
        av_log(avctx, AV_LOG_ERROR, "invalid sample format\n");
42
        return -1;
43
    }
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->bit_rate = 8000;
51
    ractx = avctx->priv_data;
52
    ractx->lpc_coef[0] = ractx->lpc_tables[0];
53
    ractx->lpc_coef[1] = ractx->lpc_tables[1];
54
    ractx->avctx = avctx;
55
    ff_lpc_init(&ractx->lpc_ctx);
56
    return 0;
57
}
58

    
59

    
60
/**
61
 * Quantize a value by searching a sorted table for the element with the
62
 * nearest value
63
 *
64
 * @param value value to quantize
65
 * @param table array containing the quantization table
66
 * @param size size of the quantization table
67
 * @return index of the quantization table corresponding to the element with the
68
 *         nearest value
69
 */
70
static int quantize(int value, const int16_t *table, unsigned int size)
71
{
72
    unsigned int low = 0, high = size - 1;
73

    
74
    while (1) {
75
        int index = (low + high) >> 1;
76
        int error = table[index] - value;
77

    
78
        if (index == low)
79
            return table[high] + error > value ? low : high;
80
        if (error > 0) {
81
            high = index;
82
        } else {
83
            low = index;
84
        }
85
    }
86
}
87

    
88

    
89
/**
90
 * Orthogonalize a vector to another vector
91
 *
92
 * @param v vector to orthogonalize
93
 * @param u vector against which orthogonalization is performed
94
 */
95
static void orthogonalize(float *v, const float *u)
96
{
97
    int i;
98
    float num = 0, den = 0;
99

    
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

    
110
/**
111
 * Calculate match score and gain of an LPC-filtered vector with respect to
112
 * input data, possibly othogonalizing it to up to 2 other vectors
113
 *
114
 * @param work array used to calculate the filtered vector
115
 * @param coefs coefficients of the LPC filter
116
 * @param vect original vector
117
 * @param ortho1 first vector against which orthogonalization is performed
118
 * @param ortho2 second vector against which orthogonalization is performed
119
 * @param data input data
120
 * @param score pointer to variable where match score is returned
121
 * @param gain pointer to variable where gain is returned
122
 */
123
static void get_match_score(float *work, const float *coefs, float *vect,
124
                            const float *ortho1, const float *ortho2,
125
                            const float *data, float *score, float *gain)
126
{
127
    float c, g;
128
    int i;
129

    
130
    ff_celp_lp_synthesis_filterf(work, coefs, vect, BLOCKSIZE, LPC_ORDER);
131
    if (ortho1)
132
        orthogonalize(work, ortho1);
133
    if (ortho2)
134
        orthogonalize(work, ortho2);
135
    c = g = 0;
136
    for (i = 0; i < BLOCKSIZE; i++) {
137
        g += work[i] * work[i];
138
        c += data[i] * work[i];
139
    }
140
    if (c <= 0) {
141
        *score = 0;
142
        return;
143
    }
144
    *gain = c / g;
145
    *score = *gain * c;
146
}
147

    
148

    
149
/**
150
 * Create a vector from the adaptive codebook at a given lag value
151
 *
152
 * @param vect array where vector is stored
153
 * @param cb adaptive codebook
154
 * @param lag lag value
155
 */
156
static void create_adapt_vect(float *vect, const int16_t *cb, int lag)
157
{
158
    int i;
159

    
160
    cb += BUFFERSIZE - lag;
161
    for (i = 0; i < FFMIN(BLOCKSIZE, lag); i++)
162
        vect[i] = cb[i];
163
    if (lag < BLOCKSIZE)
164
        for (i = 0; i < BLOCKSIZE - lag; i++)
165
            vect[lag + i] = cb[i];
166
}
167

    
168

    
169
/**
170
 * Search the adaptive codebook for the best entry and gain and remove its
171
 * contribution from input data
172
 *
173
 * @param adapt_cb array from which the adaptive codebook is extracted
174
 * @param work array used to calculate LPC-filtered vectors
175
 * @param coefs coefficients of the LPC filter
176
 * @param data input data
177
 * @return index of the best entry of the adaptive codebook
178
 */
179
static int adaptive_cb_search(const int16_t *adapt_cb, float *work,
180
                              const float *coefs, float *data)
181
{
182
    int i, best_vect;
183
    float score, gain, best_score, best_gain;
184
    float exc[BLOCKSIZE];
185

    
186
    gain = best_score = 0;
187
    for (i = BLOCKSIZE / 2; i <= BUFFERSIZE; i++) {
188
        create_adapt_vect(exc, adapt_cb, i);
189
        get_match_score(work, coefs, exc, NULL, NULL, data, &score, &gain);
190
        if (score > best_score) {
191
            best_score = score;
192
            best_vect = i;
193
            best_gain = gain;
194
        }
195
    }
196
    if (!best_score)
197
        return 0;
198

    
199
    /**
200
     * Re-calculate the filtered vector from the vector with maximum match score
201
     * and remove its contribution from input data.
202
     */
203
    create_adapt_vect(exc, adapt_cb, best_vect);
204
    ff_celp_lp_synthesis_filterf(work, coefs, exc, BLOCKSIZE, LPC_ORDER);
205
    for (i = 0; i < BLOCKSIZE; i++)
206
        data[i] -= best_gain * work[i];
207
    return (best_vect - BLOCKSIZE / 2 + 1);
208
}
209

    
210

    
211
/**
212
 * Find the best vector of a fixed codebook by applying an LPC filter to
213
 * codebook entries, possibly othogonalizing them to up to 2 other vectors and
214
 * matching the results with input data
215
 *
216
 * @param work array used to calculate the filtered vectors
217
 * @param coefs coefficients of the LPC filter
218
 * @param cb fixed codebook
219
 * @param ortho1 first vector against which orthogonalization is performed
220
 * @param ortho2 second vector against which orthogonalization is performed
221
 * @param data input data
222
 * @param idx pointer to variable where the index of the best codebook entry is
223
 *        returned
224
 * @param gain pointer to variable where the gain of the best codebook entry is
225
 *        returned
226
 */
227
static void find_best_vect(float *work, const float *coefs,
228
                           const int8_t cb[][BLOCKSIZE], const float *ortho1,
229
                           const float *ortho2, float *data, int *idx,
230
                           float *gain)
231
{
232
    int i, j;
233
    float g, score, best_score;
234
    float vect[BLOCKSIZE];
235

    
236
    *idx = *gain = best_score = 0;
237
    for (i = 0; i < FIXED_CB_SIZE; i++) {
238
        for (j = 0; j < BLOCKSIZE; j++)
239
            vect[j] = cb[i][j];
240
        get_match_score(work, coefs, vect, ortho1, ortho2, data, &score, &g);
241
        if (score > best_score) {
242
            best_score = score;
243
            *idx = i;
244
            *gain = g;
245
        }
246
    }
247
}
248

    
249

    
250
/**
251
 * Search the two fixed codebooks for the best entry and gain
252
 *
253
 * @param work array used to calculate LPC-filtered vectors
254
 * @param coefs coefficients of the LPC filter
255
 * @param data input data
256
 * @param cba_idx index of the best entry of the adaptive codebook
257
 * @param cb1_idx pointer to variable where the index of the best entry of the
258
 *        first fixed codebook is returned
259
 * @param cb2_idx pointer to variable where the index of the best entry of the
260
 *        second fixed codebook is returned
261
 */
262
static void fixed_cb_search(float *work, const float *coefs, float *data,
263
                            int cba_idx, int *cb1_idx, int *cb2_idx)
264
{
265
    int i, ortho_cb1;
266
    float gain;
267
    float cba_vect[BLOCKSIZE], cb1_vect[BLOCKSIZE];
268
    float vect[BLOCKSIZE];
269

    
270
    /**
271
     * The filtered vector from the adaptive codebook can be retrieved from
272
     * work, because this function is called just after adaptive_cb_search().
273
     */
274
    if (cba_idx)
275
        memcpy(cba_vect, work, sizeof(cba_vect));
276

    
277
    find_best_vect(work, coefs, ff_cb1_vects, cba_idx ? cba_vect : NULL, NULL,
278
                   data, cb1_idx, &gain);
279

    
280
    /**
281
     * Re-calculate the filtered vector from the vector with maximum match score
282
     * and remove its contribution from input data.
283
     */
284
    if (gain) {
285
        for (i = 0; i < BLOCKSIZE; i++)
286
            vect[i] = ff_cb1_vects[*cb1_idx][i];
287
        ff_celp_lp_synthesis_filterf(work, coefs, vect, BLOCKSIZE, LPC_ORDER);
288
        if (cba_idx)
289
            orthogonalize(work, cba_vect);
290
        for (i = 0; i < BLOCKSIZE; i++)
291
            data[i] -= gain * work[i];
292
        memcpy(cb1_vect, work, sizeof(cb1_vect));
293
        ortho_cb1 = 1;
294
    } else
295
        ortho_cb1 = 0;
296

    
297
    find_best_vect(work, coefs, ff_cb2_vects, cba_idx ? cba_vect : NULL,
298
                   ortho_cb1 ? cb1_vect : NULL, data, cb2_idx, &gain);
299
}
300

    
301

    
302
/**
303
 * Encode a subblock of the current frame
304
 *
305
 * @param ractx encoder context
306
 * @param sblock_data input data of the subblock
307
 * @param lpc_coefs coefficients of the LPC filter
308
 * @param rms RMS of the reflection coefficients
309
 * @param pb pointer to PutBitContext of the current frame
310
 */
311
static void ra144_encode_subblock(RA144Context *ractx,
312
                                  const int16_t *sblock_data,
313
                                  const int16_t *lpc_coefs, unsigned int rms,
314
                                  PutBitContext *pb)
315
{
316
    float data[BLOCKSIZE], work[LPC_ORDER + BLOCKSIZE];
317
    float coefs[LPC_ORDER];
318
    float zero[BLOCKSIZE], cba[BLOCKSIZE], cb1[BLOCKSIZE], cb2[BLOCKSIZE];
319
    int16_t cba_vect[BLOCKSIZE];
320
    int cba_idx, cb1_idx, cb2_idx, gain;
321
    int i, n, m[3];
322
    float g[3];
323
    float error, best_error;
324

    
325
    for (i = 0; i < LPC_ORDER; i++) {
326
        work[i] = ractx->curr_sblock[BLOCKSIZE + i];
327
        coefs[i] = lpc_coefs[i] * (1/4096.0);
328
    }
329

    
330
    /**
331
     * Calculate the zero-input response of the LPC filter and subtract it from
332
     * input data.
333
     */
334
    memset(data, 0, sizeof(data));
335
    ff_celp_lp_synthesis_filterf(work + LPC_ORDER, coefs, data, BLOCKSIZE,
336
                                 LPC_ORDER);
337
    for (i = 0; i < BLOCKSIZE; i++) {
338
        zero[i] = work[LPC_ORDER + i];
339
        data[i] = sblock_data[i] - zero[i];
340
    }
341

    
342
    /**
343
     * Codebook search is performed without taking into account the contribution
344
     * of the previous subblock, since it has been just subtracted from input
345
     * data.
346
     */
347
    memset(work, 0, LPC_ORDER * sizeof(*work));
348

    
349
    cba_idx = adaptive_cb_search(ractx->adapt_cb, work + LPC_ORDER, coefs,
350
                                 data);
351
    if (cba_idx) {
352
        /**
353
         * The filtered vector from the adaptive codebook can be retrieved from
354
         * work, see implementation of adaptive_cb_search().
355
         */
356
        memcpy(cba, work + LPC_ORDER, sizeof(cba));
357

    
358
        ff_copy_and_dup(cba_vect, ractx->adapt_cb, cba_idx + BLOCKSIZE / 2 - 1);
359
        m[0] = (ff_irms(cba_vect) * rms) >> 12;
360
    }
361
    fixed_cb_search(work + LPC_ORDER, coefs, data, cba_idx, &cb1_idx, &cb2_idx);
362
    for (i = 0; i < BLOCKSIZE; i++) {
363
        cb1[i] = ff_cb1_vects[cb1_idx][i];
364
        cb2[i] = ff_cb2_vects[cb2_idx][i];
365
    }
366
    ff_celp_lp_synthesis_filterf(work + LPC_ORDER, coefs, cb1, BLOCKSIZE,
367
                                 LPC_ORDER);
368
    memcpy(cb1, work + LPC_ORDER, sizeof(cb1));
369
    m[1] = (ff_cb1_base[cb1_idx] * rms) >> 8;
370
    ff_celp_lp_synthesis_filterf(work + LPC_ORDER, coefs, cb2, BLOCKSIZE,
371
                                 LPC_ORDER);
372
    memcpy(cb2, work + LPC_ORDER, sizeof(cb2));
373
    m[2] = (ff_cb2_base[cb2_idx] * rms) >> 8;
374
    best_error = FLT_MAX;
375
    gain = 0;
376
    for (n = 0; n < 256; n++) {
377
        g[1] = ((ff_gain_val_tab[n][1] * m[1]) >> ff_gain_exp_tab[n]) *
378
               (1/4096.0);
379
        g[2] = ((ff_gain_val_tab[n][2] * m[2]) >> ff_gain_exp_tab[n]) *
380
               (1/4096.0);
381
        error = 0;
382
        if (cba_idx) {
383
            g[0] = ((ff_gain_val_tab[n][0] * m[0]) >> ff_gain_exp_tab[n]) *
384
                   (1/4096.0);
385
            for (i = 0; i < BLOCKSIZE; i++) {
386
                data[i] = zero[i] + g[0] * cba[i] + g[1] * cb1[i] +
387
                          g[2] * cb2[i];
388
                error += (data[i] - sblock_data[i]) *
389
                         (data[i] - sblock_data[i]);
390
            }
391
        } else {
392
            for (i = 0; i < BLOCKSIZE; i++) {
393
                data[i] = zero[i] + g[1] * cb1[i] + g[2] * cb2[i];
394
                error += (data[i] - sblock_data[i]) *
395
                         (data[i] - sblock_data[i]);
396
            }
397
        }
398
        if (error < best_error) {
399
            best_error = error;
400
            gain = n;
401
        }
402
    }
403
    put_bits(pb, 7, cba_idx);
404
    put_bits(pb, 8, gain);
405
    put_bits(pb, 7, cb1_idx);
406
    put_bits(pb, 7, cb2_idx);
407
    ff_subblock_synthesis(ractx, lpc_coefs, cba_idx, cb1_idx, cb2_idx, rms,
408
                          gain);
409
}
410

    
411

    
412
static int ra144_encode_frame(AVCodecContext *avctx, uint8_t *frame,
413
                              int buf_size, void *data)
414
{
415
    static const uint8_t sizes[LPC_ORDER] = {64, 32, 32, 16, 16, 8, 8, 8, 8, 4};
416
    static const uint8_t bit_sizes[LPC_ORDER] = {6, 5, 5, 4, 4, 3, 3, 3, 3, 2};
417
    RA144Context *ractx;
418
    PutBitContext pb;
419
    int32_t lpc_data[NBLOCKS * BLOCKSIZE];
420
    int32_t lpc_coefs[LPC_ORDER][MAX_LPC_ORDER];
421
    int shift[LPC_ORDER];
422
    int16_t block_coefs[NBLOCKS][LPC_ORDER];
423
    int lpc_refl[LPC_ORDER];    /**< reflection coefficients of the frame */
424
    unsigned int refl_rms[NBLOCKS]; /**< RMS of the reflection coefficients */
425
    int energy = 0;
426
    int i, idx;
427

    
428
    if (buf_size < FRAMESIZE) {
429
        av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");
430
        return 0;
431
    }
432
    ractx = avctx->priv_data;
433

    
434
    /**
435
     * Since the LPC coefficients are calculated on a frame centered over the
436
     * fourth subframe, to encode a given frame, data from the next frame is
437
     * needed. In each call to this function, the previous frame (whose data are
438
     * saved in the encoder context) is encoded, and data from the current frame
439
     * are saved in the encoder context to be used in the next function call.
440
     */
441
    for (i = 0; i < (2 * BLOCKSIZE + BLOCKSIZE / 2); i++) {
442
        lpc_data[i] = ractx->curr_block[BLOCKSIZE + BLOCKSIZE / 2 + i];
443
        energy += (lpc_data[i] * lpc_data[i]) >> 4;
444
    }
445
    for (i = 2 * BLOCKSIZE + BLOCKSIZE / 2; i < NBLOCKS * BLOCKSIZE; i++) {
446
        lpc_data[i] = *((int16_t *)data + i - 2 * BLOCKSIZE - BLOCKSIZE / 2) >>
447
                      2;
448
        energy += (lpc_data[i] * lpc_data[i]) >> 4;
449
    }
450
    energy = ff_energy_tab[quantize(ff_t_sqrt(energy >> 5) >> 10, ff_energy_tab,
451
                                    32)];
452

    
453
    ff_lpc_calc_coefs(&ractx->lpc_ctx, lpc_data, NBLOCKS * BLOCKSIZE, LPC_ORDER,
454
                      LPC_ORDER, 16, lpc_coefs, shift, AV_LPC_TYPE_LEVINSON,
455
                      0, ORDER_METHOD_EST, 12, 0);
456
    for (i = 0; i < LPC_ORDER; i++)
457
        block_coefs[NBLOCKS - 1][i] = -(lpc_coefs[LPC_ORDER - 1][i] <<
458
                                        (12 - shift[LPC_ORDER - 1]));
459

    
460
    /**
461
     * TODO: apply perceptual weighting of the input speech through bandwidth
462
     * expansion of the LPC filter.
463
     */
464

    
465
    if (ff_eval_refl(lpc_refl, block_coefs[NBLOCKS - 1], avctx)) {
466
        /**
467
         * The filter is unstable: use the coefficients of the previous frame.
468
         */
469
        ff_int_to_int16(block_coefs[NBLOCKS - 1], ractx->lpc_coef[1]);
470
        ff_eval_refl(lpc_refl, block_coefs[NBLOCKS - 1], avctx);
471
    }
472
    init_put_bits(&pb, frame, buf_size);
473
    for (i = 0; i < LPC_ORDER; i++) {
474
        idx = quantize(lpc_refl[i], ff_lpc_refl_cb[i], sizes[i]);
475
        put_bits(&pb, bit_sizes[i], idx);
476
        lpc_refl[i] = ff_lpc_refl_cb[i][idx];
477
    }
478
    ractx->lpc_refl_rms[0] = ff_rms(lpc_refl);
479
    ff_eval_coefs(ractx->lpc_coef[0], lpc_refl);
480
    refl_rms[0] = ff_interp(ractx, block_coefs[0], 1, 1, ractx->old_energy);
481
    refl_rms[1] = ff_interp(ractx, block_coefs[1], 2,
482
                            energy <= ractx->old_energy,
483
                            ff_t_sqrt(energy * ractx->old_energy) >> 12);
484
    refl_rms[2] = ff_interp(ractx, block_coefs[2], 3, 0, energy);
485
    refl_rms[3] = ff_rescale_rms(ractx->lpc_refl_rms[0], energy);
486
    ff_int_to_int16(block_coefs[NBLOCKS - 1], ractx->lpc_coef[0]);
487
    put_bits(&pb, 5, quantize(energy, ff_energy_tab, 32));
488
    for (i = 0; i < NBLOCKS; i++)
489
        ra144_encode_subblock(ractx, ractx->curr_block + i * BLOCKSIZE,
490
                              block_coefs[i], refl_rms[i], &pb);
491
    flush_put_bits(&pb);
492
    ractx->old_energy = energy;
493
    ractx->lpc_refl_rms[1] = ractx->lpc_refl_rms[0];
494
    FFSWAP(unsigned int *, ractx->lpc_coef[0], ractx->lpc_coef[1]);
495
    for (i = 0; i < NBLOCKS * BLOCKSIZE; i++)
496
        ractx->curr_block[i] = *((int16_t *)data + i) >> 2;
497
    return FRAMESIZE;
498
}
499

    
500

    
501
AVCodec ra_144_encoder =
502
{
503
    "real_144",
504
    AVMEDIA_TYPE_AUDIO,
505
    CODEC_ID_RA_144,
506
    sizeof(RA144Context),
507
    ra144_encode_init,
508
    ra144_encode_frame,
509
    .long_name = NULL_IF_CONFIG_SMALL("RealAudio 1.0 (14.4K) encoder"),
510
};