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