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