GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/g723_1enc.c Lines: 564 580 97.2 %
Date: 2021-04-18 21:26:34 Branches: 245 260 94.2 %

Line Branch Exec Source
1
/*
2
 * G.723.1 compatible encoder
3
 * Copyright (c) Mohamed Naufal <naufal22@gmail.com>
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
 * G.723.1 compatible encoder
25
 */
26
27
#include <stdint.h>
28
#include <string.h>
29
30
#include "libavutil/channel_layout.h"
31
#include "libavutil/common.h"
32
#include "libavutil/mem.h"
33
#include "libavutil/opt.h"
34
35
#include "avcodec.h"
36
#include "celp_math.h"
37
#include "g723_1.h"
38
#include "internal.h"
39
40
#define BITSTREAM_WRITER_LE
41
#include "put_bits.h"
42
43
/**
44
 * Hamming window coefficients scaled by 2^15
45
 */
46
static const int16_t hamming_window[LPC_FRAME] = {
47
     2621,  2631,  2659,  2705,  2770,  2853,  2955,  3074,  3212,  3367,
48
     3541,  3731,  3939,  4164,  4405,  4663,  4937,  5226,  5531,  5851,
49
     6186,  6534,  6897,  7273,  7661,  8062,  8475,  8899,  9334,  9780,
50
    10235, 10699, 11172, 11653, 12141, 12636, 13138, 13645, 14157, 14673,
51
    15193, 15716, 16242, 16769, 17298, 17827, 18356, 18884, 19411, 19935,
52
    20457, 20975, 21489, 21999, 22503, 23002, 23494, 23978, 24455, 24924,
53
    25384, 25834, 26274, 26704, 27122, 27529, 27924, 28306, 28675, 29031,
54
    29373, 29700, 30012, 30310, 30592, 30857, 31107, 31340, 31557, 31756,
55
    31938, 32102, 32249, 32377, 32488, 32580, 32654, 32710, 32747, 32766,
56
    32766, 32747, 32710, 32654, 32580, 32488, 32377, 32249, 32102, 31938,
57
    31756, 31557, 31340, 31107, 30857, 30592, 30310, 30012, 29700, 29373,
58
    29031, 28675, 28306, 27924, 27529, 27122, 26704, 26274, 25834, 25384,
59
    24924, 24455, 23978, 23494, 23002, 22503, 21999, 21489, 20975, 20457,
60
    19935, 19411, 18884, 18356, 17827, 17298, 16769, 16242, 15716, 15193,
61
    14673, 14157, 13645, 13138, 12636, 12141, 11653, 11172, 10699, 10235,
62
     9780, 9334,   8899,  8475,  8062,  7661,  7273,  6897,  6534,  6186,
63
     5851, 5531,   5226,  4937,  4663,  4405,  4164,  3939,  3731,  3541,
64
     3367, 3212,   3074,  2955,  2853,  2770,  2705,  2659,  2631,  2621
65
};
66
67
/**
68
 * Binomial window coefficients scaled by 2^15
69
 */
70
static const int16_t binomial_window[LPC_ORDER] = {
71
    32749, 32695, 32604, 32477, 32315, 32118, 31887, 31622, 31324, 30995
72
};
73
74
/**
75
 * 0.994^i scaled by 2^15
76
 */
77
static const int16_t bandwidth_expand[LPC_ORDER] = {
78
    32571, 32376, 32182, 31989, 31797, 31606, 31416, 31228, 31040, 30854
79
};
80
81
/**
82
 * 0.5^i scaled by 2^15
83
 */
84
static const int16_t percept_flt_tbl[2][LPC_ORDER] = {
85
    /* Zero part */
86
    {29491, 26542, 23888, 21499, 19349, 17414, 15673, 14106, 12695, 11425},
87
    /* Pole part */
88
    {16384,  8192,  4096,  2048,  1024,   512,   256,   128,    64,    32}
89
};
90
91
1
static av_cold int g723_1_encode_init(AVCodecContext *avctx)
92
{
93
1
    G723_1_Context *s = avctx->priv_data;
94
1
    G723_1_ChannelContext *p = &s->ch[0];
95
96
1
    if (avctx->sample_rate != 8000) {
97
        av_log(avctx, AV_LOG_ERROR, "Only 8000Hz sample rate supported\n");
98
        return AVERROR(EINVAL);
99
    }
100
101
1
    if (avctx->channels != 1) {
102
        av_log(avctx, AV_LOG_ERROR, "Only mono supported\n");
103
        return AVERROR(EINVAL);
104
    }
105
106
1
    if (avctx->bit_rate == 6300) {
107
1
        p->cur_rate = RATE_6300;
108
    } else if (avctx->bit_rate == 5300) {
109
        av_log(avctx, AV_LOG_ERROR, "Use bitrate 6300 instead of 5300.\n");
110
        avpriv_report_missing_feature(avctx, "Bitrate 5300");
111
        return AVERROR_PATCHWELCOME;
112
    } else {
113
        av_log(avctx, AV_LOG_ERROR, "Bitrate not supported, use 6300\n");
114
        return AVERROR(EINVAL);
115
    }
116
1
    avctx->frame_size = 240;
117
1
    memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(int16_t));
118
119
1
    return 0;
120
}
121
122
/**
123
 * Remove DC component from the input signal.
124
 *
125
 * @param buf input signal
126
 * @param fir zero memory
127
 * @param iir pole memory
128
 */
129
200
static void highpass_filter(int16_t *buf, int16_t *fir, int *iir)
130
{
131
    int i;
132
48200
    for (i = 0; i < FRAME_LEN; i++) {
133
48000
        *iir   = (buf[i] << 15) + ((-*fir) << 15) + MULL2(*iir, 0x7f00);
134
48000
        *fir   = buf[i];
135
48000
        buf[i] = av_clipl_int32((int64_t)*iir + (1 << 15)) >> 16;
136
    }
137
200
}
138
139
/**
140
 * Estimate autocorrelation of the input vector.
141
 *
142
 * @param buf      input buffer
143
 * @param autocorr autocorrelation coefficients vector
144
 */
145
800
static void comp_autocorr(int16_t *buf, int16_t *autocorr)
146
{
147
    int i, scale, temp;
148
    int16_t vector[LPC_FRAME];
149
150
800
    ff_g723_1_scale_vector(vector, buf, LPC_FRAME);
151
152
    /* Apply the Hamming window */
153
144800
    for (i = 0; i < LPC_FRAME; i++)
154
144000
        vector[i] = (vector[i] * hamming_window[i] + (1 << 14)) >> 15;
155
156
    /* Compute the first autocorrelation coefficient */
157
800
    temp = ff_dot_product(vector, vector, LPC_FRAME);
158
159
    /* Apply a white noise correlation factor of (1025/1024) */
160
800
    temp += temp >> 10;
161
162
    /* Normalize */
163
800
    scale       = ff_g723_1_normalize_bits(temp, 31);
164
800
    autocorr[0] = av_clipl_int32((int64_t) (temp << scale) +
165
800
                                 (1 << 15)) >> 16;
166
167
    /* Compute the remaining coefficients */
168
800
    if (!autocorr[0]) {
169
        memset(autocorr + 1, 0, LPC_ORDER * sizeof(int16_t));
170
    } else {
171
8800
        for (i = 1; i <= LPC_ORDER; i++) {
172
8000
            temp        = ff_dot_product(vector, vector + i, LPC_FRAME - i);
173
8000
            temp        = MULL2((temp << scale), binomial_window[i - 1]);
174
8000
            autocorr[i] = av_clipl_int32((int64_t) temp + (1 << 15)) >> 16;
175
        }
176
    }
177
800
}
178
179
/**
180
 * Use Levinson-Durbin recursion to compute LPC coefficients from
181
 * autocorrelation values.
182
 *
183
 * @param lpc      LPC coefficients vector
184
 * @param autocorr autocorrelation coefficients vector
185
 * @param error    prediction error
186
 */
187
800
static void levinson_durbin(int16_t *lpc, int16_t *autocorr, int16_t error)
188
{
189
    int16_t vector[LPC_ORDER];
190
    int16_t partial_corr;
191
    int i, j, temp;
192
193
800
    memset(lpc, 0, LPC_ORDER * sizeof(int16_t));
194
195
8800
    for (i = 0; i < LPC_ORDER; i++) {
196
        /* Compute the partial correlation coefficient */
197
8000
        temp = 0;
198
44000
        for (j = 0; j < i; j++)
199
36000
            temp -= lpc[j] * autocorr[i - j - 1];
200
8000
        temp = ((autocorr[i] << 13) + temp) << 3;
201
202
8000
        if (FFABS(temp) >= (error << 16))
203
            break;
204
205
8000
        partial_corr = temp / (error << 1);
206
207
8000
        lpc[i] = av_clipl_int32((int64_t) (partial_corr << 14) +
208
8000
                                (1 << 15)) >> 16;
209
210
        /* Update the prediction error */
211
8000
        temp  = MULL2(temp, partial_corr);
212
8000
        error = av_clipl_int32((int64_t) (error << 16) - temp +
213
8000
                               (1 << 15)) >> 16;
214
215
8000
        memcpy(vector, lpc, i * sizeof(int16_t));
216
44000
        for (j = 0; j < i; j++) {
217
36000
            temp   = partial_corr * vector[i - j - 1] << 1;
218
36000
            lpc[j] = av_clipl_int32((int64_t) (lpc[j] << 16) - temp +
219
36000
                                    (1 << 15)) >> 16;
220
        }
221
    }
222
800
}
223
224
/**
225
 * Calculate LPC coefficients for the current frame.
226
 *
227
 * @param buf       current frame
228
 * @param prev_data 2 trailing subframes of the previous frame
229
 * @param lpc       LPC coefficients vector
230
 */
231
200
static void comp_lpc_coeff(int16_t *buf, int16_t *lpc)
232
{
233
    int16_t autocorr[(LPC_ORDER + 1) * SUBFRAMES];
234
200
    int16_t *autocorr_ptr = autocorr;
235
200
    int16_t *lpc_ptr      = lpc;
236
    int i, j;
237
238
1000
    for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
239
800
        comp_autocorr(buf + i, autocorr_ptr);
240
800
        levinson_durbin(lpc_ptr, autocorr_ptr + 1, autocorr_ptr[0]);
241
242
800
        lpc_ptr      += LPC_ORDER;
243
800
        autocorr_ptr += LPC_ORDER + 1;
244
    }
245
200
}
246
247
200
static void lpc2lsp(int16_t *lpc, int16_t *prev_lsp, int16_t *lsp)
248
{
249
    int f[LPC_ORDER + 2]; ///< coefficients of the sum and difference
250
                          ///< polynomials (F1, F2) ordered as
251
                          ///< f1[0], f2[0], ...., f1[5], f2[5]
252
253
    int max, shift, cur_val, prev_val, count, p;
254
    int i, j;
255
    int64_t temp;
256
257
    /* Initialize f1[0] and f2[0] to 1 in Q25 */
258
2200
    for (i = 0; i < LPC_ORDER; i++)
259
2000
        lsp[i] = (lpc[i] * bandwidth_expand[i] + (1 << 14)) >> 15;
260
261
    /* Apply bandwidth expansion on the LPC coefficients */
262
200
    f[0] = f[1] = 1 << 25;
263
264
    /* Compute the remaining coefficients */
265
1200
    for (i = 0; i < LPC_ORDER / 2; i++) {
266
        /* f1 */
267
1000
        f[2 * i + 2] = -f[2 * i] - ((lsp[i] + lsp[LPC_ORDER - 1 - i]) << 12);
268
        /* f2 */
269
1000
        f[2 * i + 3] = f[2 * i + 1] - ((lsp[i] - lsp[LPC_ORDER - 1 - i]) << 12);
270
    }
271
272
    /* Divide f1[5] and f2[5] by 2 for use in polynomial evaluation */
273
200
    f[LPC_ORDER]     >>= 1;
274
200
    f[LPC_ORDER + 1] >>= 1;
275
276
    /* Normalize and shorten */
277
200
    max = FFABS(f[0]);
278
2400
    for (i = 1; i < LPC_ORDER + 2; i++)
279
2200
        max = FFMAX(max, FFABS(f[i]));
280
281
200
    shift = ff_g723_1_normalize_bits(max, 31);
282
283
2600
    for (i = 0; i < LPC_ORDER + 2; i++)
284
2400
        f[i] = av_clipl_int32((int64_t) (f[i] << shift) + (1 << 15)) >> 16;
285
286
    /**
287
     * Evaluate F1 and F2 at uniform intervals of pi/256 along the
288
     * unit circle and check for zero crossings.
289
     */
290
200
    p    = 0;
291
200
    temp = 0;
292
1400
    for (i = 0; i <= LPC_ORDER / 2; i++)
293
1200
        temp += f[2 * i] * G723_1_COS_TAB_FIRST_ELEMENT;
294
200
    prev_val = av_clipl_int32(temp << 1);
295
200
    count    = 0;
296
46245
    for (i = 1; i < COS_TBL_SIZE / 2; i++) {
297
        /* Evaluate */
298
46245
        temp = 0;
299
323715
        for (j = 0; j <= LPC_ORDER / 2; j++)
300
277470
            temp += f[LPC_ORDER - 2 * j + p] * ff_g723_1_cos_tab[i * j % COS_TBL_SIZE];
301
46245
        cur_val = av_clipl_int32(temp << 1);
302
303
        /* Check for sign change, indicating a zero crossing */
304
46245
        if ((cur_val ^ prev_val) < 0) {
305
2000
            int abs_cur  = FFABS(cur_val);
306
2000
            int abs_prev = FFABS(prev_val);
307
2000
            int sum      = abs_cur + abs_prev;
308
309
2000
            shift        = ff_g723_1_normalize_bits(sum, 31);
310
2000
            sum        <<= shift;
311
2000
            abs_prev     = abs_prev << shift >> 8;
312
2000
            lsp[count++] = ((i - 1) << 7) + (abs_prev >> 1) / (sum >> 16);
313
314
2000
            if (count == LPC_ORDER)
315
200
                break;
316
317
            /* Switch between sum and difference polynomials */
318
1800
            p ^= 1;
319
320
            /* Evaluate */
321
1800
            temp = 0;
322
12600
            for (j = 0; j <= LPC_ORDER / 2; j++)
323
10800
                temp += f[LPC_ORDER - 2 * j + p] *
324
10800
                        ff_g723_1_cos_tab[i * j % COS_TBL_SIZE];
325
1800
            cur_val = av_clipl_int32(temp << 1);
326
        }
327
46045
        prev_val = cur_val;
328
    }
329
330
200
    if (count != LPC_ORDER)
331
        memcpy(lsp, prev_lsp, LPC_ORDER * sizeof(int16_t));
332
200
}
333
334
/**
335
 * Quantize the current LSP subvector.
336
 *
337
 * @param num    band number
338
 * @param offset offset of the current subvector in an LPC_ORDER vector
339
 * @param size   size of the current subvector
340
 */
341
#define get_index(num, offset, size)                                          \
342
{                                                                             \
343
    int error, max = -1;                                                      \
344
    int16_t temp[4];                                                          \
345
    int i, j;                                                                 \
346
                                                                              \
347
    for (i = 0; i < LSP_CB_SIZE; i++) {                                       \
348
        for (j = 0; j < size; j++){                                           \
349
            temp[j] = (weight[j + (offset)] * ff_g723_1_lsp_band##num[i][j] + \
350
                      (1 << 14)) >> 15;                                       \
351
        }                                                                     \
352
        error  = ff_g723_1_dot_product(lsp + (offset), temp, size) << 1;      \
353
        error -= ff_g723_1_dot_product(ff_g723_1_lsp_band##num[i], temp, size); \
354
        if (error > max) {                                                    \
355
            max = error;                                                      \
356
            lsp_index[num] = i;                                               \
357
        }                                                                     \
358
    }                                                                         \
359
}
360
361
/**
362
 * Vector quantize the LSP frequencies.
363
 *
364
 * @param lsp      the current lsp vector
365
 * @param prev_lsp the previous lsp vector
366
 */
367
200
static void lsp_quantize(uint8_t *lsp_index, int16_t *lsp, int16_t *prev_lsp)
368
{
369
    int16_t weight[LPC_ORDER];
370
    int16_t min, max;
371
    int shift, i;
372
373
    /* Calculate the VQ weighting vector */
374
200
    weight[0]             = (1 << 20) / (lsp[1] - lsp[0]);
375
200
    weight[LPC_ORDER - 1] = (1 << 20) /
376
200
                            (lsp[LPC_ORDER - 1] - lsp[LPC_ORDER - 2]);
377
378
1800
    for (i = 1; i < LPC_ORDER - 1; i++) {
379
1600
        min = FFMIN(lsp[i] - lsp[i - 1], lsp[i + 1] - lsp[i]);
380
1600
        if (min > 0x20)
381
1600
            weight[i] = (1 << 20) / min;
382
        else
383
            weight[i] = INT16_MAX;
384
    }
385
386
    /* Normalize */
387
200
    max = 0;
388
2200
    for (i = 0; i < LPC_ORDER; i++)
389
2000
        max = FFMAX(weight[i], max);
390
391
200
    shift = ff_g723_1_normalize_bits(max, 15);
392
2200
    for (i = 0; i < LPC_ORDER; i++) {
393
2000
        weight[i] <<= shift;
394
    }
395
396
    /* Compute the VQ target vector */
397
2200
    for (i = 0; i < LPC_ORDER; i++) {
398
2000
        lsp[i] -= dc_lsp[i] +
399
2000
                  (((prev_lsp[i] - dc_lsp[i]) * 12288 + (1 << 14)) >> 15);
400
    }
401
402

205000
    get_index(0, 0, 3);
403

205000
    get_index(1, 3, 3);
404

256200
    get_index(2, 6, 4);
405
200
}
406
407
/**
408
 * Perform IIR filtering.
409
 *
410
 * @param fir_coef FIR coefficients
411
 * @param iir_coef IIR coefficients
412
 * @param src      source vector
413
 * @param dest     destination vector
414
 */
415
800
static void iir_filter(int16_t *fir_coef, int16_t *iir_coef,
416
                       int16_t *src, int16_t *dest)
417
{
418
    int m, n;
419
420
48800
    for (m = 0; m < SUBFRAME_LEN; m++) {
421
48000
        int64_t filter = 0;
422
528000
        for (n = 1; n <= LPC_ORDER; n++) {
423
480000
            filter -= fir_coef[n - 1] * src[m - n] -
424
480000
                      iir_coef[n - 1] * dest[m - n];
425
        }
426
427
48000
        dest[m] = av_clipl_int32((src[m] << 16) + (filter << 3) +
428
48000
                                 (1 << 15)) >> 16;
429
    }
430
800
}
431
432
/**
433
 * Apply the formant perceptual weighting filter.
434
 *
435
 * @param flt_coef filter coefficients
436
 * @param unq_lpc  unquantized lpc vector
437
 */
438
200
static void perceptual_filter(G723_1_ChannelContext *p, int16_t *flt_coef,
439
                              int16_t *unq_lpc, int16_t *buf)
440
{
441
    int16_t vector[FRAME_LEN + LPC_ORDER];
442
200
    int i, j, k, l = 0;
443
444
200
    memcpy(buf, p->iir_mem, sizeof(int16_t) * LPC_ORDER);
445
200
    memcpy(vector, p->fir_mem, sizeof(int16_t) * LPC_ORDER);
446
200
    memcpy(vector + LPC_ORDER, buf + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
447
448
1000
    for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
449
8800
        for (k = 0; k < LPC_ORDER; k++) {
450
8000
            flt_coef[k + 2 * l] = (unq_lpc[k + l] * percept_flt_tbl[0][k] +
451
8000
                                   (1 << 14)) >> 15;
452
8000
            flt_coef[k + 2 * l + LPC_ORDER] = (unq_lpc[k + l] *
453
8000
                                               percept_flt_tbl[1][k] +
454
8000
                                               (1 << 14)) >> 15;
455
        }
456
800
        iir_filter(flt_coef + 2 * l, flt_coef + 2 * l + LPC_ORDER,
457
800
                   vector + i, buf + i);
458
800
        l += LPC_ORDER;
459
    }
460
200
    memcpy(p->iir_mem, buf + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
461
200
    memcpy(p->fir_mem, vector + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
462
200
}
463
464
/**
465
 * Estimate the open loop pitch period.
466
 *
467
 * @param buf   perceptually weighted speech
468
 * @param start estimation is carried out from this position
469
 */
470
400
static int estimate_pitch(int16_t *buf, int start)
471
{
472
400
    int max_exp = 32;
473
400
    int max_ccr = 0x4000;
474
400
    int max_eng = 0x7fff;
475
400
    int index   = PITCH_MIN;
476
400
    int offset  = start - PITCH_MIN + 1;
477
478
    int ccr, eng, orig_eng, ccr_eng, exp;
479
    int diff, temp;
480
481
    int i;
482
483
400
    orig_eng = ff_dot_product(buf + offset, buf + offset, HALF_FRAME_LEN);
484
485
50400
    for (i = PITCH_MIN; i <= PITCH_MAX - 3; i++) {
486
50000
        offset--;
487
488
        /* Update energy and compute correlation */
489
50000
        orig_eng += buf[offset] * buf[offset] -
490
50000
                    buf[offset + HALF_FRAME_LEN] * buf[offset + HALF_FRAME_LEN];
491
50000
        ccr = ff_dot_product(buf + start, buf + offset, HALF_FRAME_LEN);
492
50000
        if (ccr <= 0)
493
25406
            continue;
494
495
        /* Split into mantissa and exponent to maintain precision */
496
24594
        exp   = ff_g723_1_normalize_bits(ccr, 31);
497
24594
        ccr   = av_clipl_int32((int64_t) (ccr << exp) + (1 << 15)) >> 16;
498
24594
        exp <<= 1;
499
24594
        ccr  *= ccr;
500
24594
        temp  = ff_g723_1_normalize_bits(ccr, 31);
501
24594
        ccr   = ccr << temp >> 16;
502
24594
        exp  += temp;
503
504
24594
        temp = ff_g723_1_normalize_bits(orig_eng, 31);
505
24594
        eng  = av_clipl_int32((int64_t) (orig_eng << temp) + (1 << 15)) >> 16;
506
24594
        exp -= temp;
507
508
24594
        if (ccr >= eng) {
509
9755
            exp--;
510
9755
            ccr >>= 1;
511
        }
512
24594
        if (exp > max_exp)
513
19555
            continue;
514
515
5039
        if (exp + 1 < max_exp)
516
502
            goto update;
517
518
        /* Equalize exponents before comparison */
519
4537
        if (exp + 1 == max_exp)
520
364
            temp = max_ccr >> 1;
521
        else
522
4173
            temp = max_ccr;
523
4537
        ccr_eng = ccr * max_eng;
524
4537
        diff    = ccr_eng - eng * temp;
525

4537
        if (diff > 0 && (i - index < PITCH_MIN || diff > ccr_eng >> 2)) {
526
693
update:
527
1195
            index   = i;
528
1195
            max_exp = exp;
529
1195
            max_ccr = ccr;
530
1195
            max_eng = eng;
531
        }
532
    }
533
400
    return index;
534
}
535
536
/**
537
 * Compute harmonic noise filter parameters.
538
 *
539
 * @param buf       perceptually weighted speech
540
 * @param pitch_lag open loop pitch period
541
 * @param hf        harmonic filter parameters
542
 */
543
800
static void comp_harmonic_coeff(int16_t *buf, int16_t pitch_lag, HFParam *hf)
544
{
545
    int ccr, eng, max_ccr, max_eng;
546
    int exp, max, diff;
547
    int energy[15];
548
    int i, j;
549
550
6400
    for (i = 0, j = pitch_lag - 3; j <= pitch_lag + 3; i++, j++) {
551
        /* Compute residual energy */
552
5600
        energy[i << 1] = ff_dot_product(buf - j, buf - j, SUBFRAME_LEN);
553
        /* Compute correlation */
554
5600
        energy[(i << 1) + 1] = ff_dot_product(buf, buf - j, SUBFRAME_LEN);
555
    }
556
557
    /* Compute target energy */
558
800
    energy[14] = ff_dot_product(buf, buf, SUBFRAME_LEN);
559
560
    /* Normalize */
561
800
    max = 0;
562
12800
    for (i = 0; i < 15; i++)
563
12000
        max = FFMAX(max, FFABS(energy[i]));
564
565
800
    exp = ff_g723_1_normalize_bits(max, 31);
566
12800
    for (i = 0; i < 15; i++) {
567
12000
        energy[i] = av_clipl_int32((int64_t)(energy[i] << exp) +
568
12000
                                   (1 << 15)) >> 16;
569
    }
570
571
800
    hf->index = -1;
572
800
    hf->gain  =  0;
573
800
    max_ccr   =  1;
574
800
    max_eng   =  0x7fff;
575
576
6400
    for (i = 0; i <= 6; i++) {
577
5600
        eng = energy[i << 1];
578
5600
        ccr = energy[(i << 1) + 1];
579
580
5600
        if (ccr <= 0)
581
1732
            continue;
582
583
3868
        ccr  = (ccr * ccr + (1 << 14)) >> 15;
584
3868
        diff = ccr * max_eng - eng * max_ccr;
585
3868
        if (diff > 0) {
586
2218
            max_ccr   = ccr;
587
2218
            max_eng   = eng;
588
2218
            hf->index = i;
589
        }
590
    }
591
592
800
    if (hf->index == -1) {
593
3
        hf->index = pitch_lag;
594
3
        return;
595
    }
596
597
797
    eng = energy[14] * max_eng;
598
797
    eng = (eng >> 2) + (eng >> 3);
599
797
    ccr = energy[(hf->index << 1) + 1] * energy[(hf->index << 1) + 1];
600
797
    if (eng < ccr) {
601
656
        eng = energy[(hf->index << 1) + 1];
602
603
656
        if (eng >= max_eng)
604
202
            hf->gain = 0x2800;
605
        else
606
454
            hf->gain = ((eng << 15) / max_eng * 0x2800 + (1 << 14)) >> 15;
607
    }
608
797
    hf->index += pitch_lag - 3;
609
}
610
611
/**
612
 * Apply the harmonic noise shaping filter.
613
 *
614
 * @param hf filter parameters
615
 */
616
1600
static void harmonic_filter(HFParam *hf, const int16_t *src, int16_t *dest)
617
{
618
    int i;
619
620
97600
    for (i = 0; i < SUBFRAME_LEN; i++) {
621
96000
        int64_t temp = hf->gain * src[i - hf->index] << 1;
622
96000
        dest[i] = av_clipl_int32((src[i] << 16) - temp + (1 << 15)) >> 16;
623
    }
624
1600
}
625
626
800
static void harmonic_noise_sub(HFParam *hf, const int16_t *src, int16_t *dest)
627
{
628
    int i;
629
48800
    for (i = 0; i < SUBFRAME_LEN; i++) {
630
48000
        int64_t temp = hf->gain * src[i - hf->index] << 1;
631
48000
        dest[i] = av_clipl_int32(((dest[i] - src[i]) << 16) + temp +
632
48000
                                 (1 << 15)) >> 16;
633
    }
634
800
}
635
636
/**
637
 * Combined synthesis and formant perceptual weighting filer.
638
 *
639
 * @param qnt_lpc  quantized lpc coefficients
640
 * @param perf_lpc perceptual filter coefficients
641
 * @param perf_fir perceptual filter fir memory
642
 * @param perf_iir perceptual filter iir memory
643
 * @param scale    the filter output will be scaled by 2^scale
644
 */
645
2400
static void synth_percept_filter(int16_t *qnt_lpc, int16_t *perf_lpc,
646
                                 int16_t *perf_fir, int16_t *perf_iir,
647
                                 const int16_t *src, int16_t *dest, int scale)
648
{
649
    int i, j;
650
    int16_t buf_16[SUBFRAME_LEN + LPC_ORDER];
651
    int64_t buf[SUBFRAME_LEN];
652
653
2400
    int16_t *bptr_16 = buf_16 + LPC_ORDER;
654
655
2400
    memcpy(buf_16, perf_fir, sizeof(int16_t) * LPC_ORDER);
656
2400
    memcpy(dest - LPC_ORDER, perf_iir, sizeof(int16_t) * LPC_ORDER);
657
658
146400
    for (i = 0; i < SUBFRAME_LEN; i++) {
659
144000
        int64_t temp = 0;
660
1584000
        for (j = 1; j <= LPC_ORDER; j++)
661
1440000
            temp -= qnt_lpc[j - 1] * bptr_16[i - j];
662
663
144000
        buf[i]     = (src[i] << 15) + (temp << 3);
664
144000
        bptr_16[i] = av_clipl_int32(buf[i] + (1 << 15)) >> 16;
665
    }
666
667
146400
    for (i = 0; i < SUBFRAME_LEN; i++) {
668
144000
        int64_t fir = 0, iir = 0;
669
1584000
        for (j = 1; j <= LPC_ORDER; j++) {
670
1440000
            fir -= perf_lpc[j - 1] * bptr_16[i - j];
671
1440000
            iir += perf_lpc[j + LPC_ORDER - 1] * dest[i - j];
672
        }
673
144000
        dest[i] = av_clipl_int32(((buf[i] + (fir << 3)) << scale) + (iir << 3) +
674
144000
                                 (1 << 15)) >> 16;
675
    }
676
2400
    memcpy(perf_fir, buf_16 + SUBFRAME_LEN, sizeof(int16_t) * LPC_ORDER);
677
2400
    memcpy(perf_iir, dest + SUBFRAME_LEN - LPC_ORDER,
678
           sizeof(int16_t) * LPC_ORDER);
679
2400
}
680
681
/**
682
 * Compute the adaptive codebook contribution.
683
 *
684
 * @param buf   input signal
685
 * @param index the current subframe index
686
 */
687
800
static void acb_search(G723_1_ChannelContext *p, int16_t *residual,
688
                       int16_t *impulse_resp, const int16_t *buf,
689
                       int index)
690
{
691
    int16_t flt_buf[PITCH_ORDER][SUBFRAME_LEN];
692
693
800
    const int16_t *cb_tbl = ff_g723_1_adaptive_cb_gain85;
694
695
    int ccr_buf[PITCH_ORDER * SUBFRAMES << 2];
696
697
800
    int pitch_lag = p->pitch_lag[index >> 1];
698
800
    int acb_lag   = 1;
699
800
    int acb_gain  = 0;
700
800
    int odd_frame = index & 1;
701
800
    int iter      = 3 + odd_frame;
702
800
    int count     = 0;
703
800
    int tbl_size  = 85;
704
705
    int i, j, k, l, max;
706
    int64_t temp;
707
708
800
    if (!odd_frame) {
709
400
        if (pitch_lag == PITCH_MIN)
710
36
            pitch_lag++;
711
        else
712
364
            pitch_lag = FFMIN(pitch_lag, PITCH_MAX - 5);
713
    }
714
715
3600
    for (i = 0; i < iter; i++) {
716
2800
        ff_g723_1_get_residual(residual, p->prev_excitation, pitch_lag + i - 1);
717
718
170800
        for (j = 0; j < SUBFRAME_LEN; j++) {
719
168000
            temp = 0;
720
5292000
            for (k = 0; k <= j; k++)
721
5124000
                temp += residual[PITCH_ORDER - 1 + k] * impulse_resp[j - k];
722
168000
            flt_buf[PITCH_ORDER - 1][j] = av_clipl_int32((temp << 1) +
723
168000
                                                         (1 << 15)) >> 16;
724
        }
725
726
14000
        for (j = PITCH_ORDER - 2; j >= 0; j--) {
727
11200
            flt_buf[j][0] = ((residual[j] << 13) + (1 << 14)) >> 15;
728
672000
            for (k = 1; k < SUBFRAME_LEN; k++) {
729
660800
                temp = (flt_buf[j + 1][k - 1] << 15) +
730
660800
                       residual[j] * impulse_resp[k];
731
660800
                flt_buf[j][k] = av_clipl_int32((temp << 1) + (1 << 15)) >> 16;
732
            }
733
        }
734
735
        /* Compute crosscorrelation with the signal */
736
16800
        for (j = 0; j < PITCH_ORDER; j++) {
737
14000
            temp             = ff_dot_product(buf, flt_buf[j], SUBFRAME_LEN);
738
14000
            ccr_buf[count++] = av_clipl_int32(temp << 1);
739
        }
740
741
        /* Compute energies */
742
16800
        for (j = 0; j < PITCH_ORDER; j++) {
743
14000
            ccr_buf[count++] = ff_g723_1_dot_product(flt_buf[j], flt_buf[j],
744
                                                     SUBFRAME_LEN);
745
        }
746
747
14000
        for (j = 1; j < PITCH_ORDER; j++) {
748
39200
            for (k = 0; k < j; k++) {
749
28000
                temp             = ff_dot_product(flt_buf[j], flt_buf[k], SUBFRAME_LEN);
750
28000
                ccr_buf[count++] = av_clipl_int32(temp << 2);
751
            }
752
        }
753
    }
754
755
    /* Normalize and shorten */
756
800
    max = 0;
757
56800
    for (i = 0; i < 20 * iter; i++)
758
56000
        max = FFMAX(max, FFABS(ccr_buf[i]));
759
760
800
    temp = ff_g723_1_normalize_bits(max, 31);
761
762
56800
    for (i = 0; i < 20 * iter; i++)
763
56000
        ccr_buf[i] = av_clipl_int32((int64_t) (ccr_buf[i] << temp) +
764
56000
                                    (1 << 15)) >> 16;
765
766
800
    max = 0;
767
3600
    for (i = 0; i < iter; i++) {
768
        /* Select quantization table */
769

2800
        if (!odd_frame && pitch_lag + i - 1 >= SUBFRAME_LEN - 2 ||
770
1600
            odd_frame && pitch_lag >= SUBFRAME_LEN - 2) {
771
232
            cb_tbl   = ff_g723_1_adaptive_cb_gain170;
772
232
            tbl_size = 170;
773
        }
774
775
260520
        for (j = 0, k = 0; j < tbl_size; j++, k += 20) {
776
257720
            temp = 0;
777
5412120
            for (l = 0; l < 20; l++)
778
5154400
                temp += ccr_buf[20 * i + l] * cb_tbl[k + l];
779
257720
            temp = av_clipl_int32(temp);
780
781
257720
            if (temp > max) {
782
8615
                max      = temp;
783
8615
                acb_gain = j;
784
8615
                acb_lag  = i;
785
            }
786
        }
787
    }
788
789
800
    if (!odd_frame) {
790
400
        pitch_lag += acb_lag - 1;
791
400
        acb_lag    = 1;
792
    }
793
794
800
    p->pitch_lag[index >> 1]      = pitch_lag;
795
800
    p->subframe[index].ad_cb_lag  = acb_lag;
796
800
    p->subframe[index].ad_cb_gain = acb_gain;
797
800
}
798
799
/**
800
 * Subtract the adaptive codebook contribution from the input
801
 * to obtain the residual.
802
 *
803
 * @param buf target vector
804
 */
805
800
static void sub_acb_contrib(const int16_t *residual, const int16_t *impulse_resp,
806
                            int16_t *buf)
807
{
808
    int i, j;
809
    /* Subtract adaptive CB contribution to obtain the residual */
810
48800
    for (i = 0; i < SUBFRAME_LEN; i++) {
811
48000
        int64_t temp = buf[i] << 14;
812
1512000
        for (j = 0; j <= i; j++)
813
1464000
            temp -= residual[j] * impulse_resp[i - j];
814
815
48000
        buf[i] = av_clipl_int32((temp << 2) + (1 << 15)) >> 16;
816
    }
817
800
}
818
819
/**
820
 * Quantize the residual signal using the fixed codebook (MP-MLQ).
821
 *
822
 * @param optim optimized fixed codebook parameters
823
 * @param buf   excitation vector
824
 */
825
1534
static void get_fcb_param(FCBParam *optim, int16_t *impulse_resp,
826
                          int16_t *buf, int pulse_cnt, int pitch_lag)
827
{
828
    FCBParam param;
829
    int16_t impulse_r[SUBFRAME_LEN];
830
    int16_t temp_corr[SUBFRAME_LEN];
831
    int16_t impulse_corr[SUBFRAME_LEN];
832
833
    int ccr1[SUBFRAME_LEN];
834
    int ccr2[SUBFRAME_LEN];
835
    int amp, err, max, max_amp_index, min, scale, i, j, k, l;
836
837
    int64_t temp;
838
839
    /* Update impulse response */
840
1534
    memcpy(impulse_r, impulse_resp, sizeof(int16_t) * SUBFRAME_LEN);
841
1534
    param.dirac_train = 0;
842
1534
    if (pitch_lag < SUBFRAME_LEN - 2) {
843
734
        param.dirac_train = 1;
844
734
        ff_g723_1_gen_dirac_train(impulse_r, pitch_lag);
845
    }
846
847
93574
    for (i = 0; i < SUBFRAME_LEN; i++)
848
92040
        temp_corr[i] = impulse_r[i] >> 1;
849
850
    /* Compute impulse response autocorrelation */
851
1534
    temp = ff_g723_1_dot_product(temp_corr, temp_corr, SUBFRAME_LEN);
852
853
1534
    scale           = ff_g723_1_normalize_bits(temp, 31);
854
1534
    impulse_corr[0] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
855
856
92040
    for (i = 1; i < SUBFRAME_LEN; i++) {
857
90506
        temp = ff_g723_1_dot_product(temp_corr + i, temp_corr,
858
                                     SUBFRAME_LEN - i);
859
90506
        impulse_corr[i] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
860
    }
861
862
    /* Compute crosscorrelation of impulse response with residual signal */
863
1534
    scale -= 4;
864
93574
    for (i = 0; i < SUBFRAME_LEN; i++) {
865
92040
        temp = ff_g723_1_dot_product(buf + i, impulse_r, SUBFRAME_LEN - i);
866
92040
        if (scale < 0)
867
55500
            ccr1[i] = temp >> -scale;
868
        else
869
36540
            ccr1[i] = av_clipl_int32(temp << scale);
870
    }
871
872
    /* Search loop */
873
4602
    for (i = 0; i < GRID_SIZE; i++) {
874
        /* Maximize the crosscorrelation */
875
3068
        max = 0;
876
95108
        for (j = i; j < SUBFRAME_LEN; j += GRID_SIZE) {
877
92040
            temp = FFABS(ccr1[j]);
878
92040
            if (temp >= max) {
879
12301
                max                = temp;
880
12301
                param.pulse_pos[0] = j;
881
            }
882
        }
883
884
        /* Quantize the gain (max crosscorrelation/impulse_corr[0]) */
885
3068
        amp           = max;
886
3068
        min           = 1 << 30;
887
3068
        max_amp_index = GAIN_LEVELS - 2;
888
67496
        for (j = max_amp_index; j >= 2; j--) {
889
64428
            temp = av_clipl_int32((int64_t) ff_g723_1_fixed_cb_gain[j] *
890
64428
                                  impulse_corr[0] << 1);
891
64428
            temp = FFABS(temp - amp);
892
64428
            if (temp < min) {
893
33898
                min           = temp;
894
33898
                max_amp_index = j;
895
            }
896
        }
897
898
3068
        max_amp_index--;
899
        /* Select additional gain values */
900
15340
        for (j = 1; j < 5; j++) {
901
380432
            for (k = i; k < SUBFRAME_LEN; k += GRID_SIZE) {
902
368160
                temp_corr[k] = 0;
903
368160
                ccr2[k]      = ccr1[k];
904
            }
905
12272
            param.amp_index = max_amp_index + j - 2;
906
12272
            amp             = ff_g723_1_fixed_cb_gain[param.amp_index];
907
908
12272
            param.pulse_sign[0] = (ccr2[param.pulse_pos[0]] < 0) ? -amp : amp;
909
12272
            temp_corr[param.pulse_pos[0]] = 1;
910
911
67496
            for (k = 1; k < pulse_cnt; k++) {
912
55224
                max = INT_MIN;
913
1711944
                for (l = i; l < SUBFRAME_LEN; l += GRID_SIZE) {
914
1656720
                    if (temp_corr[l])
915
153400
                        continue;
916
1503320
                    temp = impulse_corr[FFABS(l - param.pulse_pos[k - 1])];
917
1503320
                    temp = av_clipl_int32((int64_t) temp *
918
1503320
                                          param.pulse_sign[k - 1] << 1);
919
1503320
                    ccr2[l] -= temp;
920
1503320
                    temp     = FFABS(ccr2[l]);
921
1503320
                    if (temp > max) {
922
224253
                        max                = temp;
923
224253
                        param.pulse_pos[k] = l;
924
                    }
925
                }
926
927
110448
                param.pulse_sign[k] = (ccr2[param.pulse_pos[k]] < 0) ?
928
55224
                                      -amp : amp;
929
55224
                temp_corr[param.pulse_pos[k]] = 1;
930
            }
931
932
            /* Create the error vector */
933
12272
            memset(temp_corr, 0, sizeof(int16_t) * SUBFRAME_LEN);
934
935
79768
            for (k = 0; k < pulse_cnt; k++)
936
67496
                temp_corr[param.pulse_pos[k]] = param.pulse_sign[k];
937
938
748592
            for (k = SUBFRAME_LEN - 1; k >= 0; k--) {
939
736320
                temp = 0;
940
23194080
                for (l = 0; l <= k; l++) {
941
22457760
                    int prod = av_clipl_int32((int64_t) temp_corr[l] *
942
22457760
                                              impulse_r[k - l] << 1);
943
22457760
                    temp = av_clipl_int32(temp + prod);
944
                }
945
736320
                temp_corr[k] = temp << 2 >> 16;
946
            }
947
948
            /* Compute square of error */
949
12272
            err = 0;
950
748592
            for (k = 0; k < SUBFRAME_LEN; k++) {
951
                int64_t prod;
952
736320
                prod = av_clipl_int32((int64_t) buf[k] * temp_corr[k] << 1);
953
736320
                err  = av_clipl_int32(err - prod);
954
736320
                prod = av_clipl_int32((int64_t) temp_corr[k] * temp_corr[k]);
955
736320
                err  = av_clipl_int32(err + prod);
956
            }
957
958
            /* Minimize */
959
12272
            if (err < optim->min_err) {
960
2638
                optim->min_err     = err;
961
2638
                optim->grid_index  = i;
962
2638
                optim->amp_index   = param.amp_index;
963
2638
                optim->dirac_train = param.dirac_train;
964
965
17164
                for (k = 0; k < pulse_cnt; k++) {
966
14526
                    optim->pulse_sign[k] = param.pulse_sign[k];
967
14526
                    optim->pulse_pos[k]  = param.pulse_pos[k];
968
                }
969
            }
970
        }
971
    }
972
1534
}
973
974
/**
975
 * Encode the pulse position and gain of the current subframe.
976
 *
977
 * @param optim optimized fixed CB parameters
978
 * @param buf   excitation vector
979
 */
980
800
static void pack_fcb_param(G723_1_Subframe *subfrm, FCBParam *optim,
981
                           int16_t *buf, int pulse_cnt)
982
{
983
    int i, j;
984
985
800
    j = PULSE_MAX - pulse_cnt;
986
987
800
    subfrm->pulse_sign = 0;
988
800
    subfrm->pulse_pos  = 0;
989
990
17850
    for (i = 0; i < SUBFRAME_LEN >> 1; i++) {
991
17850
        int val = buf[optim->grid_index + (i << 1)];
992
17850
        if (!val) {
993
13450
            subfrm->pulse_pos += ff_g723_1_combinatorial_table[j][i];
994
        } else {
995
4400
            subfrm->pulse_sign <<= 1;
996
4400
            if (val < 0)
997
2239
                subfrm->pulse_sign++;
998
4400
            j++;
999
1000
4400
            if (j == PULSE_MAX)
1001
800
                break;
1002
        }
1003
    }
1004
800
    subfrm->amp_index   = optim->amp_index;
1005
800
    subfrm->grid_index  = optim->grid_index;
1006
800
    subfrm->dirac_train = optim->dirac_train;
1007
800
}
1008
1009
/**
1010
 * Compute the fixed codebook excitation.
1011
 *
1012
 * @param buf          target vector
1013
 * @param impulse_resp impulse response of the combined filter
1014
 */
1015
800
static void fcb_search(G723_1_ChannelContext *p, int16_t *impulse_resp,
1016
                       int16_t *buf, int index)
1017
{
1018
    FCBParam optim;
1019
800
    int pulse_cnt = pulses[index];
1020
    int i;
1021
1022
800
    optim.min_err = 1 << 30;
1023
800
    get_fcb_param(&optim, impulse_resp, buf, pulse_cnt, SUBFRAME_LEN);
1024
1025
800
    if (p->pitch_lag[index >> 1] < SUBFRAME_LEN - 2) {
1026
734
        get_fcb_param(&optim, impulse_resp, buf, pulse_cnt,
1027
734
                      p->pitch_lag[index >> 1]);
1028
    }
1029
1030
    /* Reconstruct the excitation */
1031
800
    memset(buf, 0, sizeof(int16_t) * SUBFRAME_LEN);
1032
5200
    for (i = 0; i < pulse_cnt; i++)
1033
4400
        buf[optim.pulse_pos[i]] = optim.pulse_sign[i];
1034
1035
800
    pack_fcb_param(&p->subframe[index], &optim, buf, pulse_cnt);
1036
1037
800
    if (optim.dirac_train)
1038
378
        ff_g723_1_gen_dirac_train(buf, p->pitch_lag[index >> 1]);
1039
800
}
1040
1041
/**
1042
 * Pack the frame parameters into output bitstream.
1043
 *
1044
 * @param frame output buffer
1045
 * @param size  size of the buffer
1046
 */
1047
200
static int pack_bitstream(G723_1_ChannelContext *p, AVPacket *avpkt)
1048
{
1049
    PutBitContext pb;
1050
200
    int info_bits = 0;
1051
    int i, temp;
1052
1053
200
    init_put_bits(&pb, avpkt->data, avpkt->size);
1054
1055
200
    put_bits(&pb, 2, info_bits);
1056
1057
200
    put_bits(&pb, 8, p->lsp_index[2]);
1058
200
    put_bits(&pb, 8, p->lsp_index[1]);
1059
200
    put_bits(&pb, 8, p->lsp_index[0]);
1060
1061
200
    put_bits(&pb, 7, p->pitch_lag[0] - PITCH_MIN);
1062
200
    put_bits(&pb, 2, p->subframe[1].ad_cb_lag);
1063
200
    put_bits(&pb, 7, p->pitch_lag[1] - PITCH_MIN);
1064
200
    put_bits(&pb, 2, p->subframe[3].ad_cb_lag);
1065
1066
    /* Write 12 bit combined gain */
1067
1000
    for (i = 0; i < SUBFRAMES; i++) {
1068
800
        temp = p->subframe[i].ad_cb_gain * GAIN_LEVELS +
1069
800
               p->subframe[i].amp_index;
1070
800
        if (p->cur_rate == RATE_6300)
1071
800
            temp += p->subframe[i].dirac_train << 11;
1072
800
        put_bits(&pb, 12, temp);
1073
    }
1074
1075
200
    put_bits(&pb, 1, p->subframe[0].grid_index);
1076
200
    put_bits(&pb, 1, p->subframe[1].grid_index);
1077
200
    put_bits(&pb, 1, p->subframe[2].grid_index);
1078
200
    put_bits(&pb, 1, p->subframe[3].grid_index);
1079
1080
200
    if (p->cur_rate == RATE_6300) {
1081
200
        put_bits(&pb, 1, 0); /* reserved bit */
1082
1083
        /* Write 13 bit combined position index */
1084
200
        temp = (p->subframe[0].pulse_pos >> 16) * 810 +
1085
200
               (p->subframe[1].pulse_pos >> 14) *  90 +
1086
200
               (p->subframe[2].pulse_pos >> 16) *   9 +
1087
200
               (p->subframe[3].pulse_pos >> 14);
1088
200
        put_bits(&pb, 13, temp);
1089
1090
200
        put_bits(&pb, 16, p->subframe[0].pulse_pos & 0xffff);
1091
200
        put_bits(&pb, 14, p->subframe[1].pulse_pos & 0x3fff);
1092
200
        put_bits(&pb, 16, p->subframe[2].pulse_pos & 0xffff);
1093
200
        put_bits(&pb, 14, p->subframe[3].pulse_pos & 0x3fff);
1094
1095
200
        put_bits(&pb, 6, p->subframe[0].pulse_sign);
1096
200
        put_bits(&pb, 5, p->subframe[1].pulse_sign);
1097
200
        put_bits(&pb, 6, p->subframe[2].pulse_sign);
1098
200
        put_bits(&pb, 5, p->subframe[3].pulse_sign);
1099
    }
1100
1101
200
    flush_put_bits(&pb);
1102
200
    return frame_size[info_bits];
1103
}
1104
1105
200
static int g723_1_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1106
                               const AVFrame *frame, int *got_packet_ptr)
1107
{
1108
200
    G723_1_Context *s = avctx->priv_data;
1109
200
    G723_1_ChannelContext *p = &s->ch[0];
1110
    int16_t unq_lpc[LPC_ORDER * SUBFRAMES];
1111
    int16_t qnt_lpc[LPC_ORDER * SUBFRAMES];
1112
    int16_t cur_lsp[LPC_ORDER];
1113
    int16_t weighted_lpc[LPC_ORDER * SUBFRAMES << 1];
1114
    int16_t vector[FRAME_LEN + PITCH_MAX];
1115
    int offset, ret, i, j;
1116
    int16_t *in, *start;
1117
    HFParam hf[4];
1118
1119
    /* duplicate input */
1120
200
    start = in = av_malloc(frame->nb_samples * sizeof(int16_t));
1121
200
    if (!in)
1122
        return AVERROR(ENOMEM);
1123
200
    memcpy(in, frame->data[0], frame->nb_samples * sizeof(int16_t));
1124
1125
200
    highpass_filter(in, &p->hpf_fir_mem, &p->hpf_iir_mem);
1126
1127
200
    memcpy(vector, p->prev_data, HALF_FRAME_LEN * sizeof(int16_t));
1128
200
    memcpy(vector + HALF_FRAME_LEN, in, FRAME_LEN * sizeof(int16_t));
1129
1130
200
    comp_lpc_coeff(vector, unq_lpc);
1131
200
    lpc2lsp(&unq_lpc[LPC_ORDER * 3], p->prev_lsp, cur_lsp);
1132
200
    lsp_quantize(p->lsp_index, cur_lsp, p->prev_lsp);
1133
1134
    /* Update memory */
1135
200
    memcpy(vector + LPC_ORDER, p->prev_data + SUBFRAME_LEN,
1136
           sizeof(int16_t) * SUBFRAME_LEN);
1137
200
    memcpy(vector + LPC_ORDER + SUBFRAME_LEN, in,
1138
           sizeof(int16_t) * (HALF_FRAME_LEN + SUBFRAME_LEN));
1139
200
    memcpy(p->prev_data, in + HALF_FRAME_LEN,
1140
           sizeof(int16_t) * HALF_FRAME_LEN);
1141
200
    memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
1142
1143
200
    perceptual_filter(p, weighted_lpc, unq_lpc, vector);
1144
1145
200
    memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
1146
200
    memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
1147
200
    memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
1148
1149
200
    ff_g723_1_scale_vector(vector, vector, FRAME_LEN + PITCH_MAX);
1150
1151
200
    p->pitch_lag[0] = estimate_pitch(vector, PITCH_MAX);
1152
200
    p->pitch_lag[1] = estimate_pitch(vector, PITCH_MAX + HALF_FRAME_LEN);
1153
1154
1000
    for (i = PITCH_MAX, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1155
800
        comp_harmonic_coeff(vector + i, p->pitch_lag[j >> 1], hf + j);
1156
1157
200
    memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
1158
200
    memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
1159
200
    memcpy(p->prev_weight_sig, vector + FRAME_LEN, sizeof(int16_t) * PITCH_MAX);
1160
1161
1000
    for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1162
800
        harmonic_filter(hf + j, vector + PITCH_MAX + i, in + i);
1163
1164
200
    ff_g723_1_inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, 0);
1165
200
    ff_g723_1_lsp_interpolate(qnt_lpc, cur_lsp, p->prev_lsp);
1166
1167
200
    memcpy(p->prev_lsp, cur_lsp, sizeof(int16_t) * LPC_ORDER);
1168
1169
200
    offset = 0;
1170
1000
    for (i = 0; i < SUBFRAMES; i++) {
1171
        int16_t impulse_resp[SUBFRAME_LEN];
1172
        int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
1173
        int16_t flt_in[SUBFRAME_LEN];
1174
        int16_t zero[LPC_ORDER], fir[LPC_ORDER], iir[LPC_ORDER];
1175
1176
        /**
1177
         * Compute the combined impulse response of the synthesis filter,
1178
         * formant perceptual weighting filter and harmonic noise shaping filter
1179
         */
1180
800
        memset(zero, 0, sizeof(int16_t) * LPC_ORDER);
1181
800
        memset(vector, 0, sizeof(int16_t) * PITCH_MAX);
1182
800
        memset(flt_in, 0, sizeof(int16_t) * SUBFRAME_LEN);
1183
1184
800
        flt_in[0] = 1 << 13; /* Unit impulse */
1185
800
        synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
1186
                             zero, zero, flt_in, vector + PITCH_MAX, 1);
1187
800
        harmonic_filter(hf + i, vector + PITCH_MAX, impulse_resp);
1188
1189
        /* Compute the combined zero input response */
1190
800
        flt_in[0] = 0;
1191
800
        memcpy(fir, p->perf_fir_mem, sizeof(int16_t) * LPC_ORDER);
1192
800
        memcpy(iir, p->perf_iir_mem, sizeof(int16_t) * LPC_ORDER);
1193
1194
800
        synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
1195
                             fir, iir, flt_in, vector + PITCH_MAX, 0);
1196
800
        memcpy(vector, p->harmonic_mem, sizeof(int16_t) * PITCH_MAX);
1197
800
        harmonic_noise_sub(hf + i, vector + PITCH_MAX, in);
1198
1199
800
        acb_search(p, residual, impulse_resp, in, i);
1200
800
        ff_g723_1_gen_acb_excitation(residual, p->prev_excitation,
1201
800
                                     p->pitch_lag[i >> 1], &p->subframe[i],
1202
                                     p->cur_rate);
1203
800
        sub_acb_contrib(residual, impulse_resp, in);
1204
1205
800
        fcb_search(p, impulse_resp, in, i);
1206
1207
        /* Reconstruct the excitation */
1208
800
        ff_g723_1_gen_acb_excitation(impulse_resp, p->prev_excitation,
1209
800
                                     p->pitch_lag[i >> 1], &p->subframe[i],
1210
                                     RATE_6300);
1211
1212
800
        memmove(p->prev_excitation, p->prev_excitation + SUBFRAME_LEN,
1213
                sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
1214
48800
        for (j = 0; j < SUBFRAME_LEN; j++)
1215
48000
            in[j] = av_clip_int16((in[j] << 1) + impulse_resp[j]);
1216
800
        memcpy(p->prev_excitation + PITCH_MAX - SUBFRAME_LEN, in,
1217
               sizeof(int16_t) * SUBFRAME_LEN);
1218
1219
        /* Update filter memories */
1220
800
        synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
1221
800
                             p->perf_fir_mem, p->perf_iir_mem,
1222
                             in, vector + PITCH_MAX, 0);
1223
800
        memmove(p->harmonic_mem, p->harmonic_mem + SUBFRAME_LEN,
1224
                sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
1225
800
        memcpy(p->harmonic_mem + PITCH_MAX - SUBFRAME_LEN, vector + PITCH_MAX,
1226
               sizeof(int16_t) * SUBFRAME_LEN);
1227
1228
800
        in     += SUBFRAME_LEN;
1229
800
        offset += LPC_ORDER;
1230
    }
1231
1232
200
    av_free(start);
1233
1234
200
    if ((ret = ff_alloc_packet2(avctx, avpkt, 24, 0)) < 0)
1235
        return ret;
1236
1237
200
    *got_packet_ptr = 1;
1238
200
    avpkt->size = pack_bitstream(p, avpkt);
1239
200
    return 0;
1240
}
1241
1242
static const AVCodecDefault defaults[] = {
1243
    { "b", "6300" },
1244
    { NULL },
1245
};
1246
1247
AVCodec ff_g723_1_encoder = {
1248
    .name           = "g723_1",
1249
    .long_name      = NULL_IF_CONFIG_SMALL("G.723.1"),
1250
    .type           = AVMEDIA_TYPE_AUDIO,
1251
    .id             = AV_CODEC_ID_G723_1,
1252
    .priv_data_size = sizeof(G723_1_Context),
1253
    .init           = g723_1_encode_init,
1254
    .encode2        = g723_1_encode_frame,
1255
    .defaults       = defaults,
1256
    .sample_fmts    = (const enum AVSampleFormat[]) {
1257
        AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
1258
    },
1259
};