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