]> git.sesse.net Git - ffmpeg/blob - libavcodec/g723_1.c
Merge commit '0a7005bebd23ade7bb852bce0401af1a8fdbb723'
[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 FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * G.723.1 compatible decoder
26  */
27
28 #define BITSTREAM_READER_LE
29 #include "libavutil/audioconvert.h"
30 #include "libavutil/lzo.h"
31 #include "libavutil/opt.h"
32 #include "avcodec.h"
33 #include "internal.h"
34 #include "get_bits.h"
35 #include "acelp_vectors.h"
36 #include "celp_filters.h"
37 #include "celp_math.h"
38 #include "g723_1_data.h"
39
40 #define CNG_RANDOM_SEED 12345
41
42 typedef struct g723_1_context {
43     AVClass *class;
44     AVFrame frame;
45
46     G723_1_Subframe subframe[4];
47     enum FrameType cur_frame_type;
48     enum FrameType past_frame_type;
49     enum Rate cur_rate;
50     uint8_t lsp_index[LSP_BANDS];
51     int pitch_lag[2];
52     int erased_frames;
53
54     int16_t prev_lsp[LPC_ORDER];
55     int16_t sid_lsp[LPC_ORDER];
56     int16_t prev_excitation[PITCH_MAX];
57     int16_t excitation[PITCH_MAX + FRAME_LEN + 4];
58     int16_t synth_mem[LPC_ORDER];
59     int16_t fir_mem[LPC_ORDER];
60     int     iir_mem[LPC_ORDER];
61
62     int random_seed;
63     int cng_random_seed;
64     int interp_index;
65     int interp_gain;
66     int sid_gain;
67     int cur_gain;
68     int reflection_coef;
69     int pf_gain;                 ///< formant postfilter
70                                  ///< gain scaling unit memory
71     int postfilter;
72
73     int16_t audio[FRAME_LEN + LPC_ORDER + PITCH_MAX + 4];
74     int16_t prev_data[HALF_FRAME_LEN];
75     int16_t prev_weight_sig[PITCH_MAX];
76
77
78     int16_t hpf_fir_mem;                   ///< highpass filter fir
79     int     hpf_iir_mem;                   ///< and iir memories
80     int16_t perf_fir_mem[LPC_ORDER];       ///< perceptual filter fir
81     int16_t perf_iir_mem[LPC_ORDER];       ///< and iir memories
82
83     int16_t harmonic_mem[PITCH_MAX];
84 } G723_1_Context;
85
86 static av_cold int g723_1_decode_init(AVCodecContext *avctx)
87 {
88     G723_1_Context *p = avctx->priv_data;
89
90     avctx->channel_layout = AV_CH_LAYOUT_MONO;
91     avctx->sample_fmt     = AV_SAMPLE_FMT_S16;
92     avctx->channels       = 1;
93     p->pf_gain            = 1 << 12;
94
95     avcodec_get_frame_defaults(&p->frame);
96     avctx->coded_frame    = &p->frame;
97
98     memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
99     memcpy(p->sid_lsp,  dc_lsp, LPC_ORDER * sizeof(*p->sid_lsp));
100
101     p->cng_random_seed = CNG_RANDOM_SEED;
102     p->past_frame_type = SID_FRAME;
103
104     return 0;
105 }
106
107 /**
108  * Unpack the frame into parameters.
109  *
110  * @param p           the context
111  * @param buf         pointer to the input buffer
112  * @param buf_size    size of the input buffer
113  */
114 static int unpack_bitstream(G723_1_Context *p, const uint8_t *buf,
115                             int buf_size)
116 {
117     GetBitContext gb;
118     int ad_cb_len;
119     int temp, info_bits, i;
120
121     init_get_bits(&gb, buf, buf_size * 8);
122
123     /* Extract frame type and rate info */
124     info_bits = get_bits(&gb, 2);
125
126     if (info_bits == 3) {
127         p->cur_frame_type = UNTRANSMITTED_FRAME;
128         return 0;
129     }
130
131     /* Extract 24 bit lsp indices, 8 bit for each band */
132     p->lsp_index[2] = get_bits(&gb, 8);
133     p->lsp_index[1] = get_bits(&gb, 8);
134     p->lsp_index[0] = get_bits(&gb, 8);
135
136     if (info_bits == 2) {
137         p->cur_frame_type = SID_FRAME;
138         p->subframe[0].amp_index = get_bits(&gb, 6);
139         return 0;
140     }
141
142     /* Extract the info common to both rates */
143     p->cur_rate       = info_bits ? RATE_5300 : RATE_6300;
144     p->cur_frame_type = ACTIVE_FRAME;
145
146     p->pitch_lag[0] = get_bits(&gb, 7);
147     if (p->pitch_lag[0] > 123)       /* test if forbidden code */
148         return -1;
149     p->pitch_lag[0] += PITCH_MIN;
150     p->subframe[1].ad_cb_lag = get_bits(&gb, 2);
151
152     p->pitch_lag[1] = get_bits(&gb, 7);
153     if (p->pitch_lag[1] > 123)
154         return -1;
155     p->pitch_lag[1] += PITCH_MIN;
156     p->subframe[3].ad_cb_lag = get_bits(&gb, 2);
157     p->subframe[0].ad_cb_lag = 1;
158     p->subframe[2].ad_cb_lag = 1;
159
160     for (i = 0; i < SUBFRAMES; i++) {
161         /* Extract combined gain */
162         temp = get_bits(&gb, 12);
163         ad_cb_len = 170;
164         p->subframe[i].dirac_train = 0;
165         if (p->cur_rate == RATE_6300 && p->pitch_lag[i >> 1] < SUBFRAME_LEN - 2) {
166             p->subframe[i].dirac_train = temp >> 11;
167             temp &= 0x7FF;
168             ad_cb_len = 85;
169         }
170         p->subframe[i].ad_cb_gain = FASTDIV(temp, GAIN_LEVELS);
171         if (p->subframe[i].ad_cb_gain < ad_cb_len) {
172             p->subframe[i].amp_index = temp - p->subframe[i].ad_cb_gain *
173                                        GAIN_LEVELS;
174         } else {
175             return -1;
176         }
177     }
178
179     p->subframe[0].grid_index = get_bits1(&gb);
180     p->subframe[1].grid_index = get_bits1(&gb);
181     p->subframe[2].grid_index = get_bits1(&gb);
182     p->subframe[3].grid_index = get_bits1(&gb);
183
184     if (p->cur_rate == RATE_6300) {
185         skip_bits1(&gb);  /* skip reserved bit */
186
187         /* Compute pulse_pos index using the 13-bit combined position index */
188         temp = get_bits(&gb, 13);
189         p->subframe[0].pulse_pos = temp / 810;
190
191         temp -= p->subframe[0].pulse_pos * 810;
192         p->subframe[1].pulse_pos = FASTDIV(temp, 90);
193
194         temp -= p->subframe[1].pulse_pos * 90;
195         p->subframe[2].pulse_pos = FASTDIV(temp, 9);
196         p->subframe[3].pulse_pos = temp - p->subframe[2].pulse_pos * 9;
197
198         p->subframe[0].pulse_pos = (p->subframe[0].pulse_pos << 16) +
199                                    get_bits(&gb, 16);
200         p->subframe[1].pulse_pos = (p->subframe[1].pulse_pos << 14) +
201                                    get_bits(&gb, 14);
202         p->subframe[2].pulse_pos = (p->subframe[2].pulse_pos << 16) +
203                                    get_bits(&gb, 16);
204         p->subframe[3].pulse_pos = (p->subframe[3].pulse_pos << 14) +
205                                    get_bits(&gb, 14);
206
207         p->subframe[0].pulse_sign = get_bits(&gb, 6);
208         p->subframe[1].pulse_sign = get_bits(&gb, 5);
209         p->subframe[2].pulse_sign = get_bits(&gb, 6);
210         p->subframe[3].pulse_sign = get_bits(&gb, 5);
211     } else { /* 5300 bps */
212         p->subframe[0].pulse_pos  = get_bits(&gb, 12);
213         p->subframe[1].pulse_pos  = get_bits(&gb, 12);
214         p->subframe[2].pulse_pos  = get_bits(&gb, 12);
215         p->subframe[3].pulse_pos  = get_bits(&gb, 12);
216
217         p->subframe[0].pulse_sign = get_bits(&gb, 4);
218         p->subframe[1].pulse_sign = get_bits(&gb, 4);
219         p->subframe[2].pulse_sign = get_bits(&gb, 4);
220         p->subframe[3].pulse_sign = get_bits(&gb, 4);
221     }
222
223     return 0;
224 }
225
226 /**
227  * Bitexact implementation of sqrt(val/2).
228  */
229 static int16_t square_root(int val)
230 {
231     return (ff_sqrt(val << 1) >> 1) & (~1);
232 }
233
234 /**
235  * Calculate the number of left-shifts required for normalizing the input.
236  *
237  * @param num   input number
238  * @param width width of the input, 15 or 31 bits
239  */
240 static int normalize_bits(int num, int width)
241 {
242     return width - av_log2(num) - 1;
243 }
244
245 #define normalize_bits_int16(num) normalize_bits(num, 15)
246 #define normalize_bits_int32(num) normalize_bits(num, 31)
247
248 /**
249  * Scale vector contents based on the largest of their absolutes.
250  */
251 static int scale_vector(int16_t *dst, const int16_t *vector, int length)
252 {
253     int bits, max = 0;
254     int i;
255
256     for (i = 0; i < length; i++)
257         max |= FFABS(vector[i]);
258
259     bits= 14 - av_log2_16bit(max);
260     bits= FFMAX(bits, 0);
261
262     for (i = 0; i < length; i++)
263         dst[i] = vector[i] << bits >> 3;
264
265     return bits - 3;
266 }
267
268 /**
269  * Perform inverse quantization of LSP frequencies.
270  *
271  * @param cur_lsp    the current LSP vector
272  * @param prev_lsp   the previous LSP vector
273  * @param lsp_index  VQ indices
274  * @param bad_frame  bad frame flag
275  */
276 static void inverse_quant(int16_t *cur_lsp, int16_t *prev_lsp,
277                           uint8_t *lsp_index, int bad_frame)
278 {
279     int min_dist, pred;
280     int i, j, temp, stable;
281
282     /* Check for frame erasure */
283     if (!bad_frame) {
284         min_dist     = 0x100;
285         pred         = 12288;
286     } else {
287         min_dist     = 0x200;
288         pred         = 23552;
289         lsp_index[0] = lsp_index[1] = lsp_index[2] = 0;
290     }
291
292     /* Get the VQ table entry corresponding to the transmitted index */
293     cur_lsp[0] = lsp_band0[lsp_index[0]][0];
294     cur_lsp[1] = lsp_band0[lsp_index[0]][1];
295     cur_lsp[2] = lsp_band0[lsp_index[0]][2];
296     cur_lsp[3] = lsp_band1[lsp_index[1]][0];
297     cur_lsp[4] = lsp_band1[lsp_index[1]][1];
298     cur_lsp[5] = lsp_band1[lsp_index[1]][2];
299     cur_lsp[6] = lsp_band2[lsp_index[2]][0];
300     cur_lsp[7] = lsp_band2[lsp_index[2]][1];
301     cur_lsp[8] = lsp_band2[lsp_index[2]][2];
302     cur_lsp[9] = lsp_band2[lsp_index[2]][3];
303
304     /* Add predicted vector & DC component to the previously quantized vector */
305     for (i = 0; i < LPC_ORDER; i++) {
306         temp        = ((prev_lsp[i] - dc_lsp[i]) * pred + (1 << 14)) >> 15;
307         cur_lsp[i] += dc_lsp[i] + temp;
308     }
309
310     for (i = 0; i < LPC_ORDER; i++) {
311         cur_lsp[0]             = FFMAX(cur_lsp[0],  0x180);
312         cur_lsp[LPC_ORDER - 1] = FFMIN(cur_lsp[LPC_ORDER - 1], 0x7e00);
313
314         /* Stability check */
315         for (j = 1; j < LPC_ORDER; j++) {
316             temp = min_dist + cur_lsp[j - 1] - cur_lsp[j];
317             if (temp > 0) {
318                 temp >>= 1;
319                 cur_lsp[j - 1] -= temp;
320                 cur_lsp[j]     += temp;
321             }
322         }
323         stable = 1;
324         for (j = 1; j < LPC_ORDER; j++) {
325             temp = cur_lsp[j - 1] + min_dist - cur_lsp[j] - 4;
326             if (temp > 0) {
327                 stable = 0;
328                 break;
329             }
330         }
331         if (stable)
332             break;
333     }
334     if (!stable)
335         memcpy(cur_lsp, prev_lsp, LPC_ORDER * sizeof(*cur_lsp));
336 }
337
338 /**
339  * Bitexact implementation of 2ab scaled by 1/2^16.
340  *
341  * @param a 32 bit multiplicand
342  * @param b 16 bit multiplier
343  */
344 #define MULL2(a, b) \
345         MULL(a,b,15)
346
347 /**
348  * Convert LSP frequencies to LPC coefficients.
349  *
350  * @param lpc buffer for LPC coefficients
351  */
352 static void lsp2lpc(int16_t *lpc)
353 {
354     int f1[LPC_ORDER / 2 + 1];
355     int f2[LPC_ORDER / 2 + 1];
356     int i, j;
357
358     /* Calculate negative cosine */
359     for (j = 0; j < LPC_ORDER; j++) {
360         int index     = lpc[j] >> 7;
361         int offset    = lpc[j] & 0x7f;
362         int temp1     = cos_tab[index] << 16;
363         int temp2     = (cos_tab[index + 1] - cos_tab[index]) *
364                           ((offset << 8) + 0x80) << 1;
365
366         lpc[j] = -(av_sat_dadd32(1 << 15, temp1 + temp2) >> 16);
367     }
368
369     /*
370      * Compute sum and difference polynomial coefficients
371      * (bitexact alternative to lsp2poly() in lsp.c)
372      */
373     /* Initialize with values in Q28 */
374     f1[0] = 1 << 28;
375     f1[1] = (lpc[0] << 14) + (lpc[2] << 14);
376     f1[2] = lpc[0] * lpc[2] + (2 << 28);
377
378     f2[0] = 1 << 28;
379     f2[1] = (lpc[1] << 14) + (lpc[3] << 14);
380     f2[2] = lpc[1] * lpc[3] + (2 << 28);
381
382     /*
383      * Calculate and scale the coefficients by 1/2 in
384      * each iteration for a final scaling factor of Q25
385      */
386     for (i = 2; i < LPC_ORDER / 2; i++) {
387         f1[i + 1] = f1[i - 1] + MULL2(f1[i], lpc[2 * i]);
388         f2[i + 1] = f2[i - 1] + MULL2(f2[i], lpc[2 * i + 1]);
389
390         for (j = i; j >= 2; j--) {
391             f1[j] = MULL2(f1[j - 1], lpc[2 * i]) +
392                     (f1[j] >> 1) + (f1[j - 2] >> 1);
393             f2[j] = MULL2(f2[j - 1], lpc[2 * i + 1]) +
394                     (f2[j] >> 1) + (f2[j - 2] >> 1);
395         }
396
397         f1[0] >>= 1;
398         f2[0] >>= 1;
399         f1[1] = ((lpc[2 * i]     << 16 >> i) + f1[1]) >> 1;
400         f2[1] = ((lpc[2 * i + 1] << 16 >> i) + f2[1]) >> 1;
401     }
402
403     /* Convert polynomial coefficients to LPC coefficients */
404     for (i = 0; i < LPC_ORDER / 2; i++) {
405         int64_t ff1 = f1[i + 1] + f1[i];
406         int64_t ff2 = f2[i + 1] - f2[i];
407
408         lpc[i] = av_clipl_int32(((ff1 + ff2) << 3) + (1 << 15)) >> 16;
409         lpc[LPC_ORDER - i - 1] = av_clipl_int32(((ff1 - ff2) << 3) +
410                                                 (1 << 15)) >> 16;
411     }
412 }
413
414 /**
415  * Quantize LSP frequencies by interpolation and convert them to
416  * the corresponding LPC coefficients.
417  *
418  * @param lpc      buffer for LPC coefficients
419  * @param cur_lsp  the current LSP vector
420  * @param prev_lsp the previous LSP vector
421  */
422 static void lsp_interpolate(int16_t *lpc, int16_t *cur_lsp, int16_t *prev_lsp)
423 {
424     int i;
425     int16_t *lpc_ptr = lpc;
426
427     /* cur_lsp * 0.25 + prev_lsp * 0.75 */
428     ff_acelp_weighted_vector_sum(lpc, cur_lsp, prev_lsp,
429                                  4096, 12288, 1 << 13, 14, LPC_ORDER);
430     ff_acelp_weighted_vector_sum(lpc + LPC_ORDER, cur_lsp, prev_lsp,
431                                  8192, 8192, 1 << 13, 14, LPC_ORDER);
432     ff_acelp_weighted_vector_sum(lpc + 2 * LPC_ORDER, cur_lsp, prev_lsp,
433                                  12288, 4096, 1 << 13, 14, LPC_ORDER);
434     memcpy(lpc + 3 * LPC_ORDER, cur_lsp, LPC_ORDER * sizeof(*lpc));
435
436     for (i = 0; i < SUBFRAMES; i++) {
437         lsp2lpc(lpc_ptr);
438         lpc_ptr += LPC_ORDER;
439     }
440 }
441
442 /**
443  * Generate a train of dirac functions with period as pitch lag.
444  */
445 static void gen_dirac_train(int16_t *buf, int pitch_lag)
446 {
447     int16_t vector[SUBFRAME_LEN];
448     int i, j;
449
450     memcpy(vector, buf, SUBFRAME_LEN * sizeof(*vector));
451     for (i = pitch_lag; i < SUBFRAME_LEN; i += pitch_lag) {
452         for (j = 0; j < SUBFRAME_LEN - i; j++)
453             buf[i + j] += vector[j];
454     }
455 }
456
457 /**
458  * Generate fixed codebook excitation vector.
459  *
460  * @param vector    decoded excitation vector
461  * @param subfrm    current subframe
462  * @param cur_rate  current bitrate
463  * @param pitch_lag closed loop pitch lag
464  * @param index     current subframe index
465  */
466 static void gen_fcb_excitation(int16_t *vector, G723_1_Subframe *subfrm,
467                                enum Rate cur_rate, int pitch_lag, int index)
468 {
469     int temp, i, j;
470
471     memset(vector, 0, SUBFRAME_LEN * sizeof(*vector));
472
473     if (cur_rate == RATE_6300) {
474         if (subfrm->pulse_pos >= max_pos[index])
475             return;
476
477         /* Decode amplitudes and positions */
478         j = PULSE_MAX - pulses[index];
479         temp = subfrm->pulse_pos;
480         for (i = 0; i < SUBFRAME_LEN / GRID_SIZE; i++) {
481             temp -= combinatorial_table[j][i];
482             if (temp >= 0)
483                 continue;
484             temp += combinatorial_table[j++][i];
485             if (subfrm->pulse_sign & (1 << (PULSE_MAX - j))) {
486                 vector[subfrm->grid_index + GRID_SIZE * i] =
487                                         -fixed_cb_gain[subfrm->amp_index];
488             } else {
489                 vector[subfrm->grid_index + GRID_SIZE * i] =
490                                          fixed_cb_gain[subfrm->amp_index];
491             }
492             if (j == PULSE_MAX)
493                 break;
494         }
495         if (subfrm->dirac_train == 1)
496             gen_dirac_train(vector, pitch_lag);
497     } else { /* 5300 bps */
498         int cb_gain  = fixed_cb_gain[subfrm->amp_index];
499         int cb_shift = subfrm->grid_index;
500         int cb_sign  = subfrm->pulse_sign;
501         int cb_pos   = subfrm->pulse_pos;
502         int offset, beta, lag;
503
504         for (i = 0; i < 8; i += 2) {
505             offset         = ((cb_pos & 7) << 3) + cb_shift + i;
506             vector[offset] = (cb_sign & 1) ? cb_gain : -cb_gain;
507             cb_pos  >>= 3;
508             cb_sign >>= 1;
509         }
510
511         /* Enhance harmonic components */
512         lag  = pitch_contrib[subfrm->ad_cb_gain << 1] + pitch_lag +
513                subfrm->ad_cb_lag - 1;
514         beta = pitch_contrib[(subfrm->ad_cb_gain << 1) + 1];
515
516         if (lag < SUBFRAME_LEN - 2) {
517             for (i = lag; i < SUBFRAME_LEN; i++)
518                 vector[i] += beta * vector[i - lag] >> 15;
519         }
520     }
521 }
522
523 /**
524  * Get delayed contribution from the previous excitation vector.
525  */
526 static void get_residual(int16_t *residual, int16_t *prev_excitation, int lag)
527 {
528     int offset = PITCH_MAX - PITCH_ORDER / 2 - lag;
529     int i;
530
531     residual[0] = prev_excitation[offset];
532     residual[1] = prev_excitation[offset + 1];
533
534     offset += 2;
535     for (i = 2; i < SUBFRAME_LEN + PITCH_ORDER - 1; i++)
536         residual[i] = prev_excitation[offset + (i - 2) % lag];
537 }
538
539 static int dot_product(const int16_t *a, const int16_t *b, int length)
540 {
541     int sum = ff_dot_product(a,b,length);
542     return av_sat_add32(sum, sum);
543 }
544
545 /**
546  * Generate adaptive codebook excitation.
547  */
548 static void gen_acb_excitation(int16_t *vector, int16_t *prev_excitation,
549                                int pitch_lag, G723_1_Subframe *subfrm,
550                                enum Rate cur_rate)
551 {
552     int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
553     const int16_t *cb_ptr;
554     int lag = pitch_lag + subfrm->ad_cb_lag - 1;
555
556     int i;
557     int sum;
558
559     get_residual(residual, prev_excitation, lag);
560
561     /* Select quantization table */
562     if (cur_rate == RATE_6300 && pitch_lag < SUBFRAME_LEN - 2) {
563         cb_ptr = adaptive_cb_gain85;
564     } else
565         cb_ptr = adaptive_cb_gain170;
566
567     /* Calculate adaptive vector */
568     cb_ptr += subfrm->ad_cb_gain * 20;
569     for (i = 0; i < SUBFRAME_LEN; i++) {
570         sum = ff_dot_product(residual + i, cb_ptr, PITCH_ORDER);
571         vector[i] = av_sat_dadd32(1 << 15, av_sat_add32(sum, sum)) >> 16;
572     }
573 }
574
575 /**
576  * Estimate maximum auto-correlation around pitch lag.
577  *
578  * @param buf       buffer with offset applied
579  * @param offset    offset of the excitation vector
580  * @param ccr_max   pointer to the maximum auto-correlation
581  * @param pitch_lag decoded pitch lag
582  * @param length    length of autocorrelation
583  * @param dir       forward lag(1) / backward lag(-1)
584  */
585 static int autocorr_max(const int16_t *buf, int offset, int *ccr_max,
586                         int pitch_lag, int length, int dir)
587 {
588     int limit, ccr, lag = 0;
589     int i;
590
591     pitch_lag = FFMIN(PITCH_MAX - 3, pitch_lag);
592     if (dir > 0)
593         limit = FFMIN(FRAME_LEN + PITCH_MAX - offset - length, pitch_lag + 3);
594     else
595         limit = pitch_lag + 3;
596
597     for (i = pitch_lag - 3; i <= limit; i++) {
598         ccr = dot_product(buf, buf + dir * i, length);
599
600         if (ccr > *ccr_max) {
601             *ccr_max = ccr;
602             lag = i;
603         }
604     }
605     return lag;
606 }
607
608 /**
609  * Calculate pitch postfilter optimal and scaling gains.
610  *
611  * @param lag      pitch postfilter forward/backward lag
612  * @param ppf      pitch postfilter parameters
613  * @param cur_rate current bitrate
614  * @param tgt_eng  target energy
615  * @param ccr      cross-correlation
616  * @param res_eng  residual energy
617  */
618 static void comp_ppf_gains(int lag, PPFParam *ppf, enum Rate cur_rate,
619                            int tgt_eng, int ccr, int res_eng)
620 {
621     int pf_residual;     /* square of postfiltered residual */
622     int temp1, temp2;
623
624     ppf->index = lag;
625
626     temp1 = tgt_eng * res_eng >> 1;
627     temp2 = ccr * ccr << 1;
628
629     if (temp2 > temp1) {
630         if (ccr >= res_eng) {
631             ppf->opt_gain = ppf_gain_weight[cur_rate];
632         } else {
633             ppf->opt_gain = (ccr << 15) / res_eng *
634                             ppf_gain_weight[cur_rate] >> 15;
635         }
636         /* pf_res^2 = tgt_eng + 2*ccr*gain + res_eng*gain^2 */
637         temp1       = (tgt_eng << 15) + (ccr * ppf->opt_gain << 1);
638         temp2       = (ppf->opt_gain * ppf->opt_gain >> 15) * res_eng;
639         pf_residual = av_sat_add32(temp1, temp2 + (1 << 15)) >> 16;
640
641         if (tgt_eng >= pf_residual << 1) {
642             temp1 = 0x7fff;
643         } else {
644             temp1 = (tgt_eng << 14) / pf_residual;
645         }
646
647         /* scaling_gain = sqrt(tgt_eng/pf_res^2) */
648         ppf->sc_gain = square_root(temp1 << 16);
649     } else {
650         ppf->opt_gain = 0;
651         ppf->sc_gain  = 0x7fff;
652     }
653
654     ppf->opt_gain = av_clip_int16(ppf->opt_gain * ppf->sc_gain >> 15);
655 }
656
657 /**
658  * Calculate pitch postfilter parameters.
659  *
660  * @param p         the context
661  * @param offset    offset of the excitation vector
662  * @param pitch_lag decoded pitch lag
663  * @param ppf       pitch postfilter parameters
664  * @param cur_rate  current bitrate
665  */
666 static void comp_ppf_coeff(G723_1_Context *p, int offset, int pitch_lag,
667                            PPFParam *ppf, enum Rate cur_rate)
668 {
669
670     int16_t scale;
671     int i;
672     int temp1, temp2;
673
674     /*
675      * 0 - target energy
676      * 1 - forward cross-correlation
677      * 2 - forward residual energy
678      * 3 - backward cross-correlation
679      * 4 - backward residual energy
680      */
681     int energy[5] = {0, 0, 0, 0, 0};
682     int16_t *buf  = p->audio + LPC_ORDER + offset;
683     int fwd_lag   = autocorr_max(buf, offset, &energy[1], pitch_lag,
684                                  SUBFRAME_LEN, 1);
685     int back_lag  = autocorr_max(buf, offset, &energy[3], pitch_lag,
686                                  SUBFRAME_LEN, -1);
687
688     ppf->index    = 0;
689     ppf->opt_gain = 0;
690     ppf->sc_gain  = 0x7fff;
691
692     /* Case 0, Section 3.6 */
693     if (!back_lag && !fwd_lag)
694         return;
695
696     /* Compute target energy */
697     energy[0] = dot_product(buf, buf, SUBFRAME_LEN);
698
699     /* Compute forward residual energy */
700     if (fwd_lag)
701         energy[2] = dot_product(buf + fwd_lag, buf + fwd_lag, SUBFRAME_LEN);
702
703     /* Compute backward residual energy */
704     if (back_lag)
705         energy[4] = dot_product(buf - back_lag, buf - back_lag, SUBFRAME_LEN);
706
707     /* Normalize and shorten */
708     temp1 = 0;
709     for (i = 0; i < 5; i++)
710         temp1 = FFMAX(energy[i], temp1);
711
712     scale = normalize_bits(temp1, 31);
713     for (i = 0; i < 5; i++)
714         energy[i] = av_clipl_int32(energy[i] << scale) >> 16;
715
716     if (fwd_lag && !back_lag) {  /* Case 1 */
717         comp_ppf_gains(fwd_lag,  ppf, cur_rate, energy[0], energy[1],
718                        energy[2]);
719     } else if (!fwd_lag) {       /* Case 2 */
720         comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
721                        energy[4]);
722     } else {                     /* Case 3 */
723
724         /*
725          * Select the largest of energy[1]^2/energy[2]
726          * and energy[3]^2/energy[4]
727          */
728         temp1 = energy[4] * ((energy[1] * energy[1] + (1 << 14)) >> 15);
729         temp2 = energy[2] * ((energy[3] * energy[3] + (1 << 14)) >> 15);
730         if (temp1 >= temp2) {
731             comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
732                            energy[2]);
733         } else {
734             comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
735                            energy[4]);
736         }
737     }
738 }
739
740 /**
741  * Classify frames as voiced/unvoiced.
742  *
743  * @param p         the context
744  * @param pitch_lag decoded pitch_lag
745  * @param exc_eng   excitation energy estimation
746  * @param scale     scaling factor of exc_eng
747  *
748  * @return residual interpolation index if voiced, 0 otherwise
749  */
750 static int comp_interp_index(G723_1_Context *p, int pitch_lag,
751                              int *exc_eng, int *scale)
752 {
753     int offset = PITCH_MAX + 2 * SUBFRAME_LEN;
754     int16_t *buf = p->audio + LPC_ORDER;
755
756     int index, ccr, tgt_eng, best_eng, temp;
757
758     *scale = scale_vector(buf, p->excitation, FRAME_LEN + PITCH_MAX);
759     buf   += offset;
760
761     /* Compute maximum backward cross-correlation */
762     ccr   = 0;
763     index = autocorr_max(buf, offset, &ccr, pitch_lag, SUBFRAME_LEN * 2, -1);
764     ccr   = av_sat_add32(ccr, 1 << 15) >> 16;
765
766     /* Compute target energy */
767     tgt_eng  = dot_product(buf, buf, SUBFRAME_LEN * 2);
768     *exc_eng = av_sat_add32(tgt_eng, 1 << 15) >> 16;
769
770     if (ccr <= 0)
771         return 0;
772
773     /* Compute best energy */
774     best_eng = dot_product(buf - index, buf - index, SUBFRAME_LEN * 2);
775     best_eng = av_sat_add32(best_eng, 1 << 15) >> 16;
776
777     temp = best_eng * *exc_eng >> 3;
778
779     if (temp < ccr * ccr) {
780         return index;
781     } else
782         return 0;
783 }
784
785 /**
786  * Peform residual interpolation based on frame classification.
787  *
788  * @param buf   decoded excitation vector
789  * @param out   output vector
790  * @param lag   decoded pitch lag
791  * @param gain  interpolated gain
792  * @param rseed seed for random number generator
793  */
794 static void residual_interp(int16_t *buf, int16_t *out, int lag,
795                             int gain, int *rseed)
796 {
797     int i;
798     if (lag) { /* Voiced */
799         int16_t *vector_ptr = buf + PITCH_MAX;
800         /* Attenuate */
801         for (i = 0; i < lag; i++)
802             out[i] = vector_ptr[i - lag] * 3 >> 2;
803         av_memcpy_backptr((uint8_t*)(out + lag), lag * sizeof(*out),
804                           (FRAME_LEN - lag) * sizeof(*out));
805     } else {  /* Unvoiced */
806         for (i = 0; i < FRAME_LEN; i++) {
807             *rseed = *rseed * 521 + 259;
808             out[i] = gain * *rseed >> 15;
809         }
810         memset(buf, 0, (FRAME_LEN + PITCH_MAX) * sizeof(*buf));
811     }
812 }
813
814 /**
815  * Perform IIR filtering.
816  *
817  * @param fir_coef FIR coefficients
818  * @param iir_coef IIR coefficients
819  * @param src      source vector
820  * @param dest     destination vector
821  * @param width    width of the output, 16 bits(0) / 32 bits(1)
822  */
823 #define iir_filter(fir_coef, iir_coef, src, dest, width)\
824 {\
825     int m, n;\
826     int res_shift = 16 & ~-(width);\
827     int in_shift  = 16 - res_shift;\
828 \
829     for (m = 0; m < SUBFRAME_LEN; m++) {\
830         int64_t filter = 0;\
831         for (n = 1; n <= LPC_ORDER; n++) {\
832             filter -= (fir_coef)[n - 1] * (src)[m - n] -\
833                       (iir_coef)[n - 1] * ((dest)[m - n] >> in_shift);\
834         }\
835 \
836         (dest)[m] = av_clipl_int32(((src)[m] << 16) + (filter << 3) +\
837                                    (1 << 15)) >> res_shift;\
838     }\
839 }
840
841 /**
842  * Adjust gain of postfiltered signal.
843  *
844  * @param p      the context
845  * @param buf    postfiltered output vector
846  * @param energy input energy coefficient
847  */
848 static void gain_scale(G723_1_Context *p, int16_t * buf, int energy)
849 {
850     int num, denom, gain, bits1, bits2;
851     int i;
852
853     num   = energy;
854     denom = 0;
855     for (i = 0; i < SUBFRAME_LEN; i++) {
856         int temp = buf[i] >> 2;
857         temp *= temp;
858         denom = av_sat_dadd32(denom, temp);
859     }
860
861     if (num && denom) {
862         bits1   = normalize_bits(num,   31);
863         bits2   = normalize_bits(denom, 31);
864         num     = num << bits1 >> 1;
865         denom <<= bits2;
866
867         bits2 = 5 + bits1 - bits2;
868         bits2 = FFMAX(0, bits2);
869
870         gain = (num >> 1) / (denom >> 16);
871         gain = square_root(gain << 16 >> bits2);
872     } else {
873         gain = 1 << 12;
874     }
875
876     for (i = 0; i < SUBFRAME_LEN; i++) {
877         p->pf_gain = (15 * p->pf_gain + gain + (1 << 3)) >> 4;
878         buf[i]     = av_clip_int16((buf[i] * (p->pf_gain + (p->pf_gain >> 4)) +
879                                    (1 << 10)) >> 11);
880     }
881 }
882
883 /**
884  * Perform formant filtering.
885  *
886  * @param p   the context
887  * @param lpc quantized lpc coefficients
888  * @param buf input buffer
889  * @param dst output buffer
890  */
891 static void formant_postfilter(G723_1_Context *p, int16_t *lpc,
892                                int16_t *buf, int16_t *dst)
893 {
894     int16_t filter_coef[2][LPC_ORDER];
895     int filter_signal[LPC_ORDER + FRAME_LEN], *signal_ptr;
896     int i, j, k;
897
898     memcpy(buf, p->fir_mem, LPC_ORDER * sizeof(*buf));
899     memcpy(filter_signal, p->iir_mem, LPC_ORDER * sizeof(*filter_signal));
900
901     for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
902         for (k = 0; k < LPC_ORDER; k++) {
903             filter_coef[0][k] = (-lpc[k] * postfilter_tbl[0][k] +
904                                  (1 << 14)) >> 15;
905             filter_coef[1][k] = (-lpc[k] * postfilter_tbl[1][k] +
906                                  (1 << 14)) >> 15;
907         }
908         iir_filter(filter_coef[0], filter_coef[1], buf + i,
909                    filter_signal + i, 1);
910         lpc += LPC_ORDER;
911     }
912
913     memcpy(p->fir_mem, buf + FRAME_LEN, LPC_ORDER * sizeof(int16_t));
914     memcpy(p->iir_mem, filter_signal + FRAME_LEN, LPC_ORDER * sizeof(int));
915
916     buf += LPC_ORDER;
917     signal_ptr = filter_signal + LPC_ORDER;
918     for (i = 0; i < SUBFRAMES; i++) {
919         int temp;
920         int auto_corr[2];
921         int scale, energy;
922
923         /* Normalize */
924         scale = scale_vector(dst, buf, SUBFRAME_LEN);
925
926         /* Compute auto correlation coefficients */
927         auto_corr[0] = dot_product(dst, dst + 1, SUBFRAME_LEN - 1);
928         auto_corr[1] = dot_product(dst, dst,     SUBFRAME_LEN);
929
930         /* Compute reflection coefficient */
931         temp = auto_corr[1] >> 16;
932         if (temp) {
933             temp = (auto_corr[0] >> 2) / temp;
934         }
935         p->reflection_coef = (3 * p->reflection_coef + temp + 2) >> 2;
936         temp = -p->reflection_coef >> 1 & ~3;
937
938         /* Compensation filter */
939         for (j = 0; j < SUBFRAME_LEN; j++) {
940             dst[j] = av_sat_dadd32(signal_ptr[j],
941                                    (signal_ptr[j - 1] >> 16) * temp) >> 16;
942         }
943
944         /* Compute normalized signal energy */
945         temp = 2 * scale + 4;
946         if (temp < 0) {
947             energy = av_clipl_int32((int64_t)auto_corr[1] << -temp);
948         } else
949             energy = auto_corr[1] >> temp;
950
951         gain_scale(p, dst, energy);
952
953         buf        += SUBFRAME_LEN;
954         signal_ptr += SUBFRAME_LEN;
955         dst        += SUBFRAME_LEN;
956     }
957 }
958
959 static int sid_gain_to_lsp_index(int gain)
960 {
961     if (gain < 0x10)
962         return gain << 6;
963     else if (gain < 0x20)
964         return gain - 8 << 7;
965     else
966         return gain - 20 << 8;
967 }
968
969 static inline int cng_rand(int *state, int base)
970 {
971     *state = (*state * 521 + 259) & 0xFFFF;
972     return (*state & 0x7FFF) * base >> 15;
973 }
974
975 static int estimate_sid_gain(G723_1_Context *p)
976 {
977     int i, shift, seg, seg2, t, val, val_add, x, y;
978
979     shift = 16 - p->cur_gain * 2;
980     if (shift > 0)
981         t = p->sid_gain << shift;
982     else
983         t = p->sid_gain >> -shift;
984     x = t * cng_filt[0] >> 16;
985
986     if (x >= cng_bseg[2])
987         return 0x3F;
988
989     if (x >= cng_bseg[1]) {
990         shift = 4;
991         seg   = 3;
992     } else {
993         shift = 3;
994         seg   = (x >= cng_bseg[0]);
995     }
996     seg2 = FFMIN(seg, 3);
997
998     val     = 1 << shift;
999     val_add = val >> 1;
1000     for (i = 0; i < shift; i++) {
1001         t = seg * 32 + (val << seg2);
1002         t *= t;
1003         if (x >= t)
1004             val += val_add;
1005         else
1006             val -= val_add;
1007         val_add >>= 1;
1008     }
1009
1010     t = seg * 32 + (val << seg2);
1011     y = t * t - x;
1012     if (y <= 0) {
1013         t = seg * 32 + (val + 1 << seg2);
1014         t = t * t - x;
1015         val = (seg2 - 1 << 4) + val;
1016         if (t >= y)
1017             val++;
1018     } else {
1019         t = seg * 32 + (val - 1 << seg2);
1020         t = t * t - x;
1021         val = (seg2 - 1 << 4) + val;
1022         if (t >= y)
1023             val--;
1024     }
1025
1026     return val;
1027 }
1028
1029 static void generate_noise(G723_1_Context *p)
1030 {
1031     int i, j, idx, t;
1032     int off[SUBFRAMES];
1033     int signs[SUBFRAMES / 2 * 11], pos[SUBFRAMES / 2 * 11];
1034     int tmp[SUBFRAME_LEN * 2];
1035     int16_t *vector_ptr;
1036     int64_t sum;
1037     int b0, c, delta, x, shift;
1038
1039     p->pitch_lag[0] = cng_rand(&p->cng_random_seed, 21) + 123;
1040     p->pitch_lag[1] = cng_rand(&p->cng_random_seed, 19) + 123;
1041
1042     for (i = 0; i < SUBFRAMES; i++) {
1043         p->subframe[i].ad_cb_gain = cng_rand(&p->cng_random_seed, 50) + 1;
1044         p->subframe[i].ad_cb_lag  = cng_adaptive_cb_lag[i];
1045     }
1046
1047     for (i = 0; i < SUBFRAMES / 2; i++) {
1048         t = cng_rand(&p->cng_random_seed, 1 << 13);
1049         off[i * 2]     =   t       & 1;
1050         off[i * 2 + 1] = ((t >> 1) & 1) + SUBFRAME_LEN;
1051         t >>= 2;
1052         for (j = 0; j < 11; j++) {
1053             signs[i * 11 + j] = (t & 1) * 2 - 1 << 14;
1054             t >>= 1;
1055         }
1056     }
1057
1058     idx = 0;
1059     for (i = 0; i < SUBFRAMES; i++) {
1060         for (j = 0; j < SUBFRAME_LEN / 2; j++)
1061             tmp[j] = j;
1062         t = SUBFRAME_LEN / 2;
1063         for (j = 0; j < pulses[i]; j++, idx++) {
1064             int idx2 = cng_rand(&p->cng_random_seed, t);
1065
1066             pos[idx]  = tmp[idx2] * 2 + off[i];
1067             tmp[idx2] = tmp[--t];
1068         }
1069     }
1070
1071     vector_ptr = p->audio + LPC_ORDER;
1072     memcpy(vector_ptr, p->prev_excitation,
1073            PITCH_MAX * sizeof(*p->excitation));
1074     for (i = 0; i < SUBFRAMES; i += 2) {
1075         gen_acb_excitation(vector_ptr, vector_ptr,
1076                            p->pitch_lag[i >> 1], &p->subframe[i],
1077                            p->cur_rate);
1078         gen_acb_excitation(vector_ptr + SUBFRAME_LEN,
1079                            vector_ptr + SUBFRAME_LEN,
1080                            p->pitch_lag[i >> 1], &p->subframe[i + 1],
1081                            p->cur_rate);
1082
1083         t = 0;
1084         for (j = 0; j < SUBFRAME_LEN * 2; j++)
1085             t |= FFABS(vector_ptr[j]);
1086         t = FFMIN(t, 0x7FFF);
1087         if (!t) {
1088             shift = 0;
1089         } else {
1090             shift = -10 + av_log2(t);
1091             if (shift < -2)
1092                 shift = -2;
1093         }
1094         sum = 0;
1095         if (shift < 0) {
1096            for (j = 0; j < SUBFRAME_LEN * 2; j++) {
1097                t      = vector_ptr[j] << -shift;
1098                sum   += t * t;
1099                tmp[j] = t;
1100            }
1101         } else {
1102            for (j = 0; j < SUBFRAME_LEN * 2; j++) {
1103                t      = vector_ptr[j] >> shift;
1104                sum   += t * t;
1105                tmp[j] = t;
1106            }
1107         }
1108
1109         b0 = 0;
1110         for (j = 0; j < 11; j++)
1111             b0 += tmp[pos[(i / 2) * 11 + j]] * signs[(i / 2) * 11 + j];
1112         b0 = b0 * 2 * 2979LL + (1 << 29) >> 30; // approximated division by 11
1113
1114         c = p->cur_gain * (p->cur_gain * SUBFRAME_LEN >> 5);
1115         if (shift * 2 + 3 >= 0)
1116             c >>= shift * 2 + 3;
1117         else
1118             c <<= -(shift * 2 + 3);
1119         c = (av_clipl_int32(sum << 1) - c) * 2979LL >> 15;
1120
1121         delta = b0 * b0 * 2 - c;
1122         if (delta <= 0) {
1123             x = -b0;
1124         } else {
1125             delta = square_root(delta);
1126             x     = delta - b0;
1127             t     = delta + b0;
1128             if (FFABS(t) < FFABS(x))
1129                 x = -t;
1130         }
1131         shift++;
1132         if (shift < 0)
1133            x >>= -shift;
1134         else
1135            x <<= shift;
1136         x = av_clip(x, -10000, 10000);
1137
1138         for (j = 0; j < 11; j++) {
1139             idx = (i / 2) * 11 + j;
1140             vector_ptr[pos[idx]] = av_clip_int16(vector_ptr[pos[idx]] +
1141                                                  (x * signs[idx] >> 15));
1142         }
1143
1144         /* copy decoded data to serve as a history for the next decoded subframes */
1145         memcpy(vector_ptr + PITCH_MAX, vector_ptr,
1146                sizeof(*vector_ptr) * SUBFRAME_LEN * 2);
1147         vector_ptr += SUBFRAME_LEN * 2;
1148     }
1149     /* Save the excitation for the next frame */
1150     memcpy(p->prev_excitation, p->audio + LPC_ORDER + FRAME_LEN,
1151            PITCH_MAX * sizeof(*p->excitation));
1152 }
1153
1154 static int g723_1_decode_frame(AVCodecContext *avctx, void *data,
1155                                int *got_frame_ptr, AVPacket *avpkt)
1156 {
1157     G723_1_Context *p  = avctx->priv_data;
1158     const uint8_t *buf = avpkt->data;
1159     int buf_size       = avpkt->size;
1160     int dec_mode       = buf[0] & 3;
1161
1162     PPFParam ppf[SUBFRAMES];
1163     int16_t cur_lsp[LPC_ORDER];
1164     int16_t lpc[SUBFRAMES * LPC_ORDER];
1165     int16_t acb_vector[SUBFRAME_LEN];
1166     int16_t *out;
1167     int bad_frame = 0, i, j, ret;
1168     int16_t *audio = p->audio;
1169
1170     if (buf_size < frame_size[dec_mode]) {
1171         if (buf_size)
1172             av_log(avctx, AV_LOG_WARNING,
1173                    "Expected %d bytes, got %d - skipping packet\n",
1174                    frame_size[dec_mode], buf_size);
1175         *got_frame_ptr = 0;
1176         return buf_size;
1177     }
1178
1179     if (unpack_bitstream(p, buf, buf_size) < 0) {
1180         bad_frame = 1;
1181         if (p->past_frame_type == ACTIVE_FRAME)
1182             p->cur_frame_type = ACTIVE_FRAME;
1183         else
1184             p->cur_frame_type = UNTRANSMITTED_FRAME;
1185     }
1186
1187     p->frame.nb_samples = FRAME_LEN;
1188     if ((ret = avctx->get_buffer(avctx, &p->frame)) < 0) {
1189         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1190         return ret;
1191     }
1192
1193     out = (int16_t *)p->frame.data[0];
1194
1195     if (p->cur_frame_type == ACTIVE_FRAME) {
1196         if (!bad_frame)
1197             p->erased_frames = 0;
1198         else if (p->erased_frames != 3)
1199             p->erased_frames++;
1200
1201         inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, bad_frame);
1202         lsp_interpolate(lpc, cur_lsp, p->prev_lsp);
1203
1204         /* Save the lsp_vector for the next frame */
1205         memcpy(p->prev_lsp, cur_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
1206
1207         /* Generate the excitation for the frame */
1208         memcpy(p->excitation, p->prev_excitation,
1209                PITCH_MAX * sizeof(*p->excitation));
1210         if (!p->erased_frames) {
1211             int16_t *vector_ptr = p->excitation + PITCH_MAX;
1212
1213             /* Update interpolation gain memory */
1214             p->interp_gain = fixed_cb_gain[(p->subframe[2].amp_index +
1215                                             p->subframe[3].amp_index) >> 1];
1216             for (i = 0; i < SUBFRAMES; i++) {
1217                 gen_fcb_excitation(vector_ptr, &p->subframe[i], p->cur_rate,
1218                                    p->pitch_lag[i >> 1], i);
1219                 gen_acb_excitation(acb_vector, &p->excitation[SUBFRAME_LEN * i],
1220                                    p->pitch_lag[i >> 1], &p->subframe[i],
1221                                    p->cur_rate);
1222                 /* Get the total excitation */
1223                 for (j = 0; j < SUBFRAME_LEN; j++) {
1224                     int v = av_clip_int16(vector_ptr[j] << 1);
1225                     vector_ptr[j] = av_clip_int16(v + acb_vector[j]);
1226                 }
1227                 vector_ptr += SUBFRAME_LEN;
1228             }
1229
1230             vector_ptr = p->excitation + PITCH_MAX;
1231
1232             p->interp_index = comp_interp_index(p, p->pitch_lag[1],
1233                                                 &p->sid_gain, &p->cur_gain);
1234
1235             /* Peform pitch postfiltering */
1236             if (p->postfilter) {
1237                 i = PITCH_MAX;
1238                 for (j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1239                     comp_ppf_coeff(p, i, p->pitch_lag[j >> 1],
1240                                    ppf + j, p->cur_rate);
1241
1242                 for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1243                     ff_acelp_weighted_vector_sum(p->audio + LPC_ORDER + i,
1244                                                  vector_ptr + i,
1245                                                  vector_ptr + i + ppf[j].index,
1246                                                  ppf[j].sc_gain,
1247                                                  ppf[j].opt_gain,
1248                                                  1 << 14, 15, SUBFRAME_LEN);
1249             } else {
1250                 audio = vector_ptr - LPC_ORDER;
1251             }
1252
1253             /* Save the excitation for the next frame */
1254             memcpy(p->prev_excitation, p->excitation + FRAME_LEN,
1255                    PITCH_MAX * sizeof(*p->excitation));
1256         } else {
1257             p->interp_gain = (p->interp_gain * 3 + 2) >> 2;
1258             if (p->erased_frames == 3) {
1259                 /* Mute output */
1260                 memset(p->excitation, 0,
1261                        (FRAME_LEN + PITCH_MAX) * sizeof(*p->excitation));
1262                 memset(p->prev_excitation, 0,
1263                        PITCH_MAX * sizeof(*p->excitation));
1264                 memset(p->frame.data[0], 0,
1265                        (FRAME_LEN + LPC_ORDER) * sizeof(int16_t));
1266             } else {
1267                 int16_t *buf = p->audio + LPC_ORDER;
1268
1269                 /* Regenerate frame */
1270                 residual_interp(p->excitation, buf, p->interp_index,
1271                                 p->interp_gain, &p->random_seed);
1272
1273                 /* Save the excitation for the next frame */
1274                 memcpy(p->prev_excitation, buf + (FRAME_LEN - PITCH_MAX),
1275                        PITCH_MAX * sizeof(*p->excitation));
1276             }
1277         }
1278         p->cng_random_seed = CNG_RANDOM_SEED;
1279     } else {
1280         if (p->cur_frame_type == SID_FRAME) {
1281             p->sid_gain = sid_gain_to_lsp_index(p->subframe[0].amp_index);
1282             inverse_quant(p->sid_lsp, p->prev_lsp, p->lsp_index, 0);
1283         } else if (p->past_frame_type == ACTIVE_FRAME) {
1284             p->sid_gain = estimate_sid_gain(p);
1285         }
1286
1287         if (p->past_frame_type == ACTIVE_FRAME)
1288             p->cur_gain = p->sid_gain;
1289         else
1290             p->cur_gain = (p->cur_gain * 7 + p->sid_gain) >> 3;
1291         generate_noise(p);
1292         lsp_interpolate(lpc, p->sid_lsp, p->prev_lsp);
1293         /* Save the lsp_vector for the next frame */
1294         memcpy(p->prev_lsp, p->sid_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
1295     }
1296
1297     p->past_frame_type = p->cur_frame_type;
1298
1299     memcpy(p->audio, p->synth_mem, LPC_ORDER * sizeof(*p->audio));
1300     for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1301         ff_celp_lp_synthesis_filter(p->audio + i, &lpc[j * LPC_ORDER],
1302                                     audio + i, SUBFRAME_LEN, LPC_ORDER,
1303                                     0, 1, 1 << 12);
1304     memcpy(p->synth_mem, p->audio + FRAME_LEN, LPC_ORDER * sizeof(*p->audio));
1305
1306     if (p->postfilter) {
1307         formant_postfilter(p, lpc, p->audio, out);
1308     } else { // if output is not postfiltered it should be scaled by 2
1309         for (i = 0; i < FRAME_LEN; i++)
1310             out[i] = av_clip_int16(p->audio[LPC_ORDER + i] << 1);
1311     }
1312
1313     *got_frame_ptr   = 1;
1314     *(AVFrame *)data = p->frame;
1315
1316     return frame_size[dec_mode];
1317 }
1318
1319 #define OFFSET(x) offsetof(G723_1_Context, x)
1320 #define AD     AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1321
1322 static const AVOption options[] = {
1323     { "postfilter", "postfilter on/off", OFFSET(postfilter), AV_OPT_TYPE_INT,
1324       { .i64 = 1 }, 0, 1, AD },
1325     { NULL }
1326 };
1327
1328
1329 static const AVClass g723_1dec_class = {
1330     .class_name = "G.723.1 decoder",
1331     .item_name  = av_default_item_name,
1332     .option     = options,
1333     .version    = LIBAVUTIL_VERSION_INT,
1334 };
1335
1336 AVCodec ff_g723_1_decoder = {
1337     .name           = "g723_1",
1338     .type           = AVMEDIA_TYPE_AUDIO,
1339     .id             = AV_CODEC_ID_G723_1,
1340     .priv_data_size = sizeof(G723_1_Context),
1341     .init           = g723_1_decode_init,
1342     .decode         = g723_1_decode_frame,
1343     .long_name      = NULL_IF_CONFIG_SMALL("G.723.1"),
1344     .capabilities   = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
1345     .priv_class     = &g723_1dec_class,
1346 };
1347
1348 #if CONFIG_G723_1_ENCODER
1349 #define BITSTREAM_WRITER_LE
1350 #include "put_bits.h"
1351
1352 static av_cold int g723_1_encode_init(AVCodecContext *avctx)
1353 {
1354     G723_1_Context *p = avctx->priv_data;
1355
1356     if (avctx->sample_rate != 8000) {
1357         av_log(avctx, AV_LOG_ERROR, "Only 8000Hz sample rate supported\n");
1358         return -1;
1359     }
1360
1361     if (avctx->channels != 1) {
1362         av_log(avctx, AV_LOG_ERROR, "Only mono supported\n");
1363         return AVERROR(EINVAL);
1364     }
1365
1366     if (avctx->bit_rate == 6300) {
1367         p->cur_rate = RATE_6300;
1368     } else if (avctx->bit_rate == 5300) {
1369         av_log(avctx, AV_LOG_ERROR, "Bitrate not supported yet, use 6.3k\n");
1370         return AVERROR_PATCHWELCOME;
1371     } else {
1372         av_log(avctx, AV_LOG_ERROR,
1373                "Bitrate not supported, use 6.3k\n");
1374         return AVERROR(EINVAL);
1375     }
1376     avctx->frame_size = 240;
1377     memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(int16_t));
1378
1379     return 0;
1380 }
1381
1382 /**
1383  * Remove DC component from the input signal.
1384  *
1385  * @param buf input signal
1386  * @param fir zero memory
1387  * @param iir pole memory
1388  */
1389 static void highpass_filter(int16_t *buf, int16_t *fir, int *iir)
1390 {
1391     int i;
1392     for (i = 0; i < FRAME_LEN; i++) {
1393         *iir   = (buf[i] << 15) + ((-*fir) << 15) + MULL2(*iir, 0x7f00);
1394         *fir   = buf[i];
1395         buf[i] = av_clipl_int32((int64_t)*iir + (1 << 15)) >> 16;
1396     }
1397 }
1398
1399 /**
1400  * Estimate autocorrelation of the input vector.
1401  *
1402  * @param buf      input buffer
1403  * @param autocorr autocorrelation coefficients vector
1404  */
1405 static void comp_autocorr(int16_t *buf, int16_t *autocorr)
1406 {
1407     int i, scale, temp;
1408     int16_t vector[LPC_FRAME];
1409
1410     scale_vector(vector, buf, LPC_FRAME);
1411
1412     /* Apply the Hamming window */
1413     for (i = 0; i < LPC_FRAME; i++)
1414         vector[i] = (vector[i] * hamming_window[i] + (1 << 14)) >> 15;
1415
1416     /* Compute the first autocorrelation coefficient */
1417     temp = ff_dot_product(vector, vector, LPC_FRAME);
1418
1419     /* Apply a white noise correlation factor of (1025/1024) */
1420     temp += temp >> 10;
1421
1422     /* Normalize */
1423     scale = normalize_bits_int32(temp);
1424     autocorr[0] = av_clipl_int32((int64_t)(temp << scale) +
1425                                  (1 << 15)) >> 16;
1426
1427     /* Compute the remaining coefficients */
1428     if (!autocorr[0]) {
1429         memset(autocorr + 1, 0, LPC_ORDER * sizeof(int16_t));
1430     } else {
1431         for (i = 1; i <= LPC_ORDER; i++) {
1432            temp = ff_dot_product(vector, vector + i, LPC_FRAME - i);
1433            temp = MULL2((temp << scale), binomial_window[i - 1]);
1434            autocorr[i] = av_clipl_int32((int64_t)temp + (1 << 15)) >> 16;
1435         }
1436     }
1437 }
1438
1439 /**
1440  * Use Levinson-Durbin recursion to compute LPC coefficients from
1441  * autocorrelation values.
1442  *
1443  * @param lpc      LPC coefficients vector
1444  * @param autocorr autocorrelation coefficients vector
1445  * @param error    prediction error
1446  */
1447 static void levinson_durbin(int16_t *lpc, int16_t *autocorr, int16_t error)
1448 {
1449     int16_t vector[LPC_ORDER];
1450     int16_t partial_corr;
1451     int i, j, temp;
1452
1453     memset(lpc, 0, LPC_ORDER * sizeof(int16_t));
1454
1455     for (i = 0; i < LPC_ORDER; i++) {
1456         /* Compute the partial correlation coefficient */
1457         temp = 0;
1458         for (j = 0; j < i; j++)
1459             temp -= lpc[j] * autocorr[i - j - 1];
1460         temp = ((autocorr[i] << 13) + temp) << 3;
1461
1462         if (FFABS(temp) >= (error << 16))
1463             break;
1464
1465         partial_corr = temp / (error << 1);
1466
1467         lpc[i] = av_clipl_int32((int64_t)(partial_corr << 14) +
1468                                 (1 << 15)) >> 16;
1469
1470         /* Update the prediction error */
1471         temp  = MULL2(temp, partial_corr);
1472         error = av_clipl_int32((int64_t)(error << 16) - temp +
1473                                 (1 << 15)) >> 16;
1474
1475         memcpy(vector, lpc, i * sizeof(int16_t));
1476         for (j = 0; j < i; j++) {
1477             temp = partial_corr * vector[i - j - 1] << 1;
1478             lpc[j] = av_clipl_int32((int64_t)(lpc[j] << 16) - temp +
1479                                     (1 << 15)) >> 16;
1480         }
1481     }
1482 }
1483
1484 /**
1485  * Calculate LPC coefficients for the current frame.
1486  *
1487  * @param buf       current frame
1488  * @param prev_data 2 trailing subframes of the previous frame
1489  * @param lpc       LPC coefficients vector
1490  */
1491 static void comp_lpc_coeff(int16_t *buf, int16_t *lpc)
1492 {
1493     int16_t autocorr[(LPC_ORDER + 1) * SUBFRAMES];
1494     int16_t *autocorr_ptr = autocorr;
1495     int16_t *lpc_ptr      = lpc;
1496     int i, j;
1497
1498     for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
1499         comp_autocorr(buf + i, autocorr_ptr);
1500         levinson_durbin(lpc_ptr, autocorr_ptr + 1, autocorr_ptr[0]);
1501
1502         lpc_ptr += LPC_ORDER;
1503         autocorr_ptr += LPC_ORDER + 1;
1504     }
1505 }
1506
1507 static void lpc2lsp(int16_t *lpc, int16_t *prev_lsp, int16_t *lsp)
1508 {
1509     int f[LPC_ORDER + 2]; ///< coefficients of the sum and difference
1510                           ///< polynomials (F1, F2) ordered as
1511                           ///< f1[0], f2[0], ...., f1[5], f2[5]
1512
1513     int max, shift, cur_val, prev_val, count, p;
1514     int i, j;
1515     int64_t temp;
1516
1517     /* Initialize f1[0] and f2[0] to 1 in Q25 */
1518     for (i = 0; i < LPC_ORDER; i++)
1519         lsp[i] = (lpc[i] * bandwidth_expand[i] + (1 << 14)) >> 15;
1520
1521     /* Apply bandwidth expansion on the LPC coefficients */
1522     f[0] = f[1] = 1 << 25;
1523
1524     /* Compute the remaining coefficients */
1525     for (i = 0; i < LPC_ORDER / 2; i++) {
1526         /* f1 */
1527         f[2 * i + 2] = -f[2 * i] - ((lsp[i] + lsp[LPC_ORDER - 1 - i]) << 12);
1528         /* f2 */
1529         f[2 * i + 3] = f[2 * i + 1] - ((lsp[i] - lsp[LPC_ORDER - 1 - i]) << 12);
1530     }
1531
1532     /* Divide f1[5] and f2[5] by 2 for use in polynomial evaluation */
1533     f[LPC_ORDER] >>= 1;
1534     f[LPC_ORDER + 1] >>= 1;
1535
1536     /* Normalize and shorten */
1537     max = FFABS(f[0]);
1538     for (i = 1; i < LPC_ORDER + 2; i++)
1539         max = FFMAX(max, FFABS(f[i]));
1540
1541     shift = normalize_bits_int32(max);
1542
1543     for (i = 0; i < LPC_ORDER + 2; i++)
1544         f[i] = av_clipl_int32((int64_t)(f[i] << shift) + (1 << 15)) >> 16;
1545
1546     /**
1547      * Evaluate F1 and F2 at uniform intervals of pi/256 along the
1548      * unit circle and check for zero crossings.
1549      */
1550     p    = 0;
1551     temp = 0;
1552     for (i = 0; i <= LPC_ORDER / 2; i++)
1553         temp += f[2 * i] * cos_tab[0];
1554     prev_val = av_clipl_int32(temp << 1);
1555     count    = 0;
1556     for ( i = 1; i < COS_TBL_SIZE / 2; i++) {
1557         /* Evaluate */
1558         temp = 0;
1559         for (j = 0; j <= LPC_ORDER / 2; j++)
1560             temp += f[LPC_ORDER - 2 * j + p] * cos_tab[i * j % COS_TBL_SIZE];
1561         cur_val = av_clipl_int32(temp << 1);
1562
1563         /* Check for sign change, indicating a zero crossing */
1564         if ((cur_val ^ prev_val) < 0) {
1565             int abs_cur  = FFABS(cur_val);
1566             int abs_prev = FFABS(prev_val);
1567             int sum      = abs_cur + abs_prev;
1568
1569             shift        = normalize_bits_int32(sum);
1570             sum          <<= shift;
1571             abs_prev     = abs_prev << shift >> 8;
1572             lsp[count++] = ((i - 1) << 7) + (abs_prev >> 1) / (sum >> 16);
1573
1574             if (count == LPC_ORDER)
1575                 break;
1576
1577             /* Switch between sum and difference polynomials */
1578             p ^= 1;
1579
1580             /* Evaluate */
1581             temp = 0;
1582             for (j = 0; j <= LPC_ORDER / 2; j++){
1583                 temp += f[LPC_ORDER - 2 * j + p] *
1584                         cos_tab[i * j % COS_TBL_SIZE];
1585             }
1586             cur_val = av_clipl_int32(temp<<1);
1587         }
1588         prev_val = cur_val;
1589     }
1590
1591     if (count != LPC_ORDER)
1592         memcpy(lsp, prev_lsp, LPC_ORDER * sizeof(int16_t));
1593 }
1594
1595 /**
1596  * Quantize the current LSP subvector.
1597  *
1598  * @param num    band number
1599  * @param offset offset of the current subvector in an LPC_ORDER vector
1600  * @param size   size of the current subvector
1601  */
1602 #define get_index(num, offset, size) \
1603 {\
1604     int error, max = -1;\
1605     int16_t temp[4];\
1606     int i, j;\
1607     for (i = 0; i < LSP_CB_SIZE; i++) {\
1608         for (j = 0; j < size; j++){\
1609             temp[j] = (weight[j + (offset)] * lsp_band##num[i][j] +\
1610                       (1 << 14)) >> 15;\
1611         }\
1612         error =  dot_product(lsp + (offset), temp, size) << 1;\
1613         error -= dot_product(lsp_band##num[i], temp, size);\
1614         if (error > max) {\
1615             max = error;\
1616             lsp_index[num] = i;\
1617         }\
1618     }\
1619 }
1620
1621 /**
1622  * Vector quantize the LSP frequencies.
1623  *
1624  * @param lsp      the current lsp vector
1625  * @param prev_lsp the previous lsp vector
1626  */
1627 static void lsp_quantize(uint8_t *lsp_index, int16_t *lsp, int16_t *prev_lsp)
1628 {
1629     int16_t weight[LPC_ORDER];
1630     int16_t min, max;
1631     int shift, i;
1632
1633     /* Calculate the VQ weighting vector */
1634     weight[0] = (1 << 20) / (lsp[1] - lsp[0]);
1635     weight[LPC_ORDER - 1] = (1 << 20) /
1636                             (lsp[LPC_ORDER - 1] - lsp[LPC_ORDER - 2]);
1637
1638     for (i = 1; i < LPC_ORDER - 1; i++) {
1639         min  = FFMIN(lsp[i] - lsp[i - 1], lsp[i + 1] - lsp[i]);
1640         if (min > 0x20)
1641             weight[i] = (1 << 20) / min;
1642         else
1643             weight[i] = INT16_MAX;
1644     }
1645
1646     /* Normalize */
1647     max = 0;
1648     for (i = 0; i < LPC_ORDER; i++)
1649         max = FFMAX(weight[i], max);
1650
1651     shift = normalize_bits_int16(max);
1652     for (i = 0; i < LPC_ORDER; i++) {
1653         weight[i] <<= shift;
1654     }
1655
1656     /* Compute the VQ target vector */
1657     for (i = 0; i < LPC_ORDER; i++) {
1658         lsp[i] -= dc_lsp[i] +
1659                   (((prev_lsp[i] - dc_lsp[i]) * 12288 + (1 << 14)) >> 15);
1660     }
1661
1662     get_index(0, 0, 3);
1663     get_index(1, 3, 3);
1664     get_index(2, 6, 4);
1665 }
1666
1667 /**
1668  * Apply the formant perceptual weighting filter.
1669  *
1670  * @param flt_coef filter coefficients
1671  * @param unq_lpc  unquantized lpc vector
1672  */
1673 static void perceptual_filter(G723_1_Context *p, int16_t *flt_coef,
1674                               int16_t *unq_lpc, int16_t *buf)
1675 {
1676     int16_t vector[FRAME_LEN + LPC_ORDER];
1677     int i, j, k, l = 0;
1678
1679     memcpy(buf, p->iir_mem, sizeof(int16_t) * LPC_ORDER);
1680     memcpy(vector, p->fir_mem, sizeof(int16_t) * LPC_ORDER);
1681     memcpy(vector + LPC_ORDER, buf + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
1682
1683     for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
1684         for (k = 0; k < LPC_ORDER; k++) {
1685             flt_coef[k + 2 * l] = (unq_lpc[k + l] * percept_flt_tbl[0][k] +
1686                                   (1 << 14)) >> 15;
1687             flt_coef[k + 2 * l + LPC_ORDER] = (unq_lpc[k + l] *
1688                                              percept_flt_tbl[1][k] +
1689                                              (1 << 14)) >> 15;
1690         }
1691         iir_filter(flt_coef + 2 * l, flt_coef + 2 * l + LPC_ORDER, vector + i,
1692                    buf + i, 0);
1693         l += LPC_ORDER;
1694     }
1695     memcpy(p->iir_mem, buf + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
1696     memcpy(p->fir_mem, vector + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
1697 }
1698
1699 /**
1700  * Estimate the open loop pitch period.
1701  *
1702  * @param buf   perceptually weighted speech
1703  * @param start estimation is carried out from this position
1704  */
1705 static int estimate_pitch(int16_t *buf, int start)
1706 {
1707     int max_exp = 32;
1708     int max_ccr = 0x4000;
1709     int max_eng = 0x7fff;
1710     int index   = PITCH_MIN;
1711     int offset  = start - PITCH_MIN + 1;
1712
1713     int ccr, eng, orig_eng, ccr_eng, exp;
1714     int diff, temp;
1715
1716     int i;
1717
1718     orig_eng = ff_dot_product(buf + offset, buf + offset, HALF_FRAME_LEN);
1719
1720     for (i = PITCH_MIN; i <= PITCH_MAX - 3; i++) {
1721         offset--;
1722
1723         /* Update energy and compute correlation */
1724         orig_eng += buf[offset] * buf[offset] -
1725                     buf[offset + HALF_FRAME_LEN] * buf[offset + HALF_FRAME_LEN];
1726         ccr      =  ff_dot_product(buf + start, buf + offset, HALF_FRAME_LEN);
1727         if (ccr <= 0)
1728             continue;
1729
1730         /* Split into mantissa and exponent to maintain precision */
1731         exp  =   normalize_bits_int32(ccr);
1732         ccr  =   av_clipl_int32((int64_t)(ccr << exp) + (1 << 15)) >> 16;
1733         exp  <<= 1;
1734         ccr  *=  ccr;
1735         temp =   normalize_bits_int32(ccr);
1736         ccr  =   ccr << temp >> 16;
1737         exp  +=  temp;
1738
1739         temp =   normalize_bits_int32(orig_eng);
1740         eng  =   av_clipl_int32((int64_t)(orig_eng << temp) + (1 << 15)) >> 16;
1741         exp  -=  temp;
1742
1743         if (ccr >= eng) {
1744             exp--;
1745             ccr >>= 1;
1746         }
1747         if (exp > max_exp)
1748             continue;
1749
1750         if (exp + 1 < max_exp)
1751             goto update;
1752
1753         /* Equalize exponents before comparison */
1754         if (exp + 1 == max_exp)
1755             temp = max_ccr >> 1;
1756         else
1757             temp = max_ccr;
1758         ccr_eng = ccr * max_eng;
1759         diff    = ccr_eng - eng * temp;
1760         if (diff > 0 && (i - index < PITCH_MIN || diff > ccr_eng >> 2)) {
1761 update:
1762             index   = i;
1763             max_exp = exp;
1764             max_ccr = ccr;
1765             max_eng = eng;
1766         }
1767     }
1768     return index;
1769 }
1770
1771 /**
1772  * Compute harmonic noise filter parameters.
1773  *
1774  * @param buf       perceptually weighted speech
1775  * @param pitch_lag open loop pitch period
1776  * @param hf        harmonic filter parameters
1777  */
1778 static void comp_harmonic_coeff(int16_t *buf, int16_t pitch_lag, HFParam *hf)
1779 {
1780     int ccr, eng, max_ccr, max_eng;
1781     int exp, max, diff;
1782     int energy[15];
1783     int i, j;
1784
1785     for (i = 0, j = pitch_lag - 3; j <= pitch_lag + 3; i++, j++) {
1786         /* Compute residual energy */
1787         energy[i << 1] = ff_dot_product(buf - j, buf - j, SUBFRAME_LEN);
1788         /* Compute correlation */
1789         energy[(i << 1) + 1] = ff_dot_product(buf, buf - j, SUBFRAME_LEN);
1790     }
1791
1792     /* Compute target energy */
1793     energy[14] = ff_dot_product(buf, buf, SUBFRAME_LEN);
1794
1795     /* Normalize */
1796     max = 0;
1797     for (i = 0; i < 15; i++)
1798         max = FFMAX(max, FFABS(energy[i]));
1799
1800     exp = normalize_bits_int32(max);
1801     for (i = 0; i < 15; i++) {
1802         energy[i] = av_clipl_int32((int64_t)(energy[i] << exp) +
1803                                    (1 << 15)) >> 16;
1804     }
1805
1806     hf->index = -1;
1807     hf->gain  =  0;
1808     max_ccr   =  1;
1809     max_eng   =  0x7fff;
1810
1811     for (i = 0; i <= 6; i++) {
1812         eng = energy[i << 1];
1813         ccr = energy[(i << 1) + 1];
1814
1815         if (ccr <= 0)
1816             continue;
1817
1818         ccr  = (ccr * ccr + (1 << 14)) >> 15;
1819         diff = ccr * max_eng - eng * max_ccr;
1820         if (diff > 0) {
1821             max_ccr   = ccr;
1822             max_eng   = eng;
1823             hf->index = i;
1824         }
1825     }
1826
1827     if (hf->index == -1) {
1828         hf->index = pitch_lag;
1829         return;
1830     }
1831
1832     eng = energy[14] * max_eng;
1833     eng = (eng >> 2) + (eng >> 3);
1834     ccr = energy[(hf->index << 1) + 1] * energy[(hf->index << 1) + 1];
1835     if (eng < ccr) {
1836         eng = energy[(hf->index << 1) + 1];
1837
1838         if (eng >= max_eng)
1839             hf->gain = 0x2800;
1840         else
1841             hf->gain = ((eng << 15) / max_eng * 0x2800 + (1 << 14)) >> 15;
1842     }
1843     hf->index += pitch_lag - 3;
1844 }
1845
1846 /**
1847  * Apply the harmonic noise shaping filter.
1848  *
1849  * @param hf filter parameters
1850  */
1851 static void harmonic_filter(HFParam *hf, const int16_t *src, int16_t *dest)
1852 {
1853     int i;
1854
1855     for (i = 0; i < SUBFRAME_LEN; i++) {
1856         int64_t temp = hf->gain * src[i - hf->index] << 1;
1857         dest[i] = av_clipl_int32((src[i] << 16) - temp + (1 << 15)) >> 16;
1858     }
1859 }
1860
1861 static void harmonic_noise_sub(HFParam *hf, const int16_t *src, int16_t *dest)
1862 {
1863     int i;
1864     for (i = 0; i < SUBFRAME_LEN; i++) {
1865         int64_t temp = hf->gain * src[i - hf->index] << 1;
1866         dest[i] = av_clipl_int32(((dest[i] - src[i]) << 16) + temp +
1867                                  (1 << 15)) >> 16;
1868
1869     }
1870 }
1871
1872 /**
1873  * Combined synthesis and formant perceptual weighting filer.
1874  *
1875  * @param qnt_lpc  quantized lpc coefficients
1876  * @param perf_lpc perceptual filter coefficients
1877  * @param perf_fir perceptual filter fir memory
1878  * @param perf_iir perceptual filter iir memory
1879  * @param scale    the filter output will be scaled by 2^scale
1880  */
1881 static void synth_percept_filter(int16_t *qnt_lpc, int16_t *perf_lpc,
1882                                  int16_t *perf_fir, int16_t *perf_iir,
1883                                  const int16_t *src, int16_t *dest, int scale)
1884 {
1885     int i, j;
1886     int16_t buf_16[SUBFRAME_LEN + LPC_ORDER];
1887     int64_t buf[SUBFRAME_LEN];
1888
1889     int16_t *bptr_16 = buf_16 + LPC_ORDER;
1890
1891     memcpy(buf_16, perf_fir, sizeof(int16_t) * LPC_ORDER);
1892     memcpy(dest - LPC_ORDER, perf_iir, sizeof(int16_t) * LPC_ORDER);
1893
1894     for (i = 0; i < SUBFRAME_LEN; i++) {
1895         int64_t temp = 0;
1896         for (j = 1; j <= LPC_ORDER; j++)
1897             temp -= qnt_lpc[j - 1] * bptr_16[i - j];
1898
1899         buf[i]     = (src[i] << 15) + (temp << 3);
1900         bptr_16[i] = av_clipl_int32(buf[i] + (1 << 15)) >> 16;
1901     }
1902
1903     for (i = 0; i < SUBFRAME_LEN; i++) {
1904         int64_t fir = 0, iir = 0;
1905         for (j = 1; j <= LPC_ORDER; j++) {
1906             fir -= perf_lpc[j - 1] * bptr_16[i - j];
1907             iir += perf_lpc[j + LPC_ORDER - 1] * dest[i - j];
1908         }
1909         dest[i] = av_clipl_int32(((buf[i] + (fir << 3)) << scale) + (iir << 3) +
1910                                  (1 << 15)) >> 16;
1911     }
1912     memcpy(perf_fir, buf_16 + SUBFRAME_LEN, sizeof(int16_t) * LPC_ORDER);
1913     memcpy(perf_iir, dest + SUBFRAME_LEN - LPC_ORDER,
1914            sizeof(int16_t) * LPC_ORDER);
1915 }
1916
1917 /**
1918  * Compute the adaptive codebook contribution.
1919  *
1920  * @param buf   input signal
1921  * @param index the current subframe index
1922  */
1923 static void acb_search(G723_1_Context *p, int16_t *residual,
1924                        int16_t *impulse_resp, const int16_t *buf,
1925                        int index)
1926 {
1927
1928     int16_t flt_buf[PITCH_ORDER][SUBFRAME_LEN];
1929
1930     const int16_t *cb_tbl = adaptive_cb_gain85;
1931
1932     int ccr_buf[PITCH_ORDER * SUBFRAMES << 2];
1933
1934     int pitch_lag = p->pitch_lag[index >> 1];
1935     int acb_lag   = 1;
1936     int acb_gain  = 0;
1937     int odd_frame = index & 1;
1938     int iter      = 3 + odd_frame;
1939     int count     = 0;
1940     int tbl_size  = 85;
1941
1942     int i, j, k, l, max;
1943     int64_t temp;
1944
1945     if (!odd_frame) {
1946         if (pitch_lag == PITCH_MIN)
1947             pitch_lag++;
1948         else
1949             pitch_lag = FFMIN(pitch_lag, PITCH_MAX - 5);
1950     }
1951
1952     for (i = 0; i < iter; i++) {
1953         get_residual(residual, p->prev_excitation, pitch_lag + i - 1);
1954
1955         for (j = 0; j < SUBFRAME_LEN; j++) {
1956             temp = 0;
1957             for (k = 0; k <= j; k++)
1958                 temp += residual[PITCH_ORDER - 1 + k] * impulse_resp[j - k];
1959             flt_buf[PITCH_ORDER - 1][j] = av_clipl_int32((temp << 1) +
1960                                                          (1 << 15)) >> 16;
1961         }
1962
1963         for (j = PITCH_ORDER - 2; j >= 0; j--) {
1964             flt_buf[j][0] = ((residual[j] << 13) + (1 << 14)) >> 15;
1965             for (k = 1; k < SUBFRAME_LEN; k++) {
1966                 temp = (flt_buf[j + 1][k - 1] << 15) +
1967                        residual[j] * impulse_resp[k];
1968                 flt_buf[j][k] = av_clipl_int32((temp << 1) + (1 << 15)) >> 16;
1969             }
1970         }
1971
1972         /* Compute crosscorrelation with the signal */
1973         for (j = 0; j < PITCH_ORDER; j++) {
1974             temp = ff_dot_product(buf, flt_buf[j], SUBFRAME_LEN);
1975             ccr_buf[count++] = av_clipl_int32(temp << 1);
1976         }
1977
1978         /* Compute energies */
1979         for (j = 0; j < PITCH_ORDER; j++) {
1980             ccr_buf[count++] = dot_product(flt_buf[j], flt_buf[j],
1981                                            SUBFRAME_LEN);
1982         }
1983
1984         for (j = 1; j < PITCH_ORDER; j++) {
1985             for (k = 0; k < j; k++) {
1986                 temp = ff_dot_product(flt_buf[j], flt_buf[k], SUBFRAME_LEN);
1987                 ccr_buf[count++] = av_clipl_int32(temp<<2);
1988             }
1989         }
1990     }
1991
1992     /* Normalize and shorten */
1993     max = 0;
1994     for (i = 0; i < 20 * iter; i++)
1995         max = FFMAX(max, FFABS(ccr_buf[i]));
1996
1997     temp = normalize_bits_int32(max);
1998
1999     for (i = 0; i < 20 * iter; i++){
2000         ccr_buf[i] = av_clipl_int32((int64_t)(ccr_buf[i] << temp) +
2001                                     (1 << 15)) >> 16;
2002     }
2003
2004     max = 0;
2005     for (i = 0; i < iter; i++) {
2006         /* Select quantization table */
2007         if (!odd_frame && pitch_lag + i - 1 >= SUBFRAME_LEN - 2 ||
2008             odd_frame && pitch_lag >= SUBFRAME_LEN - 2) {
2009             cb_tbl = adaptive_cb_gain170;
2010             tbl_size = 170;
2011         }
2012
2013         for (j = 0, k = 0; j < tbl_size; j++, k += 20) {
2014             temp = 0;
2015             for (l = 0; l < 20; l++)
2016                 temp += ccr_buf[20 * i + l] * cb_tbl[k + l];
2017             temp =  av_clipl_int32(temp);
2018
2019             if (temp > max) {
2020                 max      = temp;
2021                 acb_gain = j;
2022                 acb_lag  = i;
2023             }
2024         }
2025     }
2026
2027     if (!odd_frame) {
2028         pitch_lag += acb_lag - 1;
2029         acb_lag   =  1;
2030     }
2031
2032     p->pitch_lag[index >> 1]      = pitch_lag;
2033     p->subframe[index].ad_cb_lag  = acb_lag;
2034     p->subframe[index].ad_cb_gain = acb_gain;
2035 }
2036
2037 /**
2038  * Subtract the adaptive codebook contribution from the input
2039  * to obtain the residual.
2040  *
2041  * @param buf target vector
2042  */
2043 static void sub_acb_contrib(const int16_t *residual, const int16_t *impulse_resp,
2044                             int16_t *buf)
2045 {
2046     int i, j;
2047     /* Subtract adaptive CB contribution to obtain the residual */
2048     for (i = 0; i < SUBFRAME_LEN; i++) {
2049         int64_t temp = buf[i] << 14;
2050         for (j = 0; j <= i; j++)
2051             temp -= residual[j] * impulse_resp[i - j];
2052
2053         buf[i] = av_clipl_int32((temp << 2) + (1 << 15)) >> 16;
2054     }
2055 }
2056
2057 /**
2058  * Quantize the residual signal using the fixed codebook (MP-MLQ).
2059  *
2060  * @param optim optimized fixed codebook parameters
2061  * @param buf   excitation vector
2062  */
2063 static void get_fcb_param(FCBParam *optim, int16_t *impulse_resp,
2064                           int16_t *buf, int pulse_cnt, int pitch_lag)
2065 {
2066     FCBParam param;
2067     int16_t impulse_r[SUBFRAME_LEN];
2068     int16_t temp_corr[SUBFRAME_LEN];
2069     int16_t impulse_corr[SUBFRAME_LEN];
2070
2071     int ccr1[SUBFRAME_LEN];
2072     int ccr2[SUBFRAME_LEN];
2073     int amp, err, max, max_amp_index, min, scale, i, j, k, l;
2074
2075     int64_t temp;
2076
2077     /* Update impulse response */
2078     memcpy(impulse_r, impulse_resp, sizeof(int16_t) * SUBFRAME_LEN);
2079     param.dirac_train = 0;
2080     if (pitch_lag < SUBFRAME_LEN - 2) {
2081         param.dirac_train = 1;
2082         gen_dirac_train(impulse_r, pitch_lag);
2083     }
2084
2085     for (i = 0; i < SUBFRAME_LEN; i++)
2086         temp_corr[i] = impulse_r[i] >> 1;
2087
2088     /* Compute impulse response autocorrelation */
2089     temp = dot_product(temp_corr, temp_corr, SUBFRAME_LEN);
2090
2091     scale = normalize_bits_int32(temp);
2092     impulse_corr[0] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
2093
2094     for (i = 1; i < SUBFRAME_LEN; i++) {
2095         temp = dot_product(temp_corr + i, temp_corr, SUBFRAME_LEN - i);
2096         impulse_corr[i] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
2097     }
2098
2099     /* Compute crosscorrelation of impulse response with residual signal */
2100     scale -= 4;
2101     for (i = 0; i < SUBFRAME_LEN; i++){
2102         temp = dot_product(buf + i, impulse_r, SUBFRAME_LEN - i);
2103         if (scale < 0)
2104             ccr1[i] = temp >> -scale;
2105         else
2106             ccr1[i] = av_clipl_int32(temp << scale);
2107     }
2108
2109     /* Search loop */
2110     for (i = 0; i < GRID_SIZE; i++) {
2111         /* Maximize the crosscorrelation */
2112         max = 0;
2113         for (j = i; j < SUBFRAME_LEN; j += GRID_SIZE) {
2114             temp = FFABS(ccr1[j]);
2115             if (temp >= max) {
2116                 max = temp;
2117                 param.pulse_pos[0] = j;
2118             }
2119         }
2120
2121         /* Quantize the gain (max crosscorrelation/impulse_corr[0]) */
2122         amp = max;
2123         min = 1 << 30;
2124         max_amp_index = GAIN_LEVELS - 2;
2125         for (j = max_amp_index; j >= 2; j--) {
2126             temp = av_clipl_int32((int64_t)fixed_cb_gain[j] *
2127                                   impulse_corr[0] << 1);
2128             temp = FFABS(temp - amp);
2129             if (temp < min) {
2130                 min = temp;
2131                 max_amp_index = j;
2132             }
2133         }
2134
2135         max_amp_index--;
2136         /* Select additional gain values */
2137         for (j = 1; j < 5; j++) {
2138             for (k = i; k < SUBFRAME_LEN; k += GRID_SIZE) {
2139                 temp_corr[k] = 0;
2140                 ccr2[k]      = ccr1[k];
2141             }
2142             param.amp_index = max_amp_index + j - 2;
2143             amp = fixed_cb_gain[param.amp_index];
2144
2145             param.pulse_sign[0] = (ccr2[param.pulse_pos[0]] < 0) ? -amp : amp;
2146             temp_corr[param.pulse_pos[0]] = 1;
2147
2148             for (k = 1; k < pulse_cnt; k++) {
2149                 max = -1 << 30;
2150                 for (l = i; l < SUBFRAME_LEN; l += GRID_SIZE) {
2151                     if (temp_corr[l])
2152                         continue;
2153                     temp = impulse_corr[FFABS(l - param.pulse_pos[k - 1])];
2154                     temp = av_clipl_int32((int64_t)temp *
2155                                           param.pulse_sign[k - 1] << 1);
2156                     ccr2[l] -= temp;
2157                     temp = FFABS(ccr2[l]);
2158                     if (temp > max) {
2159                         max = temp;
2160                         param.pulse_pos[k] = l;
2161                     }
2162                 }
2163
2164                 param.pulse_sign[k] = (ccr2[param.pulse_pos[k]] < 0) ?
2165                                       -amp : amp;
2166                 temp_corr[param.pulse_pos[k]] = 1;
2167             }
2168
2169             /* Create the error vector */
2170             memset(temp_corr, 0, sizeof(int16_t) * SUBFRAME_LEN);
2171
2172             for (k = 0; k < pulse_cnt; k++)
2173                 temp_corr[param.pulse_pos[k]] = param.pulse_sign[k];
2174
2175             for (k = SUBFRAME_LEN - 1; k >= 0; k--) {
2176                 temp = 0;
2177                 for (l = 0; l <= k; l++) {
2178                     int prod = av_clipl_int32((int64_t)temp_corr[l] *
2179                                               impulse_r[k - l] << 1);
2180                     temp     = av_clipl_int32(temp + prod);
2181                 }
2182                 temp_corr[k] = temp << 2 >> 16;
2183             }
2184
2185             /* Compute square of error */
2186             err = 0;
2187             for (k = 0; k < SUBFRAME_LEN; k++) {
2188                 int64_t prod;
2189                 prod = av_clipl_int32((int64_t)buf[k] * temp_corr[k] << 1);
2190                 err  = av_clipl_int32(err - prod);
2191                 prod = av_clipl_int32((int64_t)temp_corr[k] * temp_corr[k]);
2192                 err  = av_clipl_int32(err + prod);
2193             }
2194
2195             /* Minimize */
2196             if (err < optim->min_err) {
2197                 optim->min_err     = err;
2198                 optim->grid_index  = i;
2199                 optim->amp_index   = param.amp_index;
2200                 optim->dirac_train = param.dirac_train;
2201
2202                 for (k = 0; k < pulse_cnt; k++) {
2203                     optim->pulse_sign[k] = param.pulse_sign[k];
2204                     optim->pulse_pos[k]  = param.pulse_pos[k];
2205                 }
2206             }
2207         }
2208     }
2209 }
2210
2211 /**
2212  * Encode the pulse position and gain of the current subframe.
2213  *
2214  * @param optim optimized fixed CB parameters
2215  * @param buf   excitation vector
2216  */
2217 static void pack_fcb_param(G723_1_Subframe *subfrm, FCBParam *optim,
2218                            int16_t *buf, int pulse_cnt)
2219 {
2220     int i, j;
2221
2222     j = PULSE_MAX - pulse_cnt;
2223
2224     subfrm->pulse_sign = 0;
2225     subfrm->pulse_pos  = 0;
2226
2227     for (i = 0; i < SUBFRAME_LEN >> 1; i++) {
2228         int val = buf[optim->grid_index + (i << 1)];
2229         if (!val) {
2230             subfrm->pulse_pos += combinatorial_table[j][i];
2231         } else {
2232             subfrm->pulse_sign <<= 1;
2233             if (val < 0) subfrm->pulse_sign++;
2234             j++;
2235
2236             if (j == PULSE_MAX) break;
2237         }
2238     }
2239     subfrm->amp_index   = optim->amp_index;
2240     subfrm->grid_index  = optim->grid_index;
2241     subfrm->dirac_train = optim->dirac_train;
2242 }
2243
2244 /**
2245  * Compute the fixed codebook excitation.
2246  *
2247  * @param buf          target vector
2248  * @param impulse_resp impulse response of the combined filter
2249  */
2250 static void fcb_search(G723_1_Context *p, int16_t *impulse_resp,
2251                        int16_t *buf, int index)
2252 {
2253     FCBParam optim;
2254     int pulse_cnt = pulses[index];
2255     int i;
2256
2257     optim.min_err = 1 << 30;
2258     get_fcb_param(&optim, impulse_resp, buf, pulse_cnt, SUBFRAME_LEN);
2259
2260     if (p->pitch_lag[index >> 1] < SUBFRAME_LEN - 2) {
2261         get_fcb_param(&optim, impulse_resp, buf, pulse_cnt,
2262                       p->pitch_lag[index >> 1]);
2263     }
2264
2265     /* Reconstruct the excitation */
2266     memset(buf, 0, sizeof(int16_t) * SUBFRAME_LEN);
2267     for (i = 0; i < pulse_cnt; i++)
2268         buf[optim.pulse_pos[i]] = optim.pulse_sign[i];
2269
2270     pack_fcb_param(&p->subframe[index], &optim, buf, pulse_cnt);
2271
2272     if (optim.dirac_train)
2273         gen_dirac_train(buf, p->pitch_lag[index >> 1]);
2274 }
2275
2276 /**
2277  * Pack the frame parameters into output bitstream.
2278  *
2279  * @param frame output buffer
2280  * @param size  size of the buffer
2281  */
2282 static int pack_bitstream(G723_1_Context *p, unsigned char *frame, int size)
2283 {
2284     PutBitContext pb;
2285     int info_bits, i, temp;
2286
2287     init_put_bits(&pb, frame, size);
2288
2289     if (p->cur_rate == RATE_6300) {
2290         info_bits = 0;
2291         put_bits(&pb, 2, info_bits);
2292     }
2293
2294     put_bits(&pb, 8, p->lsp_index[2]);
2295     put_bits(&pb, 8, p->lsp_index[1]);
2296     put_bits(&pb, 8, p->lsp_index[0]);
2297
2298     put_bits(&pb, 7, p->pitch_lag[0] - PITCH_MIN);
2299     put_bits(&pb, 2, p->subframe[1].ad_cb_lag);
2300     put_bits(&pb, 7, p->pitch_lag[1] - PITCH_MIN);
2301     put_bits(&pb, 2, p->subframe[3].ad_cb_lag);
2302
2303     /* Write 12 bit combined gain */
2304     for (i = 0; i < SUBFRAMES; i++) {
2305         temp = p->subframe[i].ad_cb_gain * GAIN_LEVELS +
2306                p->subframe[i].amp_index;
2307         if (p->cur_rate ==  RATE_6300)
2308             temp += p->subframe[i].dirac_train << 11;
2309         put_bits(&pb, 12, temp);
2310     }
2311
2312     put_bits(&pb, 1, p->subframe[0].grid_index);
2313     put_bits(&pb, 1, p->subframe[1].grid_index);
2314     put_bits(&pb, 1, p->subframe[2].grid_index);
2315     put_bits(&pb, 1, p->subframe[3].grid_index);
2316
2317     if (p->cur_rate == RATE_6300) {
2318         skip_put_bits(&pb, 1); /* reserved bit */
2319
2320         /* Write 13 bit combined position index */
2321         temp = (p->subframe[0].pulse_pos >> 16) * 810 +
2322                (p->subframe[1].pulse_pos >> 14) *  90 +
2323                (p->subframe[2].pulse_pos >> 16) *   9 +
2324                (p->subframe[3].pulse_pos >> 14);
2325         put_bits(&pb, 13, temp);
2326
2327         put_bits(&pb, 16, p->subframe[0].pulse_pos & 0xffff);
2328         put_bits(&pb, 14, p->subframe[1].pulse_pos & 0x3fff);
2329         put_bits(&pb, 16, p->subframe[2].pulse_pos & 0xffff);
2330         put_bits(&pb, 14, p->subframe[3].pulse_pos & 0x3fff);
2331
2332         put_bits(&pb, 6, p->subframe[0].pulse_sign);
2333         put_bits(&pb, 5, p->subframe[1].pulse_sign);
2334         put_bits(&pb, 6, p->subframe[2].pulse_sign);
2335         put_bits(&pb, 5, p->subframe[3].pulse_sign);
2336     }
2337
2338     flush_put_bits(&pb);
2339     return frame_size[info_bits];
2340 }
2341
2342 static int g723_1_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
2343                             const AVFrame *frame, int *got_packet_ptr)
2344 {
2345     G723_1_Context *p = avctx->priv_data;
2346     int16_t unq_lpc[LPC_ORDER * SUBFRAMES];
2347     int16_t qnt_lpc[LPC_ORDER * SUBFRAMES];
2348     int16_t cur_lsp[LPC_ORDER];
2349     int16_t weighted_lpc[LPC_ORDER * SUBFRAMES << 1];
2350     int16_t vector[FRAME_LEN + PITCH_MAX];
2351     int offset, ret;
2352     int16_t *in = (const int16_t *)frame->data[0];
2353
2354     HFParam hf[4];
2355     int i, j;
2356
2357     highpass_filter(in, &p->hpf_fir_mem, &p->hpf_iir_mem);
2358
2359     memcpy(vector, p->prev_data, HALF_FRAME_LEN * sizeof(int16_t));
2360     memcpy(vector + HALF_FRAME_LEN, in, FRAME_LEN * sizeof(int16_t));
2361
2362     comp_lpc_coeff(vector, unq_lpc);
2363     lpc2lsp(&unq_lpc[LPC_ORDER * 3], p->prev_lsp, cur_lsp);
2364     lsp_quantize(p->lsp_index, cur_lsp, p->prev_lsp);
2365
2366     /* Update memory */
2367     memcpy(vector + LPC_ORDER, p->prev_data + SUBFRAME_LEN,
2368            sizeof(int16_t) * SUBFRAME_LEN);
2369     memcpy(vector + LPC_ORDER + SUBFRAME_LEN, in,
2370            sizeof(int16_t) * (HALF_FRAME_LEN + SUBFRAME_LEN));
2371     memcpy(p->prev_data, in + HALF_FRAME_LEN,
2372            sizeof(int16_t) * HALF_FRAME_LEN);
2373     memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
2374
2375     perceptual_filter(p, weighted_lpc, unq_lpc, vector);
2376
2377     memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
2378     memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
2379     memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
2380
2381     scale_vector(vector, vector, FRAME_LEN + PITCH_MAX);
2382
2383     p->pitch_lag[0] = estimate_pitch(vector, PITCH_MAX);
2384     p->pitch_lag[1] = estimate_pitch(vector, PITCH_MAX + HALF_FRAME_LEN);
2385
2386     for (i = PITCH_MAX, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
2387         comp_harmonic_coeff(vector + i, p->pitch_lag[j >> 1], hf + j);
2388
2389     memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
2390     memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
2391     memcpy(p->prev_weight_sig, vector + FRAME_LEN, sizeof(int16_t) * PITCH_MAX);
2392
2393     for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
2394         harmonic_filter(hf + j, vector + PITCH_MAX + i, in + i);
2395
2396     inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, 0);
2397     lsp_interpolate(qnt_lpc, cur_lsp, p->prev_lsp);
2398
2399     memcpy(p->prev_lsp, cur_lsp, sizeof(int16_t) * LPC_ORDER);
2400
2401     offset = 0;
2402     for (i = 0; i < SUBFRAMES; i++) {
2403         int16_t impulse_resp[SUBFRAME_LEN];
2404         int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
2405         int16_t flt_in[SUBFRAME_LEN];
2406         int16_t zero[LPC_ORDER], fir[LPC_ORDER], iir[LPC_ORDER];
2407
2408         /**
2409          * Compute the combined impulse response of the synthesis filter,
2410          * formant perceptual weighting filter and harmonic noise shaping filter
2411          */
2412         memset(zero, 0, sizeof(int16_t) * LPC_ORDER);
2413         memset(vector, 0, sizeof(int16_t) * PITCH_MAX);
2414         memset(flt_in, 0, sizeof(int16_t) * SUBFRAME_LEN);
2415
2416         flt_in[0] = 1 << 13; /* Unit impulse */
2417         synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
2418                              zero, zero, flt_in, vector + PITCH_MAX, 1);
2419         harmonic_filter(hf + i, vector + PITCH_MAX, impulse_resp);
2420
2421          /* Compute the combined zero input response */
2422         flt_in[0] = 0;
2423         memcpy(fir, p->perf_fir_mem, sizeof(int16_t) * LPC_ORDER);
2424         memcpy(iir, p->perf_iir_mem, sizeof(int16_t) * LPC_ORDER);
2425
2426         synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
2427                              fir, iir, flt_in, vector + PITCH_MAX, 0);
2428         memcpy(vector, p->harmonic_mem, sizeof(int16_t) * PITCH_MAX);
2429         harmonic_noise_sub(hf + i, vector + PITCH_MAX, in);
2430
2431         acb_search(p, residual, impulse_resp, in, i);
2432         gen_acb_excitation(residual, p->prev_excitation,p->pitch_lag[i >> 1],
2433                            &p->subframe[i], p->cur_rate);
2434         sub_acb_contrib(residual, impulse_resp, in);
2435
2436         fcb_search(p, impulse_resp, in, i);
2437
2438         /* Reconstruct the excitation */
2439         gen_acb_excitation(impulse_resp, p->prev_excitation, p->pitch_lag[i >> 1],
2440                            &p->subframe[i], RATE_6300);
2441
2442         memmove(p->prev_excitation, p->prev_excitation + SUBFRAME_LEN,
2443                sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
2444         for (j = 0; j < SUBFRAME_LEN; j++)
2445             in[j] = av_clip_int16((in[j] << 1) + impulse_resp[j]);
2446         memcpy(p->prev_excitation + PITCH_MAX - SUBFRAME_LEN, in,
2447                sizeof(int16_t) * SUBFRAME_LEN);
2448
2449         /* Update filter memories */
2450         synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
2451                              p->perf_fir_mem, p->perf_iir_mem,
2452                              in, vector + PITCH_MAX, 0);
2453         memmove(p->harmonic_mem, p->harmonic_mem + SUBFRAME_LEN,
2454                 sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
2455         memcpy(p->harmonic_mem + PITCH_MAX - SUBFRAME_LEN, vector + PITCH_MAX,
2456                sizeof(int16_t) * SUBFRAME_LEN);
2457
2458         in += SUBFRAME_LEN;
2459         offset += LPC_ORDER;
2460     }
2461
2462     if ((ret = ff_alloc_packet2(avctx, avpkt, 24)))
2463         return ret;
2464
2465     *got_packet_ptr = 1;
2466     avpkt->size = pack_bitstream(p, avpkt->data, avpkt->size);
2467     return 0;
2468 }
2469
2470 AVCodec ff_g723_1_encoder = {
2471     .name           = "g723_1",
2472     .type           = AVMEDIA_TYPE_AUDIO,
2473     .id             = AV_CODEC_ID_G723_1,
2474     .priv_data_size = sizeof(G723_1_Context),
2475     .init           = g723_1_encode_init,
2476     .encode2        = g723_1_encode_frame,
2477     .long_name      = NULL_IF_CONFIG_SMALL("G.723.1"),
2478     .sample_fmts    = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,
2479                                                     AV_SAMPLE_FMT_NONE},
2480 };
2481 #endif