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