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