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