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