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