]> git.sesse.net Git - ffmpeg/blob - libavcodec/g723_1.c
amrwbdec: set channels, channel_layout, and sample_rate
[ffmpeg] / libavcodec / g723_1.c
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 Libav.
7  *
8  * Libav 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  * Libav 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 Libav; 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 #define BITSTREAM_READER_LE
29 #include "libavutil/audioconvert.h"
30 #include "libavutil/mem.h"
31 #include "libavutil/opt.h"
32 #include "avcodec.h"
33 #include "get_bits.h"
34 #include "acelp_vectors.h"
35 #include "celp_filters.h"
36 #include "g723_1_data.h"
37
38 #define CNG_RANDOM_SEED 12345
39
40 /**
41  * G723.1 frame types
42  */
43 enum FrameType {
44     ACTIVE_FRAME,        ///< Active speech
45     SID_FRAME,           ///< Silence Insertion Descriptor frame
46     UNTRANSMITTED_FRAME
47 };
48
49 enum Rate {
50     RATE_6300,
51     RATE_5300
52 };
53
54 /**
55  * G723.1 unpacked data subframe
56  */
57 typedef struct {
58     int ad_cb_lag;     ///< adaptive codebook lag
59     int ad_cb_gain;
60     int dirac_train;
61     int pulse_sign;
62     int grid_index;
63     int amp_index;
64     int pulse_pos;
65 } G723_1_Subframe;
66
67 /**
68  * Pitch postfilter parameters
69  */
70 typedef struct {
71     int     index;    ///< postfilter backward/forward lag
72     int16_t opt_gain; ///< optimal gain
73     int16_t sc_gain;  ///< scaling gain
74 } PPFParam;
75
76 typedef struct g723_1_context {
77     AVClass *class;
78     AVFrame frame;
79
80     G723_1_Subframe subframe[4];
81     enum FrameType cur_frame_type;
82     enum FrameType past_frame_type;
83     enum Rate cur_rate;
84     uint8_t lsp_index[LSP_BANDS];
85     int pitch_lag[2];
86     int erased_frames;
87
88     int16_t prev_lsp[LPC_ORDER];
89     int16_t sid_lsp[LPC_ORDER];
90     int16_t prev_excitation[PITCH_MAX];
91     int16_t excitation[PITCH_MAX + FRAME_LEN + 4];
92     int16_t synth_mem[LPC_ORDER];
93     int16_t fir_mem[LPC_ORDER];
94     int     iir_mem[LPC_ORDER];
95
96     int random_seed;
97     int cng_random_seed;
98     int interp_index;
99     int interp_gain;
100     int sid_gain;
101     int cur_gain;
102     int reflection_coef;
103     int pf_gain;
104     int postfilter;
105
106     int16_t audio[FRAME_LEN + LPC_ORDER + PITCH_MAX + 4];
107 } G723_1_Context;
108
109 static av_cold int g723_1_decode_init(AVCodecContext *avctx)
110 {
111     G723_1_Context *p = avctx->priv_data;
112
113     avctx->channel_layout = AV_CH_LAYOUT_MONO;
114     avctx->sample_fmt     = AV_SAMPLE_FMT_S16;
115     avctx->channels       = 1;
116     avctx->sample_rate    = 8000;
117     p->pf_gain            = 1 << 12;
118
119     avcodec_get_frame_defaults(&p->frame);
120     avctx->coded_frame    = &p->frame;
121
122     memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
123     memcpy(p->sid_lsp,  dc_lsp, LPC_ORDER * sizeof(*p->sid_lsp));
124
125     p->cng_random_seed = CNG_RANDOM_SEED;
126     p->past_frame_type = SID_FRAME;
127
128     return 0;
129 }
130
131 /**
132  * Unpack the frame into parameters.
133  *
134  * @param p           the context
135  * @param buf         pointer to the input buffer
136  * @param buf_size    size of the input buffer
137  */
138 static int unpack_bitstream(G723_1_Context *p, const uint8_t *buf,
139                             int buf_size)
140 {
141     GetBitContext gb;
142     int ad_cb_len;
143     int temp, info_bits, i;
144
145     init_get_bits(&gb, buf, buf_size * 8);
146
147     /* Extract frame type and rate info */
148     info_bits = get_bits(&gb, 2);
149
150     if (info_bits == 3) {
151         p->cur_frame_type = UNTRANSMITTED_FRAME;
152         return 0;
153     }
154
155     /* Extract 24 bit lsp indices, 8 bit for each band */
156     p->lsp_index[2] = get_bits(&gb, 8);
157     p->lsp_index[1] = get_bits(&gb, 8);
158     p->lsp_index[0] = get_bits(&gb, 8);
159
160     if (info_bits == 2) {
161         p->cur_frame_type = SID_FRAME;
162         p->subframe[0].amp_index = get_bits(&gb, 6);
163         return 0;
164     }
165
166     /* Extract the info common to both rates */
167     p->cur_rate       = info_bits ? RATE_5300 : RATE_6300;
168     p->cur_frame_type = ACTIVE_FRAME;
169
170     p->pitch_lag[0] = get_bits(&gb, 7);
171     if (p->pitch_lag[0] > 123)       /* test if forbidden code */
172         return -1;
173     p->pitch_lag[0] += PITCH_MIN;
174     p->subframe[1].ad_cb_lag = get_bits(&gb, 2);
175
176     p->pitch_lag[1] = get_bits(&gb, 7);
177     if (p->pitch_lag[1] > 123)
178         return -1;
179     p->pitch_lag[1] += PITCH_MIN;
180     p->subframe[3].ad_cb_lag = get_bits(&gb, 2);
181     p->subframe[0].ad_cb_lag = 1;
182     p->subframe[2].ad_cb_lag = 1;
183
184     for (i = 0; i < SUBFRAMES; i++) {
185         /* Extract combined gain */
186         temp = get_bits(&gb, 12);
187         ad_cb_len = 170;
188         p->subframe[i].dirac_train = 0;
189         if (p->cur_rate == RATE_6300 && p->pitch_lag[i >> 1] < SUBFRAME_LEN - 2) {
190             p->subframe[i].dirac_train = temp >> 11;
191             temp &= 0x7FF;
192             ad_cb_len = 85;
193         }
194         p->subframe[i].ad_cb_gain = FASTDIV(temp, GAIN_LEVELS);
195         if (p->subframe[i].ad_cb_gain < ad_cb_len) {
196             p->subframe[i].amp_index = temp - p->subframe[i].ad_cb_gain *
197                                        GAIN_LEVELS;
198         } else {
199             return -1;
200         }
201     }
202
203     p->subframe[0].grid_index = get_bits(&gb, 1);
204     p->subframe[1].grid_index = get_bits(&gb, 1);
205     p->subframe[2].grid_index = get_bits(&gb, 1);
206     p->subframe[3].grid_index = get_bits(&gb, 1);
207
208     if (p->cur_rate == RATE_6300) {
209         skip_bits(&gb, 1);  /* skip reserved bit */
210
211         /* Compute pulse_pos index using the 13-bit combined position index */
212         temp = get_bits(&gb, 13);
213         p->subframe[0].pulse_pos = temp / 810;
214
215         temp -= p->subframe[0].pulse_pos * 810;
216         p->subframe[1].pulse_pos = FASTDIV(temp, 90);
217
218         temp -= p->subframe[1].pulse_pos * 90;
219         p->subframe[2].pulse_pos = FASTDIV(temp, 9);
220         p->subframe[3].pulse_pos = temp - p->subframe[2].pulse_pos * 9;
221
222         p->subframe[0].pulse_pos = (p->subframe[0].pulse_pos << 16) +
223                                    get_bits(&gb, 16);
224         p->subframe[1].pulse_pos = (p->subframe[1].pulse_pos << 14) +
225                                    get_bits(&gb, 14);
226         p->subframe[2].pulse_pos = (p->subframe[2].pulse_pos << 16) +
227                                    get_bits(&gb, 16);
228         p->subframe[3].pulse_pos = (p->subframe[3].pulse_pos << 14) +
229                                    get_bits(&gb, 14);
230
231         p->subframe[0].pulse_sign = get_bits(&gb, 6);
232         p->subframe[1].pulse_sign = get_bits(&gb, 5);
233         p->subframe[2].pulse_sign = get_bits(&gb, 6);
234         p->subframe[3].pulse_sign = get_bits(&gb, 5);
235     } else { /* 5300 bps */
236         p->subframe[0].pulse_pos  = get_bits(&gb, 12);
237         p->subframe[1].pulse_pos  = get_bits(&gb, 12);
238         p->subframe[2].pulse_pos  = get_bits(&gb, 12);
239         p->subframe[3].pulse_pos  = get_bits(&gb, 12);
240
241         p->subframe[0].pulse_sign = get_bits(&gb, 4);
242         p->subframe[1].pulse_sign = get_bits(&gb, 4);
243         p->subframe[2].pulse_sign = get_bits(&gb, 4);
244         p->subframe[3].pulse_sign = get_bits(&gb, 4);
245     }
246
247     return 0;
248 }
249
250 /**
251  * Bitexact implementation of sqrt(val/2).
252  */
253 static int16_t square_root(int val)
254 {
255     int16_t res = 0;
256     int16_t exp = 0x4000;
257     int i;
258
259     for (i = 0; i < 14; i ++) {
260         int res_exp = res + exp;
261         if (val >= res_exp * res_exp << 1)
262             res += exp;
263         exp >>= 1;
264     }
265     return res;
266 }
267
268 /**
269  * Calculate the number of left-shifts required for normalizing the input.
270  *
271  * @param num   input number
272  * @param width width of the input, 16 bits(0) / 32 bits(1)
273  */
274 static int normalize_bits(int num, int width)
275 {
276     return width - av_log2(num) - 1;
277 }
278
279 /**
280  * Scale vector contents based on the largest of their absolutes.
281  */
282 static int scale_vector(int16_t *dst, const int16_t *vector, int length)
283 {
284     int bits, max = 0;
285     int i;
286
287
288     for (i = 0; i < length; i++)
289         max |= FFABS(vector[i]);
290
291     max   = FFMIN(max, 0x7FFF);
292     bits  = normalize_bits(max, 15);
293
294     for (i = 0; i < length; i++)
295         dst[i] = vector[i] << bits >> 3;
296
297     return bits - 3;
298 }
299
300 /**
301  * Perform inverse quantization of LSP frequencies.
302  *
303  * @param cur_lsp    the current LSP vector
304  * @param prev_lsp   the previous LSP vector
305  * @param lsp_index  VQ indices
306  * @param bad_frame  bad frame flag
307  */
308 static void inverse_quant(int16_t *cur_lsp, int16_t *prev_lsp,
309                           uint8_t *lsp_index, int bad_frame)
310 {
311     int min_dist, pred;
312     int i, j, temp, stable;
313
314     /* Check for frame erasure */
315     if (!bad_frame) {
316         min_dist     = 0x100;
317         pred         = 12288;
318     } else {
319         min_dist     = 0x200;
320         pred         = 23552;
321         lsp_index[0] = lsp_index[1] = lsp_index[2] = 0;
322     }
323
324     /* Get the VQ table entry corresponding to the transmitted index */
325     cur_lsp[0] = lsp_band0[lsp_index[0]][0];
326     cur_lsp[1] = lsp_band0[lsp_index[0]][1];
327     cur_lsp[2] = lsp_band0[lsp_index[0]][2];
328     cur_lsp[3] = lsp_band1[lsp_index[1]][0];
329     cur_lsp[4] = lsp_band1[lsp_index[1]][1];
330     cur_lsp[5] = lsp_band1[lsp_index[1]][2];
331     cur_lsp[6] = lsp_band2[lsp_index[2]][0];
332     cur_lsp[7] = lsp_band2[lsp_index[2]][1];
333     cur_lsp[8] = lsp_band2[lsp_index[2]][2];
334     cur_lsp[9] = lsp_band2[lsp_index[2]][3];
335
336     /* Add predicted vector & DC component to the previously quantized vector */
337     for (i = 0; i < LPC_ORDER; i++) {
338         temp        = ((prev_lsp[i] - dc_lsp[i]) * pred + (1 << 14)) >> 15;
339         cur_lsp[i] += dc_lsp[i] + temp;
340     }
341
342     for (i = 0; i < LPC_ORDER; i++) {
343         cur_lsp[0]             = FFMAX(cur_lsp[0],  0x180);
344         cur_lsp[LPC_ORDER - 1] = FFMIN(cur_lsp[LPC_ORDER - 1], 0x7e00);
345
346         /* Stability check */
347         for (j = 1; j < LPC_ORDER; j++) {
348             temp = min_dist + cur_lsp[j - 1] - cur_lsp[j];
349             if (temp > 0) {
350                 temp >>= 1;
351                 cur_lsp[j - 1] -= temp;
352                 cur_lsp[j]     += temp;
353             }
354         }
355         stable = 1;
356         for (j = 1; j < LPC_ORDER; j++) {
357             temp = cur_lsp[j - 1] + min_dist - cur_lsp[j] - 4;
358             if (temp > 0) {
359                 stable = 0;
360                 break;
361             }
362         }
363         if (stable)
364             break;
365     }
366     if (!stable)
367         memcpy(cur_lsp, prev_lsp, LPC_ORDER * sizeof(*cur_lsp));
368 }
369
370 /**
371  * Bitexact implementation of 2ab scaled by 1/2^16.
372  *
373  * @param a 32 bit multiplicand
374  * @param b 16 bit multiplier
375  */
376 #define MULL2(a, b) \
377         ((((a) >> 16) * (b) << 1) + (((a) & 0xffff) * (b) >> 15))
378
379 /**
380  * Convert LSP frequencies to LPC coefficients.
381  *
382  * @param lpc buffer for LPC coefficients
383  */
384 static void lsp2lpc(int16_t *lpc)
385 {
386     int f1[LPC_ORDER / 2 + 1];
387     int f2[LPC_ORDER / 2 + 1];
388     int i, j;
389
390     /* Calculate negative cosine */
391     for (j = 0; j < LPC_ORDER; j++) {
392         int index     = lpc[j] >> 7;
393         int offset    = lpc[j] & 0x7f;
394         int temp1     = cos_tab[index] << 16;
395         int temp2     = (cos_tab[index + 1] - cos_tab[index]) *
396                           ((offset << 8) + 0x80) << 1;
397
398         lpc[j] = -(av_sat_dadd32(1 << 15, temp1 + temp2) >> 16);
399     }
400
401     /*
402      * Compute sum and difference polynomial coefficients
403      * (bitexact alternative to lsp2poly() in lsp.c)
404      */
405     /* Initialize with values in Q28 */
406     f1[0] = 1 << 28;
407     f1[1] = (lpc[0] << 14) + (lpc[2] << 14);
408     f1[2] = lpc[0] * lpc[2] + (2 << 28);
409
410     f2[0] = 1 << 28;
411     f2[1] = (lpc[1] << 14) + (lpc[3] << 14);
412     f2[2] = lpc[1] * lpc[3] + (2 << 28);
413
414     /*
415      * Calculate and scale the coefficients by 1/2 in
416      * each iteration for a final scaling factor of Q25
417      */
418     for (i = 2; i < LPC_ORDER / 2; i++) {
419         f1[i + 1] = f1[i - 1] + MULL2(f1[i], lpc[2 * i]);
420         f2[i + 1] = f2[i - 1] + MULL2(f2[i], lpc[2 * i + 1]);
421
422         for (j = i; j >= 2; j--) {
423             f1[j] = MULL2(f1[j - 1], lpc[2 * i]) +
424                     (f1[j] >> 1) + (f1[j - 2] >> 1);
425             f2[j] = MULL2(f2[j - 1], lpc[2 * i + 1]) +
426                     (f2[j] >> 1) + (f2[j - 2] >> 1);
427         }
428
429         f1[0] >>= 1;
430         f2[0] >>= 1;
431         f1[1] = ((lpc[2 * i]     << 16 >> i) + f1[1]) >> 1;
432         f2[1] = ((lpc[2 * i + 1] << 16 >> i) + f2[1]) >> 1;
433     }
434
435     /* Convert polynomial coefficients to LPC coefficients */
436     for (i = 0; i < LPC_ORDER / 2; i++) {
437         int64_t ff1 = f1[i + 1] + f1[i];
438         int64_t ff2 = f2[i + 1] - f2[i];
439
440         lpc[i] = av_clipl_int32(((ff1 + ff2) << 3) + (1 << 15)) >> 16;
441         lpc[LPC_ORDER - i - 1] = av_clipl_int32(((ff1 - ff2) << 3) +
442                                                 (1 << 15)) >> 16;
443     }
444 }
445
446 /**
447  * Quantize LSP frequencies by interpolation and convert them to
448  * the corresponding LPC coefficients.
449  *
450  * @param lpc      buffer for LPC coefficients
451  * @param cur_lsp  the current LSP vector
452  * @param prev_lsp the previous LSP vector
453  */
454 static void lsp_interpolate(int16_t *lpc, int16_t *cur_lsp, int16_t *prev_lsp)
455 {
456     int i;
457     int16_t *lpc_ptr = lpc;
458
459     /* cur_lsp * 0.25 + prev_lsp * 0.75 */
460     ff_acelp_weighted_vector_sum(lpc, cur_lsp, prev_lsp,
461                                  4096, 12288, 1 << 13, 14, LPC_ORDER);
462     ff_acelp_weighted_vector_sum(lpc + LPC_ORDER, cur_lsp, prev_lsp,
463                                  8192, 8192, 1 << 13, 14, LPC_ORDER);
464     ff_acelp_weighted_vector_sum(lpc + 2 * LPC_ORDER, cur_lsp, prev_lsp,
465                                  12288, 4096, 1 << 13, 14, LPC_ORDER);
466     memcpy(lpc + 3 * LPC_ORDER, cur_lsp, LPC_ORDER * sizeof(*lpc));
467
468     for (i = 0; i < SUBFRAMES; i++) {
469         lsp2lpc(lpc_ptr);
470         lpc_ptr += LPC_ORDER;
471     }
472 }
473
474 /**
475  * Generate a train of dirac functions with period as pitch lag.
476  */
477 static void gen_dirac_train(int16_t *buf, int pitch_lag)
478 {
479     int16_t vector[SUBFRAME_LEN];
480     int i, j;
481
482     memcpy(vector, buf, SUBFRAME_LEN * sizeof(*vector));
483     for (i = pitch_lag; i < SUBFRAME_LEN; i += pitch_lag) {
484         for (j = 0; j < SUBFRAME_LEN - i; j++)
485             buf[i + j] += vector[j];
486     }
487 }
488
489 /**
490  * Generate fixed codebook excitation vector.
491  *
492  * @param vector    decoded excitation vector
493  * @param subfrm    current subframe
494  * @param cur_rate  current bitrate
495  * @param pitch_lag closed loop pitch lag
496  * @param index     current subframe index
497  */
498 static void gen_fcb_excitation(int16_t *vector, G723_1_Subframe *subfrm,
499                                enum Rate cur_rate, int pitch_lag, int index)
500 {
501     int temp, i, j;
502
503     memset(vector, 0, SUBFRAME_LEN * sizeof(*vector));
504
505     if (cur_rate == RATE_6300) {
506         if (subfrm->pulse_pos >= max_pos[index])
507             return;
508
509         /* Decode amplitudes and positions */
510         j = PULSE_MAX - pulses[index];
511         temp = subfrm->pulse_pos;
512         for (i = 0; i < SUBFRAME_LEN / GRID_SIZE; i++) {
513             temp -= combinatorial_table[j][i];
514             if (temp >= 0)
515                 continue;
516             temp += combinatorial_table[j++][i];
517             if (subfrm->pulse_sign & (1 << (PULSE_MAX - j))) {
518                 vector[subfrm->grid_index + GRID_SIZE * i] =
519                                         -fixed_cb_gain[subfrm->amp_index];
520             } else {
521                 vector[subfrm->grid_index + GRID_SIZE * i] =
522                                          fixed_cb_gain[subfrm->amp_index];
523             }
524             if (j == PULSE_MAX)
525                 break;
526         }
527         if (subfrm->dirac_train == 1)
528             gen_dirac_train(vector, pitch_lag);
529     } else { /* 5300 bps */
530         int cb_gain  = fixed_cb_gain[subfrm->amp_index];
531         int cb_shift = subfrm->grid_index;
532         int cb_sign  = subfrm->pulse_sign;
533         int cb_pos   = subfrm->pulse_pos;
534         int offset, beta, lag;
535
536         for (i = 0; i < 8; i += 2) {
537             offset         = ((cb_pos & 7) << 3) + cb_shift + i;
538             vector[offset] = (cb_sign & 1) ? cb_gain : -cb_gain;
539             cb_pos  >>= 3;
540             cb_sign >>= 1;
541         }
542
543         /* Enhance harmonic components */
544         lag  = pitch_contrib[subfrm->ad_cb_gain << 1] + pitch_lag +
545                subfrm->ad_cb_lag - 1;
546         beta = pitch_contrib[(subfrm->ad_cb_gain << 1) + 1];
547
548         if (lag < SUBFRAME_LEN - 2) {
549             for (i = lag; i < SUBFRAME_LEN; i++)
550                 vector[i] += beta * vector[i - lag] >> 15;
551         }
552     }
553 }
554
555 /**
556  * Get delayed contribution from the previous excitation vector.
557  */
558 static void get_residual(int16_t *residual, int16_t *prev_excitation, int lag)
559 {
560     int offset = PITCH_MAX - PITCH_ORDER / 2 - lag;
561     int i;
562
563     residual[0] = prev_excitation[offset];
564     residual[1] = prev_excitation[offset + 1];
565
566     offset += 2;
567     for (i = 2; i < SUBFRAME_LEN + PITCH_ORDER - 1; i++)
568         residual[i] = prev_excitation[offset + (i - 2) % lag];
569 }
570
571 static int dot_product(const int16_t *a, const int16_t *b, int length)
572 {
573     int i, sum = 0;
574
575     for (i = 0; i < length; i++) {
576         int prod = a[i] * b[i];
577         sum = av_sat_dadd32(sum, prod);
578     }
579     return sum;
580 }
581
582 /**
583  * Generate adaptive codebook excitation.
584  */
585 static void gen_acb_excitation(int16_t *vector, int16_t *prev_excitation,
586                                int pitch_lag, G723_1_Subframe *subfrm,
587                                enum Rate cur_rate)
588 {
589     int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
590     const int16_t *cb_ptr;
591     int lag = pitch_lag + subfrm->ad_cb_lag - 1;
592
593     int i;
594     int sum;
595
596     get_residual(residual, prev_excitation, lag);
597
598     /* Select quantization table */
599     if (cur_rate == RATE_6300 && pitch_lag < SUBFRAME_LEN - 2)
600         cb_ptr = adaptive_cb_gain85;
601     else
602         cb_ptr = adaptive_cb_gain170;
603
604     /* Calculate adaptive vector */
605     cb_ptr += subfrm->ad_cb_gain * 20;
606     for (i = 0; i < SUBFRAME_LEN; i++) {
607         sum = dot_product(residual + i, cb_ptr, PITCH_ORDER);
608         vector[i] = av_sat_dadd32(1 << 15, sum) >> 16;
609     }
610 }
611
612 /**
613  * Estimate maximum auto-correlation around pitch lag.
614  *
615  * @param buf       buffer with offset applied
616  * @param offset    offset of the excitation vector
617  * @param ccr_max   pointer to the maximum auto-correlation
618  * @param pitch_lag decoded pitch lag
619  * @param length    length of autocorrelation
620  * @param dir       forward lag(1) / backward lag(-1)
621  */
622 static int autocorr_max(const int16_t *buf, int offset, int *ccr_max,
623                         int pitch_lag, int length, int dir)
624 {
625     int limit, ccr, lag = 0;
626     int i;
627
628     pitch_lag = FFMIN(PITCH_MAX - 3, pitch_lag);
629     if (dir > 0)
630         limit = FFMIN(FRAME_LEN + PITCH_MAX - offset - length, pitch_lag + 3);
631     else
632         limit = pitch_lag + 3;
633
634     for (i = pitch_lag - 3; i <= limit; i++) {
635         ccr = dot_product(buf, buf + dir * i, length);
636
637         if (ccr > *ccr_max) {
638             *ccr_max = ccr;
639             lag = i;
640         }
641     }
642     return lag;
643 }
644
645 /**
646  * Calculate pitch postfilter optimal and scaling gains.
647  *
648  * @param lag      pitch postfilter forward/backward lag
649  * @param ppf      pitch postfilter parameters
650  * @param cur_rate current bitrate
651  * @param tgt_eng  target energy
652  * @param ccr      cross-correlation
653  * @param res_eng  residual energy
654  */
655 static void comp_ppf_gains(int lag, PPFParam *ppf, enum Rate cur_rate,
656                            int tgt_eng, int ccr, int res_eng)
657 {
658     int pf_residual;     /* square of postfiltered residual */
659     int temp1, temp2;
660
661     ppf->index = lag;
662
663     temp1 = tgt_eng * res_eng >> 1;
664     temp2 = ccr * ccr << 1;
665
666     if (temp2 > temp1) {
667         if (ccr >= res_eng) {
668             ppf->opt_gain = ppf_gain_weight[cur_rate];
669         } else {
670             ppf->opt_gain = (ccr << 15) / res_eng *
671                             ppf_gain_weight[cur_rate] >> 15;
672         }
673         /* pf_res^2 = tgt_eng + 2*ccr*gain + res_eng*gain^2 */
674         temp1       = (tgt_eng << 15) + (ccr * ppf->opt_gain << 1);
675         temp2       = (ppf->opt_gain * ppf->opt_gain >> 15) * res_eng;
676         pf_residual = av_sat_add32(temp1, temp2 + (1 << 15)) >> 16;
677
678         if (tgt_eng >= pf_residual << 1) {
679             temp1 = 0x7fff;
680         } else {
681             temp1 = (tgt_eng << 14) / pf_residual;
682         }
683
684         /* scaling_gain = sqrt(tgt_eng/pf_res^2) */
685         ppf->sc_gain = square_root(temp1 << 16);
686     } else {
687         ppf->opt_gain = 0;
688         ppf->sc_gain  = 0x7fff;
689     }
690
691     ppf->opt_gain = av_clip_int16(ppf->opt_gain * ppf->sc_gain >> 15);
692 }
693
694 /**
695  * Calculate pitch postfilter parameters.
696  *
697  * @param p         the context
698  * @param offset    offset of the excitation vector
699  * @param pitch_lag decoded pitch lag
700  * @param ppf       pitch postfilter parameters
701  * @param cur_rate  current bitrate
702  */
703 static void comp_ppf_coeff(G723_1_Context *p, int offset, int pitch_lag,
704                            PPFParam *ppf, enum Rate cur_rate)
705 {
706
707     int16_t scale;
708     int i;
709     int temp1, temp2;
710
711     /*
712      * 0 - target energy
713      * 1 - forward cross-correlation
714      * 2 - forward residual energy
715      * 3 - backward cross-correlation
716      * 4 - backward residual energy
717      */
718     int energy[5] = {0, 0, 0, 0, 0};
719     int16_t *buf  = p->audio + LPC_ORDER + offset;
720     int fwd_lag   = autocorr_max(buf, offset, &energy[1], pitch_lag,
721                                  SUBFRAME_LEN, 1);
722     int back_lag  = autocorr_max(buf, offset, &energy[3], pitch_lag,
723                                  SUBFRAME_LEN, -1);
724
725     ppf->index    = 0;
726     ppf->opt_gain = 0;
727     ppf->sc_gain  = 0x7fff;
728
729     /* Case 0, Section 3.6 */
730     if (!back_lag && !fwd_lag)
731         return;
732
733     /* Compute target energy */
734     energy[0] = dot_product(buf, buf, SUBFRAME_LEN);
735
736     /* Compute forward residual energy */
737     if (fwd_lag)
738         energy[2] = dot_product(buf + fwd_lag, buf + fwd_lag, SUBFRAME_LEN);
739
740     /* Compute backward residual energy */
741     if (back_lag)
742         energy[4] = dot_product(buf - back_lag, buf - back_lag, SUBFRAME_LEN);
743
744     /* Normalize and shorten */
745     temp1 = 0;
746     for (i = 0; i < 5; i++)
747         temp1 = FFMAX(energy[i], temp1);
748
749     scale = normalize_bits(temp1, 31);
750     for (i = 0; i < 5; i++)
751         energy[i] = (energy[i] << scale) >> 16;
752
753     if (fwd_lag && !back_lag) {  /* Case 1 */
754         comp_ppf_gains(fwd_lag,  ppf, cur_rate, energy[0], energy[1],
755                        energy[2]);
756     } else if (!fwd_lag) {       /* Case 2 */
757         comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
758                        energy[4]);
759     } else {                     /* Case 3 */
760
761         /*
762          * Select the largest of energy[1]^2/energy[2]
763          * and energy[3]^2/energy[4]
764          */
765         temp1 = energy[4] * ((energy[1] * energy[1] + (1 << 14)) >> 15);
766         temp2 = energy[2] * ((energy[3] * energy[3] + (1 << 14)) >> 15);
767         if (temp1 >= temp2) {
768             comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
769                            energy[2]);
770         } else {
771             comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
772                            energy[4]);
773         }
774     }
775 }
776
777 /**
778  * Classify frames as voiced/unvoiced.
779  *
780  * @param p         the context
781  * @param pitch_lag decoded pitch_lag
782  * @param exc_eng   excitation energy estimation
783  * @param scale     scaling factor of exc_eng
784  *
785  * @return residual interpolation index if voiced, 0 otherwise
786  */
787 static int comp_interp_index(G723_1_Context *p, int pitch_lag,
788                              int *exc_eng, int *scale)
789 {
790     int offset = PITCH_MAX + 2 * SUBFRAME_LEN;
791     int16_t *buf = p->audio + LPC_ORDER;
792
793     int index, ccr, tgt_eng, best_eng, temp;
794
795     *scale = scale_vector(buf, p->excitation, FRAME_LEN + PITCH_MAX);
796     buf   += offset;
797
798     /* Compute maximum backward cross-correlation */
799     ccr   = 0;
800     index = autocorr_max(buf, offset, &ccr, pitch_lag, SUBFRAME_LEN * 2, -1);
801     ccr   = av_sat_add32(ccr, 1 << 15) >> 16;
802
803     /* Compute target energy */
804     tgt_eng  = dot_product(buf, buf, SUBFRAME_LEN * 2);
805     *exc_eng = av_sat_add32(tgt_eng, 1 << 15) >> 16;
806
807     if (ccr <= 0)
808         return 0;
809
810     /* Compute best energy */
811     best_eng = dot_product(buf - index, buf - index, SUBFRAME_LEN * 2);
812     best_eng = av_sat_add32(best_eng, 1 << 15) >> 16;
813
814     temp = best_eng * *exc_eng >> 3;
815
816     if (temp < ccr * ccr)
817         return index;
818     else
819         return 0;
820 }
821
822 /**
823  * Peform residual interpolation based on frame classification.
824  *
825  * @param buf   decoded excitation vector
826  * @param out   output vector
827  * @param lag   decoded pitch lag
828  * @param gain  interpolated gain
829  * @param rseed seed for random number generator
830  */
831 static void residual_interp(int16_t *buf, int16_t *out, int lag,
832                             int gain, int *rseed)
833 {
834     int i;
835     if (lag) { /* Voiced */
836         int16_t *vector_ptr = buf + PITCH_MAX;
837         /* Attenuate */
838         for (i = 0; i < lag; i++)
839             out[i] = vector_ptr[i - lag] * 3 >> 2;
840         av_memcpy_backptr((uint8_t*)(out + lag), lag * sizeof(*out),
841                           (FRAME_LEN - lag) * sizeof(*out));
842     } else {  /* Unvoiced */
843         for (i = 0; i < FRAME_LEN; i++) {
844             *rseed = *rseed * 521 + 259;
845             out[i] = gain * *rseed >> 15;
846         }
847         memset(buf, 0, (FRAME_LEN + PITCH_MAX) * sizeof(*buf));
848     }
849 }
850
851 /**
852  * Perform IIR filtering.
853  *
854  * @param fir_coef FIR coefficients
855  * @param iir_coef IIR coefficients
856  * @param src      source vector
857  * @param dest     destination vector
858  */
859 static inline void iir_filter(int16_t *fir_coef, int16_t *iir_coef,
860                               int16_t *src, int *dest)
861 {
862     int m, n;
863
864     for (m = 0; m < SUBFRAME_LEN; m++) {
865         int64_t filter = 0;
866         for (n = 1; n <= LPC_ORDER; n++) {
867             filter -= fir_coef[n - 1] * src[m - n] -
868                       iir_coef[n - 1] * (dest[m - n] >> 16);
869         }
870
871         dest[m] = av_clipl_int32((src[m] << 16) + (filter << 3) + (1 << 15));
872     }
873 }
874
875 /**
876  * Adjust gain of postfiltered signal.
877  *
878  * @param p      the context
879  * @param buf    postfiltered output vector
880  * @param energy input energy coefficient
881  */
882 static void gain_scale(G723_1_Context *p, int16_t * buf, int energy)
883 {
884     int num, denom, gain, bits1, bits2;
885     int i;
886
887     num   = energy;
888     denom = 0;
889     for (i = 0; i < SUBFRAME_LEN; i++) {
890         int temp = buf[i] >> 2;
891         temp *= temp;
892         denom = av_sat_dadd32(denom, temp);
893     }
894
895     if (num && denom) {
896         bits1   = normalize_bits(num,   31);
897         bits2   = normalize_bits(denom, 31);
898         num     = num << bits1 >> 1;
899         denom <<= bits2;
900
901         bits2 = 5 + bits1 - bits2;
902         bits2 = FFMAX(0, bits2);
903
904         gain = (num >> 1) / (denom >> 16);
905         gain = square_root(gain << 16 >> bits2);
906     } else {
907         gain = 1 << 12;
908     }
909
910     for (i = 0; i < SUBFRAME_LEN; i++) {
911         p->pf_gain = (15 * p->pf_gain + gain + (1 << 3)) >> 4;
912         buf[i]     = av_clip_int16((buf[i] * (p->pf_gain + (p->pf_gain >> 4)) +
913                                    (1 << 10)) >> 11);
914     }
915 }
916
917 /**
918  * Perform formant filtering.
919  *
920  * @param p   the context
921  * @param lpc quantized lpc coefficients
922  * @param buf input buffer
923  * @param dst output buffer
924  */
925 static void formant_postfilter(G723_1_Context *p, int16_t *lpc,
926                                int16_t *buf, int16_t *dst)
927 {
928     int16_t filter_coef[2][LPC_ORDER];
929     int filter_signal[LPC_ORDER + FRAME_LEN], *signal_ptr;
930     int i, j, k;
931
932     memcpy(buf, p->fir_mem, LPC_ORDER * sizeof(*buf));
933     memcpy(filter_signal, p->iir_mem, LPC_ORDER * sizeof(*filter_signal));
934
935     for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
936         for (k = 0; k < LPC_ORDER; k++) {
937             filter_coef[0][k] = (-lpc[k] * postfilter_tbl[0][k] +
938                                  (1 << 14)) >> 15;
939             filter_coef[1][k] = (-lpc[k] * postfilter_tbl[1][k] +
940                                  (1 << 14)) >> 15;
941         }
942         iir_filter(filter_coef[0], filter_coef[1], buf + i,
943                    filter_signal + i);
944         lpc += LPC_ORDER;
945     }
946
947     memcpy(p->fir_mem, buf + FRAME_LEN, LPC_ORDER * sizeof(*p->fir_mem));
948     memcpy(p->iir_mem, filter_signal + FRAME_LEN,
949            LPC_ORDER * sizeof(*p->iir_mem));
950
951     buf += LPC_ORDER;
952     signal_ptr = filter_signal + LPC_ORDER;
953     for (i = 0; i < SUBFRAMES; i++) {
954         int temp;
955         int auto_corr[2];
956         int scale, energy;
957
958         /* Normalize */
959         scale = scale_vector(dst, buf, SUBFRAME_LEN);
960
961         /* Compute auto correlation coefficients */
962         auto_corr[0] = dot_product(dst, dst + 1, SUBFRAME_LEN - 1);
963         auto_corr[1] = dot_product(dst, dst,     SUBFRAME_LEN);
964
965         /* Compute reflection coefficient */
966         temp = auto_corr[1] >> 16;
967         if (temp) {
968             temp = (auto_corr[0] >> 2) / temp;
969         }
970         p->reflection_coef = (3 * p->reflection_coef + temp + 2) >> 2;
971         temp = -p->reflection_coef >> 1 & ~3;
972
973         /* Compensation filter */
974         for (j = 0; j < SUBFRAME_LEN; j++) {
975             dst[j] = av_sat_dadd32(signal_ptr[j],
976                                    (signal_ptr[j - 1] >> 16) * temp) >> 16;
977         }
978
979         /* Compute normalized signal energy */
980         temp = 2 * scale + 4;
981         if (temp < 0) {
982             energy = av_clipl_int32((int64_t)auto_corr[1] << -temp);
983         } else
984             energy = auto_corr[1] >> temp;
985
986         gain_scale(p, dst, energy);
987
988         buf        += SUBFRAME_LEN;
989         signal_ptr += SUBFRAME_LEN;
990         dst        += SUBFRAME_LEN;
991     }
992 }
993
994 static int sid_gain_to_lsp_index(int gain)
995 {
996     if (gain < 0x10)
997         return gain << 6;
998     else if (gain < 0x20)
999         return gain - 8 << 7;
1000     else
1001         return gain - 20 << 8;
1002 }
1003
1004 static inline int cng_rand(int *state, int base)
1005 {
1006     *state = (*state * 521 + 259) & 0xFFFF;
1007     return (*state & 0x7FFF) * base >> 15;
1008 }
1009
1010 static int estimate_sid_gain(G723_1_Context *p)
1011 {
1012     int i, shift, seg, seg2, t, val, val_add, x, y;
1013
1014     shift = 16 - p->cur_gain * 2;
1015     if (shift > 0)
1016         t = p->sid_gain << shift;
1017     else
1018         t = p->sid_gain >> -shift;
1019     x = t * cng_filt[0] >> 16;
1020
1021     if (x >= cng_bseg[2])
1022         return 0x3F;
1023
1024     if (x >= cng_bseg[1]) {
1025         shift = 4;
1026         seg   = 3;
1027     } else {
1028         shift = 3;
1029         seg   = (x >= cng_bseg[0]);
1030     }
1031     seg2 = FFMIN(seg, 3);
1032
1033     val     = 1 << shift;
1034     val_add = val >> 1;
1035     for (i = 0; i < shift; i++) {
1036         t = seg * 32 + (val << seg2);
1037         t *= t;
1038         if (x >= t)
1039             val += val_add;
1040         else
1041             val -= val_add;
1042         val_add >>= 1;
1043     }
1044
1045     t = seg * 32 + (val << seg2);
1046     y = t * t - x;
1047     if (y <= 0) {
1048         t = seg * 32 + (val + 1 << seg2);
1049         t = t * t - x;
1050         val = (seg2 - 1 << 4) + val;
1051         if (t >= y)
1052             val++;
1053     } else {
1054         t = seg * 32 + (val - 1 << seg2);
1055         t = t * t - x;
1056         val = (seg2 - 1 << 4) + val;
1057         if (t >= y)
1058             val--;
1059     }
1060
1061     return val;
1062 }
1063
1064 static void generate_noise(G723_1_Context *p)
1065 {
1066     int i, j, idx, t;
1067     int off[SUBFRAMES];
1068     int signs[SUBFRAMES / 2 * 11], pos[SUBFRAMES / 2 * 11];
1069     int tmp[SUBFRAME_LEN * 2];
1070     int16_t *vector_ptr;
1071     int64_t sum;
1072     int b0, c, delta, x, shift;
1073
1074     p->pitch_lag[0] = cng_rand(&p->cng_random_seed, 21) + 123;
1075     p->pitch_lag[1] = cng_rand(&p->cng_random_seed, 19) + 123;
1076
1077     for (i = 0; i < SUBFRAMES; i++) {
1078         p->subframe[i].ad_cb_gain = cng_rand(&p->cng_random_seed, 50) + 1;
1079         p->subframe[i].ad_cb_lag  = cng_adaptive_cb_lag[i];
1080     }
1081
1082     for (i = 0; i < SUBFRAMES / 2; i++) {
1083         t = cng_rand(&p->cng_random_seed, 1 << 13);
1084         off[i * 2]     =   t       & 1;
1085         off[i * 2 + 1] = ((t >> 1) & 1) + SUBFRAME_LEN;
1086         t >>= 2;
1087         for (j = 0; j < 11; j++) {
1088             signs[i * 11 + j] = (t & 1) * 2 - 1 << 14;
1089             t >>= 1;
1090         }
1091     }
1092
1093     idx = 0;
1094     for (i = 0; i < SUBFRAMES; i++) {
1095         for (j = 0; j < SUBFRAME_LEN / 2; j++)
1096             tmp[j] = j;
1097         t = SUBFRAME_LEN / 2;
1098         for (j = 0; j < pulses[i]; j++, idx++) {
1099             int idx2 = cng_rand(&p->cng_random_seed, t);
1100
1101             pos[idx]  = tmp[idx2] * 2 + off[i];
1102             tmp[idx2] = tmp[--t];
1103         }
1104     }
1105
1106     vector_ptr = p->audio + LPC_ORDER;
1107     memcpy(vector_ptr, p->prev_excitation,
1108            PITCH_MAX * sizeof(*p->excitation));
1109     for (i = 0; i < SUBFRAMES; i += 2) {
1110         gen_acb_excitation(vector_ptr, vector_ptr,
1111                            p->pitch_lag[i >> 1], &p->subframe[i],
1112                            p->cur_rate);
1113         gen_acb_excitation(vector_ptr + SUBFRAME_LEN,
1114                            vector_ptr + SUBFRAME_LEN,
1115                            p->pitch_lag[i >> 1], &p->subframe[i + 1],
1116                            p->cur_rate);
1117
1118         t = 0;
1119         for (j = 0; j < SUBFRAME_LEN * 2; j++)
1120             t |= FFABS(vector_ptr[j]);
1121         t = FFMIN(t, 0x7FFF);
1122         if (!t) {
1123             shift = 0;
1124         } else {
1125             shift = -10 + av_log2(t);
1126             if (shift < -2)
1127                 shift = -2;
1128         }
1129         sum = 0;
1130         if (shift < 0) {
1131            for (j = 0; j < SUBFRAME_LEN * 2; j++) {
1132                t      = vector_ptr[j] << -shift;
1133                sum   += t * t;
1134                tmp[j] = t;
1135            }
1136         } else {
1137            for (j = 0; j < SUBFRAME_LEN * 2; j++) {
1138                t      = vector_ptr[j] >> shift;
1139                sum   += t * t;
1140                tmp[j] = t;
1141            }
1142         }
1143
1144         b0 = 0;
1145         for (j = 0; j < 11; j++)
1146             b0 += tmp[pos[(i / 2) * 11 + j]] * signs[(i / 2) * 11 + j];
1147         b0 = b0 * 2 * 2979LL + (1 << 29) >> 30; // approximated division by 11
1148
1149         c = p->cur_gain * (p->cur_gain * SUBFRAME_LEN >> 5);
1150         if (shift * 2 + 3 >= 0)
1151             c >>= shift * 2 + 3;
1152         else
1153             c <<= -(shift * 2 + 3);
1154         c = (av_clipl_int32(sum << 1) - c) * 2979LL >> 15;
1155
1156         delta = b0 * b0 * 2 - c;
1157         if (delta <= 0) {
1158             x = -b0;
1159         } else {
1160             delta = square_root(delta);
1161             x     = delta - b0;
1162             t     = delta + b0;
1163             if (FFABS(t) < FFABS(x))
1164                 x = -t;
1165         }
1166         shift++;
1167         if (shift < 0)
1168            x >>= -shift;
1169         else
1170            x <<= shift;
1171         x = av_clip(x, -10000, 10000);
1172
1173         for (j = 0; j < 11; j++) {
1174             idx = (i / 2) * 11 + j;
1175             vector_ptr[pos[idx]] = av_clip_int16(vector_ptr[pos[idx]] +
1176                                                  (x * signs[idx] >> 15));
1177         }
1178
1179         /* copy decoded data to serve as a history for the next decoded subframes */
1180         memcpy(vector_ptr + PITCH_MAX, vector_ptr,
1181                sizeof(*vector_ptr) * SUBFRAME_LEN * 2);
1182         vector_ptr += SUBFRAME_LEN * 2;
1183     }
1184     /* Save the excitation for the next frame */
1185     memcpy(p->prev_excitation, p->audio + LPC_ORDER + FRAME_LEN,
1186            PITCH_MAX * sizeof(*p->excitation));
1187 }
1188
1189 static int g723_1_decode_frame(AVCodecContext *avctx, void *data,
1190                                int *got_frame_ptr, AVPacket *avpkt)
1191 {
1192     G723_1_Context *p  = avctx->priv_data;
1193     const uint8_t *buf = avpkt->data;
1194     int buf_size       = avpkt->size;
1195     int dec_mode       = buf[0] & 3;
1196
1197     PPFParam ppf[SUBFRAMES];
1198     int16_t cur_lsp[LPC_ORDER];
1199     int16_t lpc[SUBFRAMES * LPC_ORDER];
1200     int16_t acb_vector[SUBFRAME_LEN];
1201     int16_t *out;
1202     int bad_frame = 0, i, j, ret;
1203     int16_t *audio = p->audio;
1204
1205     if (buf_size < frame_size[dec_mode]) {
1206         if (buf_size)
1207             av_log(avctx, AV_LOG_WARNING,
1208                    "Expected %d bytes, got %d - skipping packet\n",
1209                    frame_size[dec_mode], buf_size);
1210         *got_frame_ptr = 0;
1211         return buf_size;
1212     }
1213
1214     if (unpack_bitstream(p, buf, buf_size) < 0) {
1215         bad_frame = 1;
1216         if (p->past_frame_type == ACTIVE_FRAME)
1217             p->cur_frame_type = ACTIVE_FRAME;
1218         else
1219             p->cur_frame_type = UNTRANSMITTED_FRAME;
1220     }
1221
1222     p->frame.nb_samples = FRAME_LEN;
1223     if ((ret = avctx->get_buffer(avctx, &p->frame)) < 0) {
1224          av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1225          return ret;
1226     }
1227
1228     out = (int16_t *)p->frame.data[0];
1229
1230     if (p->cur_frame_type == ACTIVE_FRAME) {
1231         if (!bad_frame)
1232             p->erased_frames = 0;
1233         else if (p->erased_frames != 3)
1234             p->erased_frames++;
1235
1236         inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, bad_frame);
1237         lsp_interpolate(lpc, cur_lsp, p->prev_lsp);
1238
1239         /* Save the lsp_vector for the next frame */
1240         memcpy(p->prev_lsp, cur_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
1241
1242         /* Generate the excitation for the frame */
1243         memcpy(p->excitation, p->prev_excitation,
1244                PITCH_MAX * sizeof(*p->excitation));
1245         if (!p->erased_frames) {
1246             int16_t *vector_ptr = p->excitation + PITCH_MAX;
1247
1248             /* Update interpolation gain memory */
1249             p->interp_gain = fixed_cb_gain[(p->subframe[2].amp_index +
1250                                             p->subframe[3].amp_index) >> 1];
1251             for (i = 0; i < SUBFRAMES; i++) {
1252                 gen_fcb_excitation(vector_ptr, &p->subframe[i], p->cur_rate,
1253                                    p->pitch_lag[i >> 1], i);
1254                 gen_acb_excitation(acb_vector, &p->excitation[SUBFRAME_LEN * i],
1255                                    p->pitch_lag[i >> 1], &p->subframe[i],
1256                                    p->cur_rate);
1257                 /* Get the total excitation */
1258                 for (j = 0; j < SUBFRAME_LEN; j++) {
1259                     int v = av_clip_int16(vector_ptr[j] << 1);
1260                     vector_ptr[j] = av_clip_int16(v + acb_vector[j]);
1261                 }
1262                 vector_ptr += SUBFRAME_LEN;
1263             }
1264
1265             vector_ptr = p->excitation + PITCH_MAX;
1266
1267             p->interp_index = comp_interp_index(p, p->pitch_lag[1],
1268                                                 &p->sid_gain, &p->cur_gain);
1269
1270             /* Peform pitch postfiltering */
1271             if (p->postfilter) {
1272                 i = PITCH_MAX;
1273                 for (j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1274                     comp_ppf_coeff(p, i, p->pitch_lag[j >> 1],
1275                                    ppf + j, p->cur_rate);
1276
1277                 for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1278                     ff_acelp_weighted_vector_sum(p->audio + LPC_ORDER + i,
1279                                                  vector_ptr + i,
1280                                                  vector_ptr + i + ppf[j].index,
1281                                                  ppf[j].sc_gain,
1282                                                  ppf[j].opt_gain,
1283                                                  1 << 14, 15, SUBFRAME_LEN);
1284             } else {
1285                 audio = vector_ptr - LPC_ORDER;
1286             }
1287
1288             /* Save the excitation for the next frame */
1289             memcpy(p->prev_excitation, p->excitation + FRAME_LEN,
1290                    PITCH_MAX * sizeof(*p->excitation));
1291         } else {
1292             p->interp_gain = (p->interp_gain * 3 + 2) >> 2;
1293             if (p->erased_frames == 3) {
1294                 /* Mute output */
1295                 memset(p->excitation, 0,
1296                        (FRAME_LEN + PITCH_MAX) * sizeof(*p->excitation));
1297                 memset(p->prev_excitation, 0,
1298                        PITCH_MAX * sizeof(*p->excitation));
1299                 memset(p->frame.data[0], 0,
1300                        (FRAME_LEN + LPC_ORDER) * sizeof(int16_t));
1301             } else {
1302                 int16_t *buf = p->audio + LPC_ORDER;
1303
1304                 /* Regenerate frame */
1305                 residual_interp(p->excitation, buf, p->interp_index,
1306                                 p->interp_gain, &p->random_seed);
1307
1308                 /* Save the excitation for the next frame */
1309                 memcpy(p->prev_excitation, buf + (FRAME_LEN - PITCH_MAX),
1310                        PITCH_MAX * sizeof(*p->excitation));
1311             }
1312         }
1313         p->cng_random_seed = CNG_RANDOM_SEED;
1314     } else {
1315         if (p->cur_frame_type == SID_FRAME) {
1316             p->sid_gain = sid_gain_to_lsp_index(p->subframe[0].amp_index);
1317             inverse_quant(p->sid_lsp, p->prev_lsp, p->lsp_index, 0);
1318         } else if (p->past_frame_type == ACTIVE_FRAME) {
1319             p->sid_gain = estimate_sid_gain(p);
1320         }
1321
1322         if (p->past_frame_type == ACTIVE_FRAME)
1323             p->cur_gain = p->sid_gain;
1324         else
1325             p->cur_gain = (p->cur_gain * 7 + p->sid_gain) >> 3;
1326         generate_noise(p);
1327         lsp_interpolate(lpc, p->sid_lsp, p->prev_lsp);
1328         /* Save the lsp_vector for the next frame */
1329         memcpy(p->prev_lsp, p->sid_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
1330     }
1331
1332     p->past_frame_type = p->cur_frame_type;
1333
1334     memcpy(p->audio, p->synth_mem, LPC_ORDER * sizeof(*p->audio));
1335     for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1336         ff_celp_lp_synthesis_filter(p->audio + i, &lpc[j * LPC_ORDER],
1337                                     audio + i, SUBFRAME_LEN, LPC_ORDER,
1338                                     0, 1, 1 << 12);
1339     memcpy(p->synth_mem, p->audio + FRAME_LEN, LPC_ORDER * sizeof(*p->audio));
1340
1341     if (p->postfilter) {
1342         formant_postfilter(p, lpc, p->audio, out);
1343     } else { // if output is not postfiltered it should be scaled by 2
1344         for (i = 0; i < FRAME_LEN; i++)
1345             out[i] = av_clip_int16(p->audio[LPC_ORDER + i] << 1);
1346     }
1347
1348     *got_frame_ptr   = 1;
1349     *(AVFrame *)data = p->frame;
1350
1351     return frame_size[dec_mode];
1352 }
1353
1354 #define OFFSET(x) offsetof(G723_1_Context, x)
1355 #define AD     AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1356
1357 static const AVOption options[] = {
1358     { "postfilter", "postfilter on/off", OFFSET(postfilter), AV_OPT_TYPE_INT,
1359       { .i64 = 1 }, 0, 1, AD },
1360     { NULL }
1361 };
1362
1363
1364 static const AVClass g723_1dec_class = {
1365     .class_name = "G.723.1 decoder",
1366     .item_name  = av_default_item_name,
1367     .option     = options,
1368     .version    = LIBAVUTIL_VERSION_INT,
1369 };
1370
1371 AVCodec ff_g723_1_decoder = {
1372     .name           = "g723_1",
1373     .type           = AVMEDIA_TYPE_AUDIO,
1374     .id             = AV_CODEC_ID_G723_1,
1375     .priv_data_size = sizeof(G723_1_Context),
1376     .init           = g723_1_decode_init,
1377     .decode         = g723_1_decode_frame,
1378     .long_name      = NULL_IF_CONFIG_SMALL("G.723.1"),
1379     .capabilities   = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
1380     .priv_class     = &g723_1dec_class,
1381 };