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