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