GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/g723_1dec.c Lines: 438 505 86.7 %
Date: 2019-11-22 03:34:36 Branches: 180 230 78.3 %

Line Branch Exec Source
1
/*
2
 * G.723.1 compatible decoder
3
 * Copyright (c) 2006 Benjamin Larsson
4
 * Copyright (c) 2010 Mohamed Naufal Basheer
5
 *
6
 * This file is part of FFmpeg.
7
 *
8
 * FFmpeg is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * FFmpeg is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with FFmpeg; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
 */
22
23
/**
24
 * @file
25
 * G.723.1 compatible decoder
26
 */
27
28
#include "libavutil/channel_layout.h"
29
#include "libavutil/mem.h"
30
#include "libavutil/opt.h"
31
32
#define BITSTREAM_READER_LE
33
#include "acelp_vectors.h"
34
#include "avcodec.h"
35
#include "celp_filters.h"
36
#include "celp_math.h"
37
#include "get_bits.h"
38
#include "internal.h"
39
#include "g723_1.h"
40
41
#define CNG_RANDOM_SEED 12345
42
43
20
static av_cold int g723_1_decode_init(AVCodecContext *avctx)
44
{
45
20
    G723_1_Context *s = avctx->priv_data;
46
47
20
    avctx->sample_fmt     = AV_SAMPLE_FMT_S16P;
48

20
    if (avctx->channels < 1 || avctx->channels > 2) {
49
        av_log(avctx, AV_LOG_ERROR, "Only mono and stereo are supported (requested channels: %d).\n", avctx->channels);
50
        return AVERROR(EINVAL);
51
    }
52
20
    avctx->channel_layout = avctx->channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
53
40
    for (int ch = 0; ch < avctx->channels; ch++) {
54
20
        G723_1_ChannelContext *p = &s->ch[ch];
55
56
20
        p->pf_gain = 1 << 12;
57
58
20
        memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
59
20
        memcpy(p->sid_lsp,  dc_lsp, LPC_ORDER * sizeof(*p->sid_lsp));
60
61
20
        p->cng_random_seed = CNG_RANDOM_SEED;
62
20
        p->past_frame_type = SID_FRAME;
63
    }
64
65
20
    return 0;
66
}
67
68
/**
69
 * Unpack the frame into parameters.
70
 *
71
 * @param p           the context
72
 * @param buf         pointer to the input buffer
73
 * @param buf_size    size of the input buffer
74
 */
75
626
static int unpack_bitstream(G723_1_ChannelContext *p, const uint8_t *buf,
76
                            int buf_size)
77
{
78
    GetBitContext gb;
79
    int ad_cb_len;
80
    int temp, info_bits, i;
81
    int ret;
82
83
626
    ret = init_get_bits8(&gb, buf, buf_size);
84
626
    if (ret < 0)
85
        return ret;
86
87
    /* Extract frame type and rate info */
88
626
    info_bits = get_bits(&gb, 2);
89
90
626
    if (info_bits == 3) {
91
42
        p->cur_frame_type = UNTRANSMITTED_FRAME;
92
42
        return 0;
93
    }
94
95
    /* Extract 24 bit lsp indices, 8 bit for each band */
96
584
    p->lsp_index[2] = get_bits(&gb, 8);
97
584
    p->lsp_index[1] = get_bits(&gb, 8);
98
584
    p->lsp_index[0] = get_bits(&gb, 8);
99
100
584
    if (info_bits == 2) {
101
7
        p->cur_frame_type = SID_FRAME;
102
7
        p->subframe[0].amp_index = get_bits(&gb, 6);
103
7
        return 0;
104
    }
105
106
    /* Extract the info common to both rates */
107
577
    p->cur_rate       = info_bits ? RATE_5300 : RATE_6300;
108
577
    p->cur_frame_type = ACTIVE_FRAME;
109
110
577
    p->pitch_lag[0] = get_bits(&gb, 7);
111
577
    if (p->pitch_lag[0] > 123)       /* test if forbidden code */
112
1
        return -1;
113
576
    p->pitch_lag[0] += PITCH_MIN;
114
576
    p->subframe[1].ad_cb_lag = get_bits(&gb, 2);
115
116
576
    p->pitch_lag[1] = get_bits(&gb, 7);
117
576
    if (p->pitch_lag[1] > 123)
118
1
        return -1;
119
575
    p->pitch_lag[1] += PITCH_MIN;
120
575
    p->subframe[3].ad_cb_lag = get_bits(&gb, 2);
121
575
    p->subframe[0].ad_cb_lag = 1;
122
575
    p->subframe[2].ad_cb_lag = 1;
123
124
2875
    for (i = 0; i < SUBFRAMES; i++) {
125
        /* Extract combined gain */
126
2300
        temp = get_bits(&gb, 12);
127
2300
        ad_cb_len = 170;
128
2300
        p->subframe[i].dirac_train = 0;
129

2300
        if (p->cur_rate == RATE_6300 && p->pitch_lag[i >> 1] < SUBFRAME_LEN - 2) {
130
1790
            p->subframe[i].dirac_train = temp >> 11;
131
1790
            temp &= 0x7FF;
132
1790
            ad_cb_len = 85;
133
        }
134
2300
        p->subframe[i].ad_cb_gain = FASTDIV(temp, GAIN_LEVELS);
135
2300
        if (p->subframe[i].ad_cb_gain < ad_cb_len) {
136
2300
            p->subframe[i].amp_index = temp - p->subframe[i].ad_cb_gain *
137
                                       GAIN_LEVELS;
138
        } else {
139
            return -1;
140
        }
141
    }
142
143
575
    p->subframe[0].grid_index = get_bits1(&gb);
144
575
    p->subframe[1].grid_index = get_bits1(&gb);
145
575
    p->subframe[2].grid_index = get_bits1(&gb);
146
575
    p->subframe[3].grid_index = get_bits1(&gb);
147
148
575
    if (p->cur_rate == RATE_6300) {
149
543
        skip_bits1(&gb);  /* skip reserved bit */
150
151
        /* Compute pulse_pos index using the 13-bit combined position index */
152
543
        temp = get_bits(&gb, 13);
153
543
        p->subframe[0].pulse_pos = temp / 810;
154
155
543
        temp -= p->subframe[0].pulse_pos * 810;
156
543
        p->subframe[1].pulse_pos = FASTDIV(temp, 90);
157
158
543
        temp -= p->subframe[1].pulse_pos * 90;
159
543
        p->subframe[2].pulse_pos = FASTDIV(temp, 9);
160
543
        p->subframe[3].pulse_pos = temp - p->subframe[2].pulse_pos * 9;
161
162
1086
        p->subframe[0].pulse_pos = (p->subframe[0].pulse_pos << 16) +
163
543
                                   get_bits(&gb, 16);
164
1086
        p->subframe[1].pulse_pos = (p->subframe[1].pulse_pos << 14) +
165
543
                                   get_bits(&gb, 14);
166
1086
        p->subframe[2].pulse_pos = (p->subframe[2].pulse_pos << 16) +
167
543
                                   get_bits(&gb, 16);
168
1086
        p->subframe[3].pulse_pos = (p->subframe[3].pulse_pos << 14) +
169
543
                                   get_bits(&gb, 14);
170
171
543
        p->subframe[0].pulse_sign = get_bits(&gb, 6);
172
543
        p->subframe[1].pulse_sign = get_bits(&gb, 5);
173
543
        p->subframe[2].pulse_sign = get_bits(&gb, 6);
174
543
        p->subframe[3].pulse_sign = get_bits(&gb, 5);
175
    } else { /* 5300 bps */
176
32
        p->subframe[0].pulse_pos  = get_bits(&gb, 12);
177
32
        p->subframe[1].pulse_pos  = get_bits(&gb, 12);
178
32
        p->subframe[2].pulse_pos  = get_bits(&gb, 12);
179
32
        p->subframe[3].pulse_pos  = get_bits(&gb, 12);
180
181
32
        p->subframe[0].pulse_sign = get_bits(&gb, 4);
182
32
        p->subframe[1].pulse_sign = get_bits(&gb, 4);
183
32
        p->subframe[2].pulse_sign = get_bits(&gb, 4);
184
32
        p->subframe[3].pulse_sign = get_bits(&gb, 4);
185
    }
186
187
575
    return 0;
188
}
189
190
/**
191
 * Bitexact implementation of sqrt(val/2).
192
 */
193
4175
static int16_t square_root(unsigned val)
194
{
195
    av_assert2(!(val & 0x80000000));
196
197
4175
    return (ff_sqrt(val << 1) >> 1) & (~1);
198
}
199
200
/**
201
 * Generate fixed codebook excitation vector.
202
 *
203
 * @param vector    decoded excitation vector
204
 * @param subfrm    current subframe
205
 * @param cur_rate  current bitrate
206
 * @param pitch_lag closed loop pitch lag
207
 * @param index     current subframe index
208
 */
209
2300
static void gen_fcb_excitation(int16_t *vector, G723_1_Subframe *subfrm,
210
                               enum Rate cur_rate, int pitch_lag, int index)
211
{
212
    int temp, i, j;
213
214
2300
    memset(vector, 0, SUBFRAME_LEN * sizeof(*vector));
215
216
2300
    if (cur_rate == RATE_6300) {
217
2172
        if (subfrm->pulse_pos >= max_pos[index])
218
3
            return;
219
220
        /* Decode amplitudes and positions */
221
2169
        j = PULSE_MAX - pulses[index];
222
2169
        temp = subfrm->pulse_pos;
223
47580
        for (i = 0; i < SUBFRAME_LEN / GRID_SIZE; i++) {
224
47580
            temp -= combinatorial_table[j][i];
225
47580
            if (temp >= 0)
226
35652
                continue;
227
11928
            temp += combinatorial_table[j++][i];
228
11928
            if (subfrm->pulse_sign & (1 << (PULSE_MAX - j))) {
229
5889
                vector[subfrm->grid_index + GRID_SIZE * i] =
230
5889
                                        -fixed_cb_gain[subfrm->amp_index];
231
            } else {
232
6039
                vector[subfrm->grid_index + GRID_SIZE * i] =
233
6039
                                         fixed_cb_gain[subfrm->amp_index];
234
            }
235
11928
            if (j == PULSE_MAX)
236
2169
                break;
237
        }
238
2169
        if (subfrm->dirac_train == 1)
239
1085
            ff_g723_1_gen_dirac_train(vector, pitch_lag);
240
    } else { /* 5300 bps */
241
128
        int cb_gain  = fixed_cb_gain[subfrm->amp_index];
242
128
        int cb_shift = subfrm->grid_index;
243
128
        int cb_sign  = subfrm->pulse_sign;
244
128
        int cb_pos   = subfrm->pulse_pos;
245
        int offset, beta, lag;
246
247
640
        for (i = 0; i < 8; i += 2) {
248
512
            offset         = ((cb_pos & 7) << 3) + cb_shift + i;
249
512
            vector[offset] = (cb_sign & 1) ? cb_gain : -cb_gain;
250
512
            cb_pos  >>= 3;
251
512
            cb_sign >>= 1;
252
        }
253
254
        /* Enhance harmonic components */
255
128
        lag  = pitch_contrib[subfrm->ad_cb_gain << 1] + pitch_lag +
256
128
               subfrm->ad_cb_lag - 1;
257
128
        beta = pitch_contrib[(subfrm->ad_cb_gain << 1) + 1];
258
259
128
        if (lag < SUBFRAME_LEN - 2) {
260
4154
            for (i = lag; i < SUBFRAME_LEN; i++)
261
4050
                vector[i] += beta * vector[i - lag] >> 15;
262
        }
263
    }
264
}
265
266
/**
267
 * Estimate maximum auto-correlation around pitch lag.
268
 *
269
 * @param buf       buffer with offset applied
270
 * @param offset    offset of the excitation vector
271
 * @param ccr_max   pointer to the maximum auto-correlation
272
 * @param pitch_lag decoded pitch lag
273
 * @param length    length of autocorrelation
274
 * @param dir       forward lag(1) / backward lag(-1)
275
 */
276
4919
static int autocorr_max(const int16_t *buf, int offset, int *ccr_max,
277
                        int pitch_lag, int length, int dir)
278
{
279
4919
    int limit, ccr, lag = 0;
280
    int i;
281
282
4919
    pitch_lag = FFMIN(PITCH_MAX - 3, pitch_lag);
283
4919
    if (dir > 0)
284
2172
        limit = FFMIN(FRAME_LEN + PITCH_MAX - offset - length, pitch_lag + 3);
285
    else
286
2747
        limit = pitch_lag + 3;
287
288
34905
    for (i = pitch_lag - 3; i <= limit; i++) {
289
29986
        ccr = ff_g723_1_dot_product(buf, buf + dir * i, length);
290
291
29986
        if (ccr > *ccr_max) {
292
11007
            *ccr_max = ccr;
293
11007
            lag = i;
294
        }
295
    }
296
4919
    return lag;
297
}
298
299
/**
300
 * Calculate pitch postfilter optimal and scaling gains.
301
 *
302
 * @param lag      pitch postfilter forward/backward lag
303
 * @param ppf      pitch postfilter parameters
304
 * @param cur_rate current bitrate
305
 * @param tgt_eng  target energy
306
 * @param ccr      cross-correlation
307
 * @param res_eng  residual energy
308
 */
309
2162
static void comp_ppf_gains(int lag, PPFParam *ppf, enum Rate cur_rate,
310
                           int tgt_eng, int ccr, int res_eng)
311
{
312
    int pf_residual;     /* square of postfiltered residual */
313
    int temp1, temp2;
314
315
2162
    ppf->index = lag;
316
317
2162
    temp1 = tgt_eng * res_eng >> 1;
318
2162
    temp2 = ccr * ccr << 1;
319
320
2162
    if (temp2 > temp1) {
321
1711
        if (ccr >= res_eng) {
322
327
            ppf->opt_gain = ppf_gain_weight[cur_rate];
323
        } else {
324
1384
            ppf->opt_gain = (ccr << 15) / res_eng *
325
1384
                            ppf_gain_weight[cur_rate] >> 15;
326
        }
327
        /* pf_res^2 = tgt_eng + 2*ccr*gain + res_eng*gain^2 */
328
1711
        temp1       = (tgt_eng << 15) + (ccr * ppf->opt_gain << 1);
329
1711
        temp2       = (ppf->opt_gain * ppf->opt_gain >> 15) * res_eng;
330
1711
        pf_residual = av_sat_add32(temp1, temp2 + (1 << 15)) >> 16;
331
332
1711
        if (tgt_eng >= pf_residual << 1) {
333
4
            temp1 = 0x7fff;
334
        } else {
335
1707
            temp1 = (tgt_eng << 14) / pf_residual;
336
        }
337
338
        /* scaling_gain = sqrt(tgt_eng/pf_res^2) */
339
1711
        ppf->sc_gain = square_root(temp1 << 16);
340
    } else {
341
451
        ppf->opt_gain = 0;
342
451
        ppf->sc_gain  = 0x7fff;
343
    }
344
345
2162
    ppf->opt_gain = av_clip_int16(ppf->opt_gain * ppf->sc_gain >> 15);
346
2162
}
347
348
/**
349
 * Calculate pitch postfilter parameters.
350
 *
351
 * @param p         the context
352
 * @param offset    offset of the excitation vector
353
 * @param pitch_lag decoded pitch lag
354
 * @param ppf       pitch postfilter parameters
355
 * @param cur_rate  current bitrate
356
 */
357
2172
static void comp_ppf_coeff(G723_1_ChannelContext *p, int offset, int pitch_lag,
358
                           PPFParam *ppf, enum Rate cur_rate)
359
{
360
361
    int16_t scale;
362
    int i;
363
    int temp1, temp2;
364
365
    /*
366
     * 0 - target energy
367
     * 1 - forward cross-correlation
368
     * 2 - forward residual energy
369
     * 3 - backward cross-correlation
370
     * 4 - backward residual energy
371
     */
372
2172
    int energy[5] = {0, 0, 0, 0, 0};
373
2172
    int16_t *buf  = p->audio + LPC_ORDER + offset;
374
2172
    int fwd_lag   = autocorr_max(buf, offset, &energy[1], pitch_lag,
375
                                 SUBFRAME_LEN, 1);
376
2172
    int back_lag  = autocorr_max(buf, offset, &energy[3], pitch_lag,
377
                                 SUBFRAME_LEN, -1);
378
379
2172
    ppf->index    = 0;
380
2172
    ppf->opt_gain = 0;
381
2172
    ppf->sc_gain  = 0x7fff;
382
383
    /* Case 0, Section 3.6 */
384

2172
    if (!back_lag && !fwd_lag)
385
10
        return;
386
387
    /* Compute target energy */
388
2162
    energy[0] = ff_g723_1_dot_product(buf, buf, SUBFRAME_LEN);
389
390
    /* Compute forward residual energy */
391
2162
    if (fwd_lag)
392
1537
        energy[2] = ff_g723_1_dot_product(buf + fwd_lag, buf + fwd_lag,
393
                                          SUBFRAME_LEN);
394
395
    /* Compute backward residual energy */
396
2162
    if (back_lag)
397
2156
        energy[4] = ff_g723_1_dot_product(buf - back_lag, buf - back_lag,
398
                                          SUBFRAME_LEN);
399
400
    /* Normalize and shorten */
401
2162
    temp1 = 0;
402
12972
    for (i = 0; i < 5; i++)
403
10810
        temp1 = FFMAX(energy[i], temp1);
404
405
2162
    scale = ff_g723_1_normalize_bits(temp1, 31);
406
12972
    for (i = 0; i < 5; i++)
407
10810
        energy[i] = (energy[i] << scale) >> 16;
408
409

2162
    if (fwd_lag && !back_lag) {  /* Case 1 */
410
6
        comp_ppf_gains(fwd_lag,  ppf, cur_rate, energy[0], energy[1],
411
                       energy[2]);
412
2156
    } else if (!fwd_lag) {       /* Case 2 */
413
625
        comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
414
                       energy[4]);
415
    } else {                     /* Case 3 */
416
417
        /*
418
         * Select the largest of energy[1]^2/energy[2]
419
         * and energy[3]^2/energy[4]
420
         */
421
1531
        temp1 = energy[4] * ((energy[1] * energy[1] + (1 << 14)) >> 15);
422
1531
        temp2 = energy[2] * ((energy[3] * energy[3] + (1 << 14)) >> 15);
423
1531
        if (temp1 >= temp2) {
424
662
            comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
425
                           energy[2]);
426
        } else {
427
869
            comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
428
                           energy[4]);
429
        }
430
    }
431
}
432
433
/**
434
 * Classify frames as voiced/unvoiced.
435
 *
436
 * @param p         the context
437
 * @param pitch_lag decoded pitch_lag
438
 * @param exc_eng   excitation energy estimation
439
 * @param scale     scaling factor of exc_eng
440
 *
441
 * @return residual interpolation index if voiced, 0 otherwise
442
 */
443
575
static int comp_interp_index(G723_1_ChannelContext *p, int pitch_lag,
444
                             int *exc_eng, int *scale)
445
{
446
575
    int offset = PITCH_MAX + 2 * SUBFRAME_LEN;
447
575
    int16_t *buf = p->audio + LPC_ORDER;
448
449
    int index, ccr, tgt_eng, best_eng, temp;
450
451
575
    *scale = ff_g723_1_scale_vector(buf, p->excitation, FRAME_LEN + PITCH_MAX);
452
575
    buf   += offset;
453
454
    /* Compute maximum backward cross-correlation */
455
575
    ccr   = 0;
456
575
    index = autocorr_max(buf, offset, &ccr, pitch_lag, SUBFRAME_LEN * 2, -1);
457
575
    ccr   = av_sat_add32(ccr, 1 << 15) >> 16;
458
459
    /* Compute target energy */
460
575
    tgt_eng  = ff_g723_1_dot_product(buf, buf, SUBFRAME_LEN * 2);
461
575
    *exc_eng = av_sat_add32(tgt_eng, 1 << 15) >> 16;
462
463
575
    if (ccr <= 0)
464
1
        return 0;
465
466
    /* Compute best energy */
467
574
    best_eng = ff_g723_1_dot_product(buf - index, buf - index,
468
                                     SUBFRAME_LEN * 2);
469
574
    best_eng = av_sat_add32(best_eng, 1 << 15) >> 16;
470
471
574
    temp = best_eng * *exc_eng >> 3;
472
473
574
    if (temp < ccr * ccr) {
474
489
        return index;
475
    } else
476
85
        return 0;
477
}
478
479
/**
480
 * Perform residual interpolation based on frame classification.
481
 *
482
 * @param buf   decoded excitation vector
483
 * @param out   output vector
484
 * @param lag   decoded pitch lag
485
 * @param gain  interpolated gain
486
 * @param rseed seed for random number generator
487
 */
488
2
static void residual_interp(int16_t *buf, int16_t *out, int lag,
489
                            int gain, int *rseed)
490
{
491
    int i;
492
2
    if (lag) { /* Voiced */
493
2
        int16_t *vector_ptr = buf + PITCH_MAX;
494
        /* Attenuate */
495
80
        for (i = 0; i < lag; i++)
496
78
            out[i] = vector_ptr[i - lag] * 3 >> 2;
497
2
        av_memcpy_backptr((uint8_t*)(out + lag), lag * sizeof(*out),
498
2
                          (FRAME_LEN - lag) * sizeof(*out));
499
    } else {  /* Unvoiced */
500
        for (i = 0; i < FRAME_LEN; i++) {
501
            *rseed = (int16_t)(*rseed * 521 + 259);
502
            out[i] = gain * *rseed >> 15;
503
        }
504
        memset(buf, 0, (FRAME_LEN + PITCH_MAX) * sizeof(*buf));
505
    }
506
2
}
507
508
/**
509
 * Perform IIR filtering.
510
 *
511
 * @param fir_coef FIR coefficients
512
 * @param iir_coef IIR coefficients
513
 * @param src      source vector
514
 * @param dest     destination vector
515
 * @param width    width of the output, 16 bits(0) / 32 bits(1)
516
 */
517
#define iir_filter(fir_coef, iir_coef, src, dest, width)\
518
{\
519
    int m, n;\
520
    int res_shift = 16 & ~-(width);\
521
    int in_shift  = 16 - res_shift;\
522
\
523
    for (m = 0; m < SUBFRAME_LEN; m++) {\
524
        int64_t filter = 0;\
525
        for (n = 1; n <= LPC_ORDER; n++) {\
526
            filter -= (fir_coef)[n - 1] * (src)[m - n] -\
527
                      (iir_coef)[n - 1] * ((dest)[m - n] >> in_shift);\
528
        }\
529
\
530
        (dest)[m] = av_clipl_int32(((src)[m] * 65536) + (filter * 8) +\
531
                                   (1 << 15)) >> res_shift;\
532
    }\
533
}
534
535
/**
536
 * Adjust gain of postfiltered signal.
537
 *
538
 * @param p      the context
539
 * @param buf    postfiltered output vector
540
 * @param energy input energy coefficient
541
 */
542
2376
static void gain_scale(G723_1_ChannelContext *p, int16_t * buf, int energy)
543
{
544
    int num, denom, gain, bits1, bits2;
545
    int i;
546
547
2376
    num   = energy;
548
2376
    denom = 0;
549
144936
    for (i = 0; i < SUBFRAME_LEN; i++) {
550
142560
        int temp = buf[i] >> 2;
551
142560
        temp *= temp;
552
142560
        denom = av_sat_dadd32(denom, temp);
553
    }
554
555

2376
    if (num && denom) {
556
2368
        bits1   = ff_g723_1_normalize_bits(num,   31);
557
2368
        bits2   = ff_g723_1_normalize_bits(denom, 31);
558
2368
        num     = num << bits1 >> 1;
559
2368
        denom <<= bits2;
560
561
2368
        bits2 = 5 + bits1 - bits2;
562
2368
        bits2 = av_clip_uintp2(bits2, 5);
563
564
2368
        gain = (num >> 1) / (denom >> 16);
565
2368
        gain = square_root(gain << 16 >> bits2);
566
    } else {
567
8
        gain = 1 << 12;
568
    }
569
570
144936
    for (i = 0; i < SUBFRAME_LEN; i++) {
571
142560
        p->pf_gain = (15 * p->pf_gain + gain + (1 << 3)) >> 4;
572
142560
        buf[i]     = av_clip_int16((buf[i] * (p->pf_gain + (p->pf_gain >> 4)) +
573
                                   (1 << 10)) >> 11);
574
    }
575
2376
}
576
577
/**
578
 * Perform formant filtering.
579
 *
580
 * @param p   the context
581
 * @param lpc quantized lpc coefficients
582
 * @param buf input buffer
583
 * @param dst output buffer
584
 */
585
594
static void formant_postfilter(G723_1_ChannelContext *p, int16_t *lpc,
586
                               int16_t *buf, int16_t *dst)
587
{
588
    int16_t filter_coef[2][LPC_ORDER];
589
    int filter_signal[LPC_ORDER + FRAME_LEN], *signal_ptr;
590
    int i, j, k;
591
592
594
    memcpy(buf, p->fir_mem, LPC_ORDER * sizeof(*buf));
593
594
    memcpy(filter_signal, p->iir_mem, LPC_ORDER * sizeof(*filter_signal));
594
595
2970
    for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
596
26136
        for (k = 0; k < LPC_ORDER; k++) {
597
23760
            filter_coef[0][k] = (-lpc[k] * postfilter_tbl[0][k] +
598
23760
                                 (1 << 14)) >> 15;
599
23760
            filter_coef[1][k] = (-lpc[k] * postfilter_tbl[1][k] +
600
23760
                                 (1 << 14)) >> 15;
601
        }
602

1570536
        iir_filter(filter_coef[0], filter_coef[1], buf + i, filter_signal + i, 1);
603
2376
        lpc += LPC_ORDER;
604
    }
605
606
594
    memcpy(p->fir_mem, buf + FRAME_LEN, LPC_ORDER * sizeof(int16_t));
607
594
    memcpy(p->iir_mem, filter_signal + FRAME_LEN, LPC_ORDER * sizeof(int));
608
609
594
    buf += LPC_ORDER;
610
594
    signal_ptr = filter_signal + LPC_ORDER;
611
2970
    for (i = 0; i < SUBFRAMES; i++) {
612
        int temp;
613
        int auto_corr[2];
614
        int scale, energy;
615
616
        /* Normalize */
617
2376
        scale = ff_g723_1_scale_vector(dst, buf, SUBFRAME_LEN);
618
619
        /* Compute auto correlation coefficients */
620
2376
        auto_corr[0] = ff_g723_1_dot_product(dst, dst + 1, SUBFRAME_LEN - 1);
621
2376
        auto_corr[1] = ff_g723_1_dot_product(dst, dst,     SUBFRAME_LEN);
622
623
        /* Compute reflection coefficient */
624
2376
        temp = auto_corr[1] >> 16;
625
2376
        if (temp) {
626
2376
            temp = (auto_corr[0] >> 2) / temp;
627
        }
628
2376
        p->reflection_coef = (3 * p->reflection_coef + temp + 2) >> 2;
629
2376
        temp = -p->reflection_coef >> 1 & ~3;
630
631
        /* Compensation filter */
632
144936
        for (j = 0; j < SUBFRAME_LEN; j++) {
633
285120
            dst[j] = av_sat_dadd32(signal_ptr[j],
634
142560
                                   (signal_ptr[j - 1] >> 16) * temp) >> 16;
635
        }
636
637
        /* Compute normalized signal energy */
638
2376
        temp = 2 * scale + 4;
639
2376
        if (temp < 0) {
640
218
            energy = av_clipl_int32((int64_t)auto_corr[1] << -temp);
641
        } else
642
2158
            energy = auto_corr[1] >> temp;
643
644
2376
        gain_scale(p, dst, energy);
645
646
2376
        buf        += SUBFRAME_LEN;
647
2376
        signal_ptr += SUBFRAME_LEN;
648
2376
        dst        += SUBFRAME_LEN;
649
    }
650
594
}
651
652
7
static int sid_gain_to_lsp_index(int gain)
653
{
654
7
    if (gain < 0x10)
655
7
        return gain << 6;
656
    else if (gain < 0x20)
657
        return gain - 8 << 7;
658
    else
659
        return gain - 20 << 8;
660
}
661
662
1470
static inline int cng_rand(int *state, int base)
663
{
664
1470
    *state = (*state * 521 + 259) & 0xFFFF;
665
1470
    return (*state & 0x7FFF) * base >> 15;
666
}
667
668
static int estimate_sid_gain(G723_1_ChannelContext *p)
669
{
670
    int i, shift, seg, seg2, t, val, val_add, x, y;
671
672
    shift = 16 - p->cur_gain * 2;
673
    if (shift > 0) {
674
        if (p->sid_gain == 0) {
675
            t = 0;
676
        } else if (shift >= 31 || (int32_t)((uint32_t)p->sid_gain << shift) >> shift != p->sid_gain) {
677
            if (p->sid_gain < 0) t = INT32_MIN;
678
            else                 t = INT32_MAX;
679
        } else
680
            t = p->sid_gain * (1 << shift);
681
    } else if(shift < -31) {
682
        t = (p->sid_gain < 0) ? -1 : 0;
683
    }else
684
        t = p->sid_gain >> -shift;
685
    x = av_clipl_int32(t * (int64_t)cng_filt[0] >> 16);
686
687
    if (x >= cng_bseg[2])
688
        return 0x3F;
689
690
    if (x >= cng_bseg[1]) {
691
        shift = 4;
692
        seg   = 3;
693
    } else {
694
        shift = 3;
695
        seg   = (x >= cng_bseg[0]);
696
    }
697
    seg2 = FFMIN(seg, 3);
698
699
    val     = 1 << shift;
700
    val_add = val >> 1;
701
    for (i = 0; i < shift; i++) {
702
        t = seg * 32 + (val << seg2);
703
        t *= t;
704
        if (x >= t)
705
            val += val_add;
706
        else
707
            val -= val_add;
708
        val_add >>= 1;
709
    }
710
711
    t = seg * 32 + (val << seg2);
712
    y = t * t - x;
713
    if (y <= 0) {
714
        t = seg * 32 + (val + 1 << seg2);
715
        t = t * t - x;
716
        val = (seg2 - 1) * 16 + val;
717
        if (t >= y)
718
            val++;
719
    } else {
720
        t = seg * 32 + (val - 1 << seg2);
721
        t = t * t - x;
722
        val = (seg2 - 1) * 16 + val;
723
        if (t >= y)
724
            val--;
725
    }
726
727
    return val;
728
}
729
730
49
static void generate_noise(G723_1_ChannelContext *p)
731
{
732
    int i, j, idx, t;
733
    int off[SUBFRAMES];
734
    int signs[SUBFRAMES / 2 * 11], pos[SUBFRAMES / 2 * 11];
735
    int tmp[SUBFRAME_LEN * 2];
736
    int16_t *vector_ptr;
737
    int64_t sum;
738
    int b0, c, delta, x, shift;
739
740
49
    p->pitch_lag[0] = cng_rand(&p->cng_random_seed, 21) + 123;
741
49
    p->pitch_lag[1] = cng_rand(&p->cng_random_seed, 19) + 123;
742
743
245
    for (i = 0; i < SUBFRAMES; i++) {
744
196
        p->subframe[i].ad_cb_gain = cng_rand(&p->cng_random_seed, 50) + 1;
745
196
        p->subframe[i].ad_cb_lag  = cng_adaptive_cb_lag[i];
746
    }
747
748
147
    for (i = 0; i < SUBFRAMES / 2; i++) {
749
98
        t = cng_rand(&p->cng_random_seed, 1 << 13);
750
98
        off[i * 2]     =   t       & 1;
751
98
        off[i * 2 + 1] = ((t >> 1) & 1) + SUBFRAME_LEN;
752
98
        t >>= 2;
753
1176
        for (j = 0; j < 11; j++) {
754
1078
            signs[i * 11 + j] = ((t & 1) * 2 - 1)  * (1 << 14);
755
1078
            t >>= 1;
756
        }
757
    }
758
759
49
    idx = 0;
760
245
    for (i = 0; i < SUBFRAMES; i++) {
761
6076
        for (j = 0; j < SUBFRAME_LEN / 2; j++)
762
5880
            tmp[j] = j;
763
196
        t = SUBFRAME_LEN / 2;
764
1274
        for (j = 0; j < pulses[i]; j++, idx++) {
765
1078
            int idx2 = cng_rand(&p->cng_random_seed, t);
766
767
1078
            pos[idx]  = tmp[idx2] * 2 + off[i];
768
1078
            tmp[idx2] = tmp[--t];
769
        }
770
    }
771
772
49
    vector_ptr = p->audio + LPC_ORDER;
773
49
    memcpy(vector_ptr, p->prev_excitation,
774
           PITCH_MAX * sizeof(*p->excitation));
775
147
    for (i = 0; i < SUBFRAMES; i += 2) {
776
98
        ff_g723_1_gen_acb_excitation(vector_ptr, vector_ptr,
777
98
                                     p->pitch_lag[i >> 1], &p->subframe[i],
778
                                     p->cur_rate);
779
98
        ff_g723_1_gen_acb_excitation(vector_ptr + SUBFRAME_LEN,
780
                                     vector_ptr + SUBFRAME_LEN,
781
98
                                     p->pitch_lag[i >> 1], &p->subframe[i + 1],
782
                                     p->cur_rate);
783
784
98
        t = 0;
785
11858
        for (j = 0; j < SUBFRAME_LEN * 2; j++)
786
11760
            t |= FFABS(vector_ptr[j]);
787
98
        t = FFMIN(t, 0x7FFF);
788
98
        if (!t) {
789
            shift = 0;
790
        } else {
791
98
            shift = -10 + av_log2(t);
792
98
            if (shift < -2)
793
96
                shift = -2;
794
        }
795
98
        sum = 0;
796
98
        if (shift < 0) {
797
11616
           for (j = 0; j < SUBFRAME_LEN * 2; j++) {
798
11520
               t      = vector_ptr[j] * (1 << -shift);
799
11520
               sum   += t * t;
800
11520
               tmp[j] = t;
801
           }
802
        } else {
803
242
           for (j = 0; j < SUBFRAME_LEN * 2; j++) {
804
240
               t      = vector_ptr[j] >> shift;
805
240
               sum   += t * t;
806
240
               tmp[j] = t;
807
           }
808
        }
809
810
98
        b0 = 0;
811
1176
        for (j = 0; j < 11; j++)
812
1078
            b0 += tmp[pos[(i / 2) * 11 + j]] * signs[(i / 2) * 11 + j];
813
98
        b0 = b0 * 2 * 2979LL + (1 << 29) >> 30; // approximated division by 11
814
815
98
        c = p->cur_gain * (p->cur_gain * SUBFRAME_LEN >> 5);
816
98
        if (shift * 2 + 3 >= 0)
817
2
            c >>= shift * 2 + 3;
818
        else
819
96
            c <<= -(shift * 2 + 3);
820
98
        c = (av_clipl_int32(sum << 1) - c) * 2979LL >> 15;
821
822
98
        delta = b0 * b0 * 2 - c;
823
98
        if (delta <= 0) {
824
2
            x = -b0;
825
        } else {
826
96
            delta = square_root(delta);
827
96
            x     = delta - b0;
828
96
            t     = delta + b0;
829
96
            if (FFABS(t) < FFABS(x))
830
44
                x = -t;
831
        }
832
98
        shift++;
833
98
        if (shift < 0)
834
96
           x >>= -shift;
835
        else
836
2
           x *= 1 << shift;
837
98
        x = av_clip(x, -10000, 10000);
838
839
1176
        for (j = 0; j < 11; j++) {
840
1078
            idx = (i / 2) * 11 + j;
841
1078
            vector_ptr[pos[idx]] = av_clip_int16(vector_ptr[pos[idx]] +
842
1078
                                                 (x * signs[idx] >> 15));
843
        }
844
845
        /* copy decoded data to serve as a history for the next decoded subframes */
846
98
        memcpy(vector_ptr + PITCH_MAX, vector_ptr,
847
               sizeof(*vector_ptr) * SUBFRAME_LEN * 2);
848
98
        vector_ptr += SUBFRAME_LEN * 2;
849
    }
850
    /* Save the excitation for the next frame */
851
49
    memcpy(p->prev_excitation, p->audio + LPC_ORDER + FRAME_LEN,
852
           PITCH_MAX * sizeof(*p->excitation));
853
49
}
854
855
626
static int g723_1_decode_frame(AVCodecContext *avctx, void *data,
856
                               int *got_frame_ptr, AVPacket *avpkt)
857
{
858
626
    G723_1_Context *s  = avctx->priv_data;
859
626
    AVFrame *frame     = data;
860
626
    const uint8_t *buf = avpkt->data;
861
626
    int buf_size       = avpkt->size;
862
626
    int dec_mode       = buf[0] & 3;
863
864
    PPFParam ppf[SUBFRAMES];
865
    int16_t cur_lsp[LPC_ORDER];
866
    int16_t lpc[SUBFRAMES * LPC_ORDER];
867
    int16_t acb_vector[SUBFRAME_LEN];
868
    int16_t *out;
869
626
    int bad_frame = 0, i, j, ret;
870
871
626
    if (buf_size < frame_size[dec_mode] * avctx->channels) {
872
        if (buf_size)
873
            av_log(avctx, AV_LOG_WARNING,
874
                   "Expected %d bytes, got %d - skipping packet\n",
875
                   frame_size[dec_mode], buf_size);
876
        *got_frame_ptr = 0;
877
        return buf_size;
878
    }
879
880
626
    frame->nb_samples = FRAME_LEN;
881
626
    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
882
        return ret;
883
884
1252
    for (int ch = 0; ch < avctx->channels; ch++) {
885
626
        G723_1_ChannelContext *p = &s->ch[ch];
886
626
        int16_t *audio = p->audio;
887
888
626
        if (unpack_bitstream(p, buf + ch * (buf_size / avctx->channels),
889
626
                             buf_size / avctx->channels) < 0) {
890
2
            bad_frame = 1;
891
2
            if (p->past_frame_type == ACTIVE_FRAME)
892
2
                p->cur_frame_type = ACTIVE_FRAME;
893
            else
894
                p->cur_frame_type = UNTRANSMITTED_FRAME;
895
        }
896
897
626
        out = (int16_t *)frame->extended_data[ch];
898
899
626
        if (p->cur_frame_type == ACTIVE_FRAME) {
900
577
            if (!bad_frame)
901
575
                p->erased_frames = 0;
902
2
            else if (p->erased_frames != 3)
903
2
                p->erased_frames++;
904
905
577
            ff_g723_1_inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, bad_frame);
906
577
            ff_g723_1_lsp_interpolate(lpc, cur_lsp, p->prev_lsp);
907
908
            /* Save the lsp_vector for the next frame */
909
577
            memcpy(p->prev_lsp, cur_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
910
911
            /* Generate the excitation for the frame */
912
577
            memcpy(p->excitation, p->prev_excitation,
913
                   PITCH_MAX * sizeof(*p->excitation));
914
577
            if (!p->erased_frames) {
915
575
                int16_t *vector_ptr = p->excitation + PITCH_MAX;
916
917
                /* Update interpolation gain memory */
918
575
                p->interp_gain = fixed_cb_gain[(p->subframe[2].amp_index +
919
575
                                                p->subframe[3].amp_index) >> 1];
920
2875
                for (i = 0; i < SUBFRAMES; i++) {
921
2300
                    gen_fcb_excitation(vector_ptr, &p->subframe[i], p->cur_rate,
922
2300
                                       p->pitch_lag[i >> 1], i);
923
2300
                    ff_g723_1_gen_acb_excitation(acb_vector,
924
2300
                                                 &p->excitation[SUBFRAME_LEN * i],
925
2300
                                                 p->pitch_lag[i >> 1],
926
                                                 &p->subframe[i], p->cur_rate);
927
                    /* Get the total excitation */
928
140300
                    for (j = 0; j < SUBFRAME_LEN; j++) {
929
138000
                        int v = av_clip_int16(vector_ptr[j] * 2);
930
138000
                        vector_ptr[j] = av_clip_int16(v + acb_vector[j]);
931
                    }
932
2300
                    vector_ptr += SUBFRAME_LEN;
933
                }
934
935
575
                vector_ptr = p->excitation + PITCH_MAX;
936
937
575
                p->interp_index = comp_interp_index(p, p->pitch_lag[1],
938
                                                    &p->sid_gain, &p->cur_gain);
939
940
                /* Perform pitch postfiltering */
941
575
                if (s->postfilter) {
942
543
                    i = PITCH_MAX;
943
2715
                    for (j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
944
2172
                        comp_ppf_coeff(p, i, p->pitch_lag[j >> 1],
945
2172
                                       ppf + j, p->cur_rate);
946
947
2715
                    for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
948
2172
                        ff_acelp_weighted_vector_sum(p->audio + LPC_ORDER + i,
949
2172
                                                     vector_ptr + i,
950
2172
                                                     vector_ptr + i + ppf[j].index,
951
2172
                                                     ppf[j].sc_gain,
952
2172
                                                     ppf[j].opt_gain,
953
                                                     1 << 14, 15, SUBFRAME_LEN);
954
                } else {
955
32
                    audio = vector_ptr - LPC_ORDER;
956
                }
957
958
                /* Save the excitation for the next frame */
959
575
                memcpy(p->prev_excitation, p->excitation + FRAME_LEN,
960
                       PITCH_MAX * sizeof(*p->excitation));
961
            } else {
962
2
                p->interp_gain = (p->interp_gain * 3 + 2) >> 2;
963
2
                if (p->erased_frames == 3) {
964
                    /* Mute output */
965
                    memset(p->excitation, 0,
966
                           (FRAME_LEN + PITCH_MAX) * sizeof(*p->excitation));
967
                    memset(p->prev_excitation, 0,
968
                           PITCH_MAX * sizeof(*p->excitation));
969
                    memset(frame->data[0], 0,
970
                           (FRAME_LEN + LPC_ORDER) * sizeof(int16_t));
971
                } else {
972
2
                    int16_t *buf = p->audio + LPC_ORDER;
973
974
                    /* Regenerate frame */
975
2
                    residual_interp(p->excitation, buf, p->interp_index,
976
                                    p->interp_gain, &p->random_seed);
977
978
                    /* Save the excitation for the next frame */
979
2
                    memcpy(p->prev_excitation, buf + (FRAME_LEN - PITCH_MAX),
980
                           PITCH_MAX * sizeof(*p->excitation));
981
                }
982
            }
983
577
            p->cng_random_seed = CNG_RANDOM_SEED;
984
        } else {
985
49
            if (p->cur_frame_type == SID_FRAME) {
986
7
                p->sid_gain = sid_gain_to_lsp_index(p->subframe[0].amp_index);
987
7
                ff_g723_1_inverse_quant(p->sid_lsp, p->prev_lsp, p->lsp_index, 0);
988
42
            } else if (p->past_frame_type == ACTIVE_FRAME) {
989
                p->sid_gain = estimate_sid_gain(p);
990
            }
991
992
49
            if (p->past_frame_type == ACTIVE_FRAME)
993
3
                p->cur_gain = p->sid_gain;
994
            else
995
46
                p->cur_gain = (p->cur_gain * 7 + p->sid_gain) >> 3;
996
49
            generate_noise(p);
997
49
            ff_g723_1_lsp_interpolate(lpc, p->sid_lsp, p->prev_lsp);
998
            /* Save the lsp_vector for the next frame */
999
49
            memcpy(p->prev_lsp, p->sid_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
1000
        }
1001
1002
626
        p->past_frame_type = p->cur_frame_type;
1003
1004
626
        memcpy(p->audio, p->synth_mem, LPC_ORDER * sizeof(*p->audio));
1005
3130
        for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1006
2504
            ff_celp_lp_synthesis_filter(p->audio + i, &lpc[j * LPC_ORDER],
1007
2504
                                        audio + i, SUBFRAME_LEN, LPC_ORDER,
1008
                                        0, 1, 1 << 12);
1009
626
        memcpy(p->synth_mem, p->audio + FRAME_LEN, LPC_ORDER * sizeof(*p->audio));
1010
1011
626
        if (s->postfilter) {
1012
594
            formant_postfilter(p, lpc, p->audio, out);
1013
        } else { // if output is not postfiltered it should be scaled by 2
1014
7712
            for (i = 0; i < FRAME_LEN; i++)
1015
7680
                out[i] = av_clip_int16(2 * p->audio[LPC_ORDER + i]);
1016
        }
1017
    }
1018
1019
626
    *got_frame_ptr = 1;
1020
1021
626
    return frame_size[dec_mode] * avctx->channels;
1022
}
1023
1024
#define OFFSET(x) offsetof(G723_1_Context, x)
1025
#define AD     AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1026
1027
static const AVOption options[] = {
1028
    { "postfilter", "enable postfilter", OFFSET(postfilter), AV_OPT_TYPE_BOOL,
1029
      { .i64 = 1 }, 0, 1, AD },
1030
    { NULL }
1031
};
1032
1033
1034
static const AVClass g723_1dec_class = {
1035
    .class_name = "G.723.1 decoder",
1036
    .item_name  = av_default_item_name,
1037
    .option     = options,
1038
    .version    = LIBAVUTIL_VERSION_INT,
1039
};
1040
1041
AVCodec ff_g723_1_decoder = {
1042
    .name           = "g723_1",
1043
    .long_name      = NULL_IF_CONFIG_SMALL("G.723.1"),
1044
    .type           = AVMEDIA_TYPE_AUDIO,
1045
    .id             = AV_CODEC_ID_G723_1,
1046
    .priv_data_size = sizeof(G723_1_Context),
1047
    .init           = g723_1_decode_init,
1048
    .decode         = g723_1_decode_frame,
1049
    .capabilities   = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DR1,
1050
    .priv_class     = &g723_1dec_class,
1051
};