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