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