]> git.sesse.net Git - ffmpeg/blob - libavcodec/g723_1.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / g723_1.c
1 /*
2  * G.723.1 compatible decoder
3  * Copyright (c) 2006 Benjamin Larsson
4  * Copyright (c) 2010 Mohamed Naufal Basheer
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * G.723.1 compatible decoder
26  */
27
28 #include "avcodec.h"
29 #define ALT_BITSTREAM_READER_LE
30 #include "get_bits.h"
31 #include "acelp_vectors.h"
32 #include "celp_filters.h"
33 #include "celp_math.h"
34 #include "lsp.h"
35 #include "libavutil/lzo.h"
36 #include "g723_1_data.h"
37
38 typedef struct g723_1_context {
39     G723_1_Subframe subframe[4];
40     FrameType cur_frame_type;
41     FrameType past_frame_type;
42     Rate cur_rate;
43     uint8_t lsp_index[LSP_BANDS];
44     int pitch_lag[2];
45     int erased_frames;
46
47     int16_t prev_lsp[LPC_ORDER];
48     int16_t prev_excitation[PITCH_MAX];
49     int16_t excitation[PITCH_MAX + FRAME_LEN];
50     int16_t synth_mem[LPC_ORDER];
51     int16_t fir_mem[LPC_ORDER];
52     int     iir_mem[LPC_ORDER];
53
54     int random_seed;
55     int interp_index;
56     int interp_gain;
57     int sid_gain;
58     int cur_gain;
59     int reflection_coef;
60     int pf_gain;                 ///< formant postfilter
61                                  ///< gain scaling unit memory
62 } G723_1_Context;
63
64 static av_cold int g723_1_decode_init(AVCodecContext *avctx)
65 {
66     G723_1_Context *p  = avctx->priv_data;
67
68     avctx->sample_fmt  = SAMPLE_FMT_S16;
69     p->pf_gain         = 1 << 12;
70     memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(int16_t));
71
72     return 0;
73 }
74
75 /**
76  * Unpack the frame into parameters.
77  *
78  * @param p           the context
79  * @param buf         pointer to the input buffer
80  * @param buf_size    size of the input buffer
81  */
82 static int unpack_bitstream(G723_1_Context *p, const uint8_t *buf,
83                             int buf_size)
84 {
85     GetBitContext gb;
86     int ad_cb_len;
87     int temp, info_bits, i;
88
89     init_get_bits(&gb, buf, buf_size * 8);
90
91     /* Extract frame type and rate info */
92     info_bits = get_bits(&gb, 2);
93
94     if (info_bits == 3) {
95         p->cur_frame_type = UntransmittedFrame;
96         return 0;
97     }
98
99     /* Extract 24 bit lsp indices, 8 bit for each band */
100     p->lsp_index[2] = get_bits(&gb, 8);
101     p->lsp_index[1] = get_bits(&gb, 8);
102     p->lsp_index[0] = get_bits(&gb, 8);
103
104     if (info_bits == 2) {
105         p->cur_frame_type = SIDFrame;
106         p->subframe[0].amp_index = get_bits(&gb, 6);
107         return 0;
108     }
109
110     /* Extract the info common to both rates */
111     p->cur_rate       = info_bits ? Rate5k3 : Rate6k3;
112     p->cur_frame_type = ActiveFrame;
113
114     p->pitch_lag[0] = get_bits(&gb, 7);
115     if (p->pitch_lag[0] > 123)       /* test if forbidden code */
116         return -1;
117     p->pitch_lag[0] += PITCH_MIN;
118     p->subframe[1].ad_cb_lag = get_bits(&gb, 2);
119
120     p->pitch_lag[1] = get_bits(&gb, 7);
121     if (p->pitch_lag[1] > 123)
122         return -1;
123     p->pitch_lag[1] += PITCH_MIN;
124     p->subframe[3].ad_cb_lag = get_bits(&gb, 2);
125     p->subframe[0].ad_cb_lag = 1;
126     p->subframe[2].ad_cb_lag = 1;
127
128     for (i = 0; i < SUBFRAMES; i++) {
129         /* Extract combined gain */
130         temp = get_bits(&gb, 12);
131         ad_cb_len = 170;
132         p->subframe[i].dirac_train = 0;
133         if (p->cur_rate == Rate6k3 && p->pitch_lag[i >> 1] < SUBFRAME_LEN - 2) {
134             p->subframe[i].dirac_train = temp >> 11;
135             temp &= 0x7ff;
136             ad_cb_len = 85;
137         }
138         p->subframe[i].ad_cb_gain = FASTDIV(temp, GAIN_LEVELS);
139         if (p->subframe[i].ad_cb_gain < ad_cb_len) {
140             p->subframe[i].amp_index = temp - p->subframe[i].ad_cb_gain *
141                                        GAIN_LEVELS;
142         } else {
143             return -1;
144         }
145     }
146
147     p->subframe[0].grid_index = get_bits1(&gb);
148     p->subframe[1].grid_index = get_bits1(&gb);
149     p->subframe[2].grid_index = get_bits1(&gb);
150     p->subframe[3].grid_index = get_bits1(&gb);
151
152     if (p->cur_rate == Rate6k3) {
153         skip_bits1(&gb);  /* skip reserved bit */
154
155         /* Compute pulse_pos index using the 13-bit combined position index */
156         temp = get_bits(&gb, 13);
157         p->subframe[0].pulse_pos = temp / 810;
158
159         temp -= p->subframe[0].pulse_pos * 810;
160         p->subframe[1].pulse_pos = FASTDIV(temp, 90);
161
162         temp -= p->subframe[1].pulse_pos * 90;
163         p->subframe[2].pulse_pos = FASTDIV(temp, 9);
164         p->subframe[3].pulse_pos = temp - p->subframe[2].pulse_pos * 9;
165
166         p->subframe[0].pulse_pos = (p->subframe[0].pulse_pos << 16) +
167                                    get_bits(&gb, 16);
168         p->subframe[1].pulse_pos = (p->subframe[1].pulse_pos << 14) +
169                                    get_bits(&gb, 14);
170         p->subframe[2].pulse_pos = (p->subframe[2].pulse_pos << 16) +
171                                    get_bits(&gb, 16);
172         p->subframe[3].pulse_pos = (p->subframe[3].pulse_pos << 14) +
173                                    get_bits(&gb, 14);
174
175         p->subframe[0].pulse_sign = get_bits(&gb, 6);
176         p->subframe[1].pulse_sign = get_bits(&gb, 5);
177         p->subframe[2].pulse_sign = get_bits(&gb, 6);
178         p->subframe[3].pulse_sign = get_bits(&gb, 5);
179     } else { /* Rate5k3 */
180         p->subframe[0].pulse_pos  = get_bits(&gb, 12);
181         p->subframe[1].pulse_pos  = get_bits(&gb, 12);
182         p->subframe[2].pulse_pos  = get_bits(&gb, 12);
183         p->subframe[3].pulse_pos  = get_bits(&gb, 12);
184
185         p->subframe[0].pulse_sign = get_bits(&gb, 4);
186         p->subframe[1].pulse_sign = get_bits(&gb, 4);
187         p->subframe[2].pulse_sign = get_bits(&gb, 4);
188         p->subframe[3].pulse_sign = get_bits(&gb, 4);
189     }
190
191     return 0;
192 }
193
194 /**
195  * Bitexact implementation of sqrt(val/2).
196  */
197 static int16_t square_root(int val)
198 {
199     return (ff_sqrt(val << 1) >> 1) & (~1);
200 }
201
202 /**
203  * Calculate the number of left-shifts required for normalizing the input.
204  *
205  * @param num   input number
206  * @param width width of the input, 16 bits(0) / 32 bits(1)
207  */
208 static int normalize_bits(int num, int width)
209 {
210     int i = 0;
211     int bits = (width) ? 31 : 15;
212
213     if (num) {
214         if (num == -1)
215             return bits;
216         if (num < 0)
217             num = ~num;
218         i= bits - av_log2(num) - 1;
219         i= FFMAX(i, 0);
220     }
221     return i;
222 }
223
224 /**
225  * Scale vector contents based on the largest of their absolutes.
226  */
227 static int scale_vector(int16_t *vector, int length)
228 {
229     int bits, scale, max = 0;
230     int i;
231
232     const int16_t shift_table[16] = {
233         0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
234         0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000, 0x7fff
235     };
236
237     for (i = 0; i < length; i++)
238         max = FFMAX(max, FFABS(vector[i]));
239
240     bits  = normalize_bits(max, 0);
241     scale = shift_table[bits];
242
243     for (i = 0; i < length; i++)
244         vector[i] = (vector[i] * scale) >> 3;
245
246     return bits - 3;
247 }
248
249 /**
250  * Perform inverse quantization of LSP frequencies.
251  *
252  * @param cur_lsp    the current LSP vector
253  * @param prev_lsp   the previous LSP vector
254  * @param lsp_index  VQ indices
255  * @param bad_frame  bad frame flag
256  */
257 static void inverse_quant(int16_t *cur_lsp, int16_t *prev_lsp,
258                           uint8_t *lsp_index, int bad_frame)
259 {
260     int min_dist, pred;
261     int i, j, temp, stable;
262
263     /* Check for frame erasure */
264     if (!bad_frame) {
265         min_dist     = 0x100;
266         pred         = 12288;
267     } else {
268         min_dist     = 0x200;
269         pred         = 23552;
270         lsp_index[0] = lsp_index[1] = lsp_index[2] = 0;
271     }
272
273     /* Get the VQ table entry corresponding to the transmitted index */
274     cur_lsp[0] = lsp_band0[lsp_index[0]][0];
275     cur_lsp[1] = lsp_band0[lsp_index[0]][1];
276     cur_lsp[2] = lsp_band0[lsp_index[0]][2];
277     cur_lsp[3] = lsp_band1[lsp_index[1]][0];
278     cur_lsp[4] = lsp_band1[lsp_index[1]][1];
279     cur_lsp[5] = lsp_band1[lsp_index[1]][2];
280     cur_lsp[6] = lsp_band2[lsp_index[2]][0];
281     cur_lsp[7] = lsp_band2[lsp_index[2]][1];
282     cur_lsp[8] = lsp_band2[lsp_index[2]][2];
283     cur_lsp[9] = lsp_band2[lsp_index[2]][3];
284
285     /* Add predicted vector & DC component to the previously quantized vector */
286     for (i = 0; i < LPC_ORDER; i++) {
287         temp        = ((prev_lsp[i] - dc_lsp[i]) * pred + (1 << 14)) >> 15;
288         cur_lsp[i] += dc_lsp[i] + temp;
289     }
290
291     for (i = 0; i < LPC_ORDER; i++) {
292         cur_lsp[0]             = FFMAX(cur_lsp[0],  0x180);
293         cur_lsp[LPC_ORDER - 1] = FFMIN(cur_lsp[LPC_ORDER - 1], 0x7e00);
294
295         /* Stability check */
296         for (j = 1; j < LPC_ORDER; j++) {
297             temp = min_dist + cur_lsp[j - 1] - cur_lsp[j];
298             if (temp > 0) {
299                 temp >>= 1;
300                 cur_lsp[j - 1] -= temp;
301                 cur_lsp[j]     += temp;
302             }
303         }
304         stable = 1;
305         for (j = 1; j < LPC_ORDER; j++) {
306             temp = cur_lsp[j - 1] + min_dist - cur_lsp[j] - 4;
307             if (temp > 0) {
308                 stable = 0;
309                 break;
310             }
311         }
312         if (stable)
313             break;
314     }
315     if (!stable)
316         memcpy(cur_lsp, prev_lsp, LPC_ORDER * sizeof(int16_t));
317 }
318
319 /**
320  * Bitexact implementation of 2ab scaled by 1/2^16.
321  *
322  * @param a 32 bit multiplicand
323  * @param b 16 bit multiplier
324  */
325 #define MULL2(a, b) \
326         MULL(a,b,15)
327
328 /**
329  * Convert LSP frequencies to LPC coefficients.
330  *
331  * @param lpc buffer for LPC coefficients
332  */
333 static void lsp2lpc(int16_t *lpc)
334 {
335     int f1[LPC_ORDER / 2 + 1];
336     int f2[LPC_ORDER / 2 + 1];
337     int i, j;
338
339     /* Calculate negative cosine */
340     for (j = 0; j < LPC_ORDER; j++) {
341         int index     = lpc[j] >> 7;
342         int offset    = lpc[j] & 0x7f;
343         int64_t temp1 = cos_tab[index] << 16;
344         int temp2     = (cos_tab[index + 1] - cos_tab[index]) *
345                           ((offset << 8) + 0x80) << 1;
346
347         lpc[j] = -(av_clipl_int32(((temp1 + temp2) << 1) + (1 << 15)) >> 16);
348     }
349
350     /*
351      * Compute sum and difference polynomial coefficients
352      * (bitexact alternative to lsp2poly() in lsp.c)
353      */
354     /* Initialize with values in Q28 */
355     f1[0] = 1 << 28;
356     f1[1] = (lpc[0] << 14) + (lpc[2] << 14);
357     f1[2] = lpc[0] * lpc[2] + (2 << 28);
358
359     f2[0] = 1 << 28;
360     f2[1] = (lpc[1] << 14) + (lpc[3] << 14);
361     f2[2] = lpc[1] * lpc[3] + (2 << 28);
362
363     /*
364      * Calculate and scale the coefficients by 1/2 in
365      * each iteration for a final scaling factor of Q25
366      */
367     for (i = 2; i < LPC_ORDER / 2; i++) {
368         f1[i + 1] = f1[i - 1] + MULL2(f1[i], lpc[2 * i]);
369         f2[i + 1] = f2[i - 1] + MULL2(f2[i], lpc[2 * i + 1]);
370
371         for (j = i; j >= 2; j--) {
372             f1[j] = MULL2(f1[j - 1], lpc[2 * i]) +
373                     (f1[j] >> 1) + (f1[j - 2] >> 1);
374             f2[j] = MULL2(f2[j - 1], lpc[2 * i + 1]) +
375                     (f2[j] >> 1) + (f2[j - 2] >> 1);
376         }
377
378         f1[0] >>= 1;
379         f2[0] >>= 1;
380         f1[1] = ((lpc[2 * i]     << 16 >> i) + f1[1]) >> 1;
381         f2[1] = ((lpc[2 * i + 1] << 16 >> i) + f2[1]) >> 1;
382     }
383
384     /* Convert polynomial coefficients to LPC coefficients */
385     for (i = 0; i < LPC_ORDER / 2; i++) {
386         int64_t ff1 = f1[i + 1] + f1[i];
387         int64_t ff2 = f2[i + 1] - f2[i];
388
389         lpc[i] = av_clipl_int32(((ff1 + ff2) << 3) + (1 << 15)) >> 16;
390         lpc[LPC_ORDER - i - 1] = av_clipl_int32(((ff1 - ff2) << 3) +
391                                                 (1 << 15)) >> 16;
392     }
393 }
394
395 /**
396  * Quantize LSP frequencies by interpolation and convert them to
397  * the corresponding LPC coefficients.
398  *
399  * @param lpc      buffer for LPC coefficients
400  * @param cur_lsp  the current LSP vector
401  * @param prev_lsp the previous LSP vector
402  */
403 static void lsp_interpolate(int16_t *lpc, int16_t *cur_lsp, int16_t *prev_lsp)
404 {
405     int i;
406     int16_t *lpc_ptr = lpc;
407
408     /* cur_lsp * 0.25 + prev_lsp * 0.75 */
409     ff_acelp_weighted_vector_sum(lpc, cur_lsp, prev_lsp,
410                                  4096, 12288, 1 << 13, 14, LPC_ORDER);
411     ff_acelp_weighted_vector_sum(lpc + LPC_ORDER, cur_lsp, prev_lsp,
412                                  8192, 8192, 1 << 13, 14, LPC_ORDER);
413     ff_acelp_weighted_vector_sum(lpc + 2 * LPC_ORDER, cur_lsp, prev_lsp,
414                                  12288, 4096, 1 << 13, 14, LPC_ORDER);
415     memcpy(lpc + 3 * LPC_ORDER, cur_lsp, LPC_ORDER * sizeof(int16_t));
416
417     for (i = 0; i < SUBFRAMES; i++) {
418         lsp2lpc(lpc_ptr);
419         lpc_ptr += LPC_ORDER;
420     }
421 }
422
423 /**
424  * Generate a train of dirac functions with period as pitch lag.
425  */
426 static void gen_dirac_train(int16_t *buf, int pitch_lag)
427 {
428     int16_t vector[SUBFRAME_LEN];
429     int i, j;
430
431     memcpy(vector, buf, SUBFRAME_LEN * sizeof(int16_t));
432     for (i = pitch_lag; i < SUBFRAME_LEN; i += pitch_lag) {
433         for (j = 0; j < SUBFRAME_LEN - i; j++)
434             buf[i + j] += vector[j];
435     }
436 }
437
438 /**
439  * Generate fixed codebook excitation vector.
440  *
441  * @param vector    decoded excitation vector
442  * @param subfrm    current subframe
443  * @param cur_rate  current bitrate
444  * @param pitch_lag closed loop pitch lag
445  * @param index     current subframe index
446  */
447 static void gen_fcb_excitation(int16_t *vector, G723_1_Subframe subfrm,
448                                Rate cur_rate, int pitch_lag, int index)
449 {
450     int temp, i, j;
451
452     memset(vector, 0, SUBFRAME_LEN * sizeof(int16_t));
453
454     if (cur_rate == Rate6k3) {
455         if (subfrm.pulse_pos >= max_pos[index])
456             return;
457
458         /* Decode amplitudes and positions */
459         j = PULSE_MAX - pulses[index];
460         temp = subfrm.pulse_pos;
461         for (i = 0; i < SUBFRAME_LEN / GRID_SIZE; i++) {
462             temp -= combinatorial_table[j][i];
463             if (temp >= 0)
464                 continue;
465             temp += combinatorial_table[j++][i];
466             if (subfrm.pulse_sign & (1 << (PULSE_MAX - j))) {
467                 vector[subfrm.grid_index + GRID_SIZE * i] =
468                                         -fixed_cb_gain[subfrm.amp_index];
469             } else {
470                 vector[subfrm.grid_index + GRID_SIZE * i] =
471                                          fixed_cb_gain[subfrm.amp_index];
472             }
473             if (j == PULSE_MAX)
474                 break;
475         }
476         if (subfrm.dirac_train == 1)
477             gen_dirac_train(vector, pitch_lag);
478     } else { /* Rate5k3 */
479         int cb_gain  = fixed_cb_gain[subfrm.amp_index];
480         int cb_shift = subfrm.grid_index;
481         int cb_sign  = subfrm.pulse_sign;
482         int cb_pos   = subfrm.pulse_pos;
483         int offset, beta, lag;
484
485         for (i = 0; i < 8; i += 2) {
486             offset         = ((cb_pos & 7) << 3) + cb_shift + i;
487             vector[offset] = (cb_sign & 1) ? cb_gain : -cb_gain;
488             cb_pos  >>= 3;
489             cb_sign >>= 1;
490         }
491
492         /* Enhance harmonic components */
493         lag  = pitch_contrib[subfrm.ad_cb_gain << 1] + pitch_lag +
494                subfrm.ad_cb_lag - 1;
495         beta = pitch_contrib[(subfrm.ad_cb_gain << 1) + 1];
496
497         if (lag < SUBFRAME_LEN - 2) {
498             for (i = lag; i < SUBFRAME_LEN; i++)
499                 vector[i] += beta * vector[i - lag] >> 15;
500         }
501     }
502 }
503
504 /**
505  * Get delayed contribution from the previous excitation vector.
506  */
507 static void get_residual(int16_t *residual, int16_t *prev_excitation, int lag)
508 {
509     int offset = PITCH_MAX - PITCH_ORDER / 2 - lag;
510     int i;
511
512     residual[0] = prev_excitation[offset];
513     residual[1] = prev_excitation[offset + 1];
514
515     offset += 2;
516     for (i = 2; i < SUBFRAME_LEN + PITCH_ORDER - 1; i++)
517         residual[i] = prev_excitation[offset + (i - 2) % lag];
518 }
519
520 /**
521  * Generate adaptive codebook excitation.
522  */
523 static void gen_acb_excitation(int16_t *vector, int16_t *prev_excitation,
524                                int pitch_lag, G723_1_Subframe subfrm,
525                                Rate cur_rate)
526 {
527     int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
528     const int16_t *cb_ptr;
529     int lag = pitch_lag + subfrm.ad_cb_lag - 1;
530
531     int i;
532     int64_t sum;
533
534     get_residual(residual, prev_excitation, lag);
535
536     /* Select quantization table */
537     if (cur_rate == Rate6k3 && pitch_lag < SUBFRAME_LEN - 2) {
538         cb_ptr = adaptive_cb_gain85;
539     } else
540         cb_ptr = adaptive_cb_gain170;
541
542     /* Calculate adaptive vector */
543     cb_ptr += subfrm.ad_cb_gain * 20;
544     for (i = 0; i < SUBFRAME_LEN; i++) {
545         sum = ff_dot_product(residual + i, cb_ptr, PITCH_ORDER);
546         vector[i] = av_clipl_int32((sum << 2) + (1 << 15)) >> 16;
547     }
548 }
549
550 /**
551  * Estimate maximum auto-correlation around pitch lag.
552  *
553  * @param p         the context
554  * @param offset    offset of the excitation vector
555  * @param ccr_max   pointer to the maximum auto-correlation
556  * @param pitch_lag decoded pitch lag
557  * @param length    length of autocorrelation
558  * @param dir       forward lag(1) / backward lag(-1)
559  */
560 static int autocorr_max(G723_1_Context *p, int offset, int *ccr_max,
561                         int pitch_lag, int length, int dir)
562 {
563     int limit, ccr, lag = 0;
564     int16_t *buf = p->excitation + offset;
565     int i;
566
567     pitch_lag = FFMIN(PITCH_MAX - 3, pitch_lag);
568     limit     = FFMIN(FRAME_LEN + PITCH_MAX - offset - length, pitch_lag + 3);
569
570     for (i = pitch_lag - 3; i <= limit; i++) {
571         ccr = ff_dot_product(buf, buf + dir * i, length)<<1;
572
573         if (ccr > *ccr_max) {
574             *ccr_max = ccr;
575             lag = i;
576         }
577     }
578     return lag;
579 }
580
581 /**
582  * Calculate pitch postfilter optimal and scaling gains.
583  *
584  * @param lag      pitch postfilter forward/backward lag
585  * @param ppf      pitch postfilter parameters
586  * @param cur_rate current bitrate
587  * @param tgt_eng  target energy
588  * @param ccr      cross-correlation
589  * @param res_eng  residual energy
590  */
591 static void comp_ppf_gains(int lag, PPFParam *ppf, Rate cur_rate,
592                            int tgt_eng, int ccr, int res_eng)
593 {
594     int pf_residual;     /* square of postfiltered residual */
595     int64_t temp1, temp2;
596
597     ppf->index = lag;
598
599     temp1 = tgt_eng * res_eng >> 1;
600     temp2 = ccr * ccr << 1;
601
602     if (temp2 > temp1) {
603         if (ccr >= res_eng) {
604             ppf->opt_gain = ppf_gain_weight[cur_rate];
605         } else {
606             ppf->opt_gain = (ccr << 15) / res_eng *
607                             ppf_gain_weight[cur_rate] >> 15;
608         }
609         /* pf_res^2 = tgt_eng + 2*ccr*gain + res_eng*gain^2 */
610         temp1       = (tgt_eng << 15) + (ccr * ppf->opt_gain << 1);
611         temp2       = (ppf->opt_gain * ppf->opt_gain >> 15) * res_eng;
612         pf_residual = av_clipl_int32(temp1 + temp2 + (1 << 15)) >> 16;
613
614         if (tgt_eng >= pf_residual << 1) {
615             temp1 = 0x7fff;
616         } else {
617             temp1 = (tgt_eng << 14) / pf_residual;
618         }
619
620         /* scaling_gain = sqrt(tgt_eng/pf_res^2) */
621         ppf->sc_gain = square_root(temp1 << 16);
622     } else {
623         ppf->opt_gain = 0;
624         ppf->sc_gain  = 0x7fff;
625     }
626
627     ppf->opt_gain = av_clip_int16(ppf->opt_gain * ppf->sc_gain >> 15);
628 }
629
630 /**
631  * Calculate pitch postfilter parameters.
632  *
633  * @param p         the context
634  * @param offset    offset of the excitation vector
635  * @param pitch_lag decoded pitch lag
636  * @param ppf       pitch postfilter parameters
637  * @param cur_rate  current bitrate
638  */
639 static void comp_ppf_coeff(G723_1_Context *p, int offset, int pitch_lag,
640                            PPFParam *ppf, Rate cur_rate)
641 {
642
643     int16_t scale;
644     int i;
645     int64_t temp1, temp2;
646
647     /*
648      * 0 - target energy
649      * 1 - forward cross-correlation
650      * 2 - forward residual energy
651      * 3 - backward cross-correlation
652      * 4 - backward residual energy
653      */
654     int energy[5] = {0, 0, 0, 0, 0};
655     int16_t *buf  = p->excitation + offset;
656     int fwd_lag   = autocorr_max(p, offset, &energy[1], pitch_lag,
657                                  SUBFRAME_LEN, 1);
658     int back_lag  = autocorr_max(p, offset, &energy[3], pitch_lag,
659                                  SUBFRAME_LEN, -1);
660
661     ppf->index    = 0;
662     ppf->opt_gain = 0;
663     ppf->sc_gain  = 0x7fff;
664
665     /* Case 0, Section 3.6 */
666     if (!back_lag && !fwd_lag)
667         return;
668
669     /* Compute target energy */
670     energy[0] = ff_dot_product(buf, buf, SUBFRAME_LEN)<<1;
671
672     /* Compute forward residual energy */
673     if (fwd_lag)
674         energy[2] = ff_dot_product(buf + fwd_lag, buf + fwd_lag,
675                                    SUBFRAME_LEN)<<1;
676
677     /* Compute backward residual energy */
678     if (back_lag)
679         energy[4] = ff_dot_product(buf - back_lag, buf - back_lag,
680                                    SUBFRAME_LEN)<<1;
681
682     /* Normalize and shorten */
683     temp1 = 0;
684     for (i = 0; i < 5; i++)
685         temp1 = FFMAX(energy[i], temp1);
686
687     scale = normalize_bits(temp1, 1);
688     for (i = 0; i < 5; i++)
689         energy[i] = av_clipl_int32(energy[i] << scale) >> 16;
690
691     if (fwd_lag && !back_lag) {  /* Case 1 */
692         comp_ppf_gains(fwd_lag,  ppf, cur_rate, energy[0], energy[1],
693                        energy[2]);
694     } else if (!fwd_lag) {       /* Case 2 */
695         comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
696                        energy[4]);
697     } else {                     /* Case 3 */
698
699         /*
700          * Select the largest of energy[1]^2/energy[2]
701          * and energy[3]^2/energy[4]
702          */
703         temp1 = energy[4] * ((energy[1] * energy[1] + (1 << 14)) >> 15);
704         temp2 = energy[2] * ((energy[3] * energy[3] + (1 << 14)) >> 15);
705         if (temp1 >= temp2) {
706             comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
707                            energy[2]);
708         } else {
709             comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
710                            energy[4]);
711         }
712     }
713 }
714
715 /**
716  * Classify frames as voiced/unvoiced.
717  *
718  * @param p         the context
719  * @param pitch_lag decoded pitch_lag
720  * @param exc_eng   excitation energy estimation
721  * @param scale     scaling factor of exc_eng
722  *
723  * @return residual interpolation index if voiced, 0 otherwise
724  */
725 static int comp_interp_index(G723_1_Context *p, int pitch_lag,
726                              int *exc_eng, int *scale)
727 {
728     int offset = PITCH_MAX + 2 * SUBFRAME_LEN;
729     int16_t *buf = p->excitation + offset;
730
731     int index, ccr, tgt_eng, best_eng, temp;
732
733     *scale = scale_vector(p->excitation, FRAME_LEN + PITCH_MAX);
734
735     /* Compute maximum backward cross-correlation */
736     ccr   = 0;
737     index = autocorr_max(p, offset, &ccr, pitch_lag, SUBFRAME_LEN * 2, -1);
738     ccr   = av_clipl_int32((int64_t)ccr + (1 << 15)) >> 16;
739
740     /* Compute target energy */
741     tgt_eng  = ff_dot_product(buf, buf, SUBFRAME_LEN * 2)<<1;
742     *exc_eng = av_clipl_int32(tgt_eng + (1 << 15)) >> 16;
743
744     if (ccr <= 0)
745         return 0;
746
747     /* Compute best energy */
748     best_eng = ff_dot_product(buf - index, buf - index,
749                               SUBFRAME_LEN * 2)<<1;
750     best_eng = av_clipl_int32((int64_t)best_eng + (1 << 15)) >> 16;
751
752     temp = best_eng * *exc_eng >> 3;
753
754     if (temp < ccr * ccr) {
755         return index;
756     } else
757         return 0;
758 }
759
760 /**
761  * Peform residual interpolation based on frame classification.
762  *
763  * @param buf   decoded excitation vector
764  * @param out   output vector
765  * @param lag   decoded pitch lag
766  * @param gain  interpolated gain
767  * @param rseed seed for random number generator
768  */
769 static void residual_interp(int16_t *buf, int16_t *out, int lag,
770                             int gain, int *rseed)
771 {
772     int i;
773     if (lag) { /* Voiced */
774         int16_t *vector_ptr = buf + PITCH_MAX;
775         /* Attenuate */
776         for (i = 0; i < lag; i++)
777             vector_ptr[i - lag] = vector_ptr[i - lag] * 3 >> 2;
778         av_memcpy_backptr((uint8_t*)vector_ptr, lag * sizeof(int16_t),
779                           FRAME_LEN * sizeof(int16_t));
780         memcpy(out, vector_ptr, FRAME_LEN * sizeof(int16_t));
781     } else {  /* Unvoiced */
782         for (i = 0; i < FRAME_LEN; i++) {
783             *rseed = *rseed * 521 + 259;
784             out[i] = gain * *rseed >> 15;
785         }
786         memset(buf, 0, (FRAME_LEN + PITCH_MAX) * sizeof(int16_t));
787     }
788 }
789
790 /**
791  * Perform IIR filtering.
792  *
793  * @param fir_coef FIR coefficients
794  * @param iir_coef IIR coefficients
795  * @param src      source vector
796  * @param dest     destination vector
797  * @param width    width of the output, 16 bits(0) / 32 bits(1)
798  */
799 #define iir_filter(fir_coef, iir_coef, src, dest, width)\
800 {\
801     int m, n;\
802     int res_shift = 16 & ~-(width);\
803     int in_shift  = 16 - res_shift;\
804 \
805     for (m = 0; m < SUBFRAME_LEN; m++) {\
806         int64_t filter = 0;\
807         for (n = 1; n <= LPC_ORDER; n++) {\
808             filter -= (fir_coef)[n - 1] * (src)[m - n] -\
809                       (iir_coef)[n - 1] * ((dest)[m - n] >> in_shift);\
810         }\
811 \
812         (dest)[m] = av_clipl_int32(((src)[m] << 16) + (filter << 3) +\
813                                    (1 << 15)) >> res_shift;\
814     }\
815 }
816
817 /**
818  * Adjust gain of postfiltered signal.
819  *
820  * @param p      the context
821  * @param buf    postfiltered output vector
822  * @param energy input energy coefficient
823  */
824 static void gain_scale(G723_1_Context *p, int16_t * buf, int energy)
825 {
826     int num, denom, gain, bits1, bits2;
827     int i;
828
829     num   = energy;
830     denom = 0;
831     for (i = 0; i < SUBFRAME_LEN; i++) {
832         int64_t temp = buf[i] >> 2;
833         temp  = av_clipl_int32(MUL64(temp, temp) << 1);
834         denom = av_clipl_int32(denom + temp);
835     }
836
837     if (num && denom) {
838         bits1   = normalize_bits(num, 1);
839         bits2   = normalize_bits(denom, 1);
840         num     = num << bits1 >> 1;
841         denom <<= bits2;
842
843         bits2 = 5 + bits1 - bits2;
844         bits2 = FFMAX(0, bits2);
845
846         gain = (num >> 1) / (denom >> 16);
847         gain = square_root(gain << 16 >> bits2);
848     } else {
849         gain = 1 << 12;
850     }
851
852     for (i = 0; i < SUBFRAME_LEN; i++) {
853         p->pf_gain = ((p->pf_gain << 4) - p->pf_gain + gain + (1 << 3)) >> 4;
854         buf[i]     = av_clip_int16((buf[i] * (p->pf_gain + (p->pf_gain >> 4)) +
855                                    (1 << 10)) >> 11);
856     }
857 }
858
859 /**
860  * Perform formant filtering.
861  *
862  * @param p   the context
863  * @param lpc quantized lpc coefficients
864  * @param buf output buffer
865  */
866 static void formant_postfilter(G723_1_Context *p, int16_t *lpc, int16_t *buf)
867 {
868     int16_t filter_coef[2][LPC_ORDER], *buf_ptr;
869     int filter_signal[LPC_ORDER + FRAME_LEN], *signal_ptr;
870     int i, j, k;
871
872     memcpy(buf, p->fir_mem, LPC_ORDER * sizeof(int16_t));
873     memcpy(filter_signal, p->iir_mem, LPC_ORDER * sizeof(int));
874
875     for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
876         for (k = 0; k < LPC_ORDER; k++) {
877             filter_coef[0][k] = (-lpc[k] * postfilter_tbl[0][k] +
878                                  (1 << 14)) >> 15;
879             filter_coef[1][k] = (-lpc[k] * postfilter_tbl[1][k] +
880                                  (1 << 14)) >> 15;
881         }
882         iir_filter(filter_coef[0], filter_coef[1], buf + i,
883                    filter_signal + i, 1);
884     }
885
886     memcpy(p->fir_mem, buf + FRAME_LEN, LPC_ORDER * sizeof(int16_t));
887     memcpy(p->iir_mem, filter_signal + FRAME_LEN, LPC_ORDER * sizeof(int));
888
889     buf_ptr    = buf + LPC_ORDER;
890     signal_ptr = filter_signal + LPC_ORDER;
891     for (i = 0; i < SUBFRAMES; i++) {
892         int16_t temp_vector[SUBFRAME_LEN];
893         int16_t temp;
894         int auto_corr[2];
895         int scale, energy;
896
897         /* Normalize */
898         memcpy(temp_vector, buf_ptr, SUBFRAME_LEN * sizeof(int16_t));
899         scale = scale_vector(temp_vector, SUBFRAME_LEN);
900
901         /* Compute auto correlation coefficients */
902         auto_corr[0] = ff_dot_product(temp_vector, temp_vector + 1,
903                                       SUBFRAME_LEN - 1)<<1;
904         auto_corr[1] = ff_dot_product(temp_vector, temp_vector,
905                                       SUBFRAME_LEN)<<1;
906
907         /* Compute reflection coefficient */
908         temp = auto_corr[1] >> 16;
909         if (temp) {
910             temp = (auto_corr[0] >> 2) / temp;
911         }
912         p->reflection_coef = ((p->reflection_coef << 2) - p->reflection_coef +
913                               temp + 2) >> 2;
914         temp = (p->reflection_coef * 0xffffc >> 3) & 0xfffc;
915
916         /* Compensation filter */
917         for (j = 0; j < SUBFRAME_LEN; j++) {
918             buf_ptr[j] = av_clipl_int32(signal_ptr[j] +
919                                         ((signal_ptr[j - 1] >> 16) *
920                                          temp << 1)) >> 16;
921         }
922
923         /* Compute normalized signal energy */
924         temp = 2 * scale + 4;
925         if (temp < 0) {
926             energy = av_clipl_int32((int64_t)auto_corr[1] << -temp);
927         } else
928             energy = auto_corr[1] >> temp;
929
930         gain_scale(p, buf_ptr, energy);
931
932         buf_ptr    += SUBFRAME_LEN;
933         signal_ptr += SUBFRAME_LEN;
934     }
935 }
936
937 static int g723_1_decode_frame(AVCodecContext *avctx, void *data,
938                                int *data_size, AVPacket *avpkt)
939 {
940     G723_1_Context *p  = avctx->priv_data;
941     const uint8_t *buf = avpkt->data;
942     int buf_size       = avpkt->size;
943     int16_t *out       = data;
944     int dec_mode       = buf[0] & 3;
945
946     PPFParam ppf[SUBFRAMES];
947     int16_t cur_lsp[LPC_ORDER];
948     int16_t lpc[SUBFRAMES * LPC_ORDER];
949     int16_t acb_vector[SUBFRAME_LEN];
950     int16_t *vector_ptr;
951     int bad_frame = 0, i, j;
952
953     if (!buf_size || buf_size < frame_size[dec_mode]) {
954         *data_size = 0;
955         return buf_size;
956     }
957
958     if (unpack_bitstream(p, buf, buf_size) < 0) {
959         bad_frame         = 1;
960         p->cur_frame_type = p->past_frame_type == ActiveFrame ?
961                             ActiveFrame : UntransmittedFrame;
962     }
963
964     *data_size = FRAME_LEN * sizeof(int16_t);
965     if(p->cur_frame_type == ActiveFrame) {
966         if (!bad_frame) {
967             p->erased_frames = 0;
968         } else if(p->erased_frames != 3)
969             p->erased_frames++;
970
971         inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, bad_frame);
972         lsp_interpolate(lpc, cur_lsp, p->prev_lsp);
973
974         /* Save the lsp_vector for the next frame */
975         memcpy(p->prev_lsp, cur_lsp, LPC_ORDER * sizeof(int16_t));
976
977         /* Generate the excitation for the frame */
978         memcpy(p->excitation, p->prev_excitation, PITCH_MAX * sizeof(int16_t));
979         vector_ptr = p->excitation + PITCH_MAX;
980         if (!p->erased_frames) {
981             /* Update interpolation gain memory */
982             p->interp_gain = fixed_cb_gain[(p->subframe[2].amp_index +
983                                             p->subframe[3].amp_index) >> 1];
984             for (i = 0; i < SUBFRAMES; i++) {
985                 gen_fcb_excitation(vector_ptr, p->subframe[i], p->cur_rate,
986                                    p->pitch_lag[i >> 1], i);
987                 gen_acb_excitation(acb_vector, &p->excitation[SUBFRAME_LEN * i],
988                                    p->pitch_lag[i >> 1], p->subframe[i],
989                                    p->cur_rate);
990                 /* Get the total excitation */
991                 for (j = 0; j < SUBFRAME_LEN; j++) {
992                     vector_ptr[j] = av_clip_int16(vector_ptr[j] << 1);
993                     vector_ptr[j] = av_clip_int16(vector_ptr[j] +
994                                                   acb_vector[j]);
995                 }
996                 vector_ptr += SUBFRAME_LEN;
997             }
998
999             vector_ptr = p->excitation + PITCH_MAX;
1000
1001             /* Save the excitation */
1002             memcpy(out, vector_ptr, FRAME_LEN * sizeof(int16_t));
1003
1004             p->interp_index = comp_interp_index(p, p->pitch_lag[1],
1005                                                 &p->sid_gain, &p->cur_gain);
1006
1007             for (i = PITCH_MAX, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1008                 comp_ppf_coeff(p, i, p->pitch_lag[j >> 1],
1009                                ppf + j, p->cur_rate);
1010
1011             /* Restore the original excitation */
1012             memcpy(p->excitation, p->prev_excitation,
1013                    PITCH_MAX * sizeof(int16_t));
1014             memcpy(vector_ptr, out, FRAME_LEN * sizeof(int16_t));
1015
1016             /* Peform pitch postfiltering */
1017             for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1018                 ff_acelp_weighted_vector_sum(out + LPC_ORDER + i, vector_ptr + i,
1019                                              vector_ptr + i + ppf[j].index,
1020                                              ppf[j].sc_gain, ppf[j].opt_gain,
1021                                              1 << 14, 15, SUBFRAME_LEN);
1022         } else {
1023             p->interp_gain = (p->interp_gain * 3 + 2) >> 2;
1024             if (p->erased_frames == 3) {
1025                 /* Mute output */
1026                 memset(p->excitation, 0,
1027                        (FRAME_LEN + PITCH_MAX) * sizeof(int16_t));
1028                 memset(out, 0, (FRAME_LEN + LPC_ORDER) * sizeof(int16_t));
1029             } else {
1030                 /* Regenerate frame */
1031                 residual_interp(p->excitation, out + LPC_ORDER, p->interp_index,
1032                                 p->interp_gain, &p->random_seed);
1033             }
1034         }
1035         /* Save the excitation for the next frame */
1036         memcpy(p->prev_excitation, p->excitation + FRAME_LEN,
1037                PITCH_MAX * sizeof(int16_t));
1038     } else {
1039         memset(out, 0, *data_size);
1040         av_log(avctx, AV_LOG_WARNING,
1041                "G.723.1: Comfort noise generation not supported yet\n");
1042         return frame_size[dec_mode];
1043     }
1044
1045     p->past_frame_type = p->cur_frame_type;
1046
1047     memcpy(out, p->synth_mem, LPC_ORDER * sizeof(int16_t));
1048     for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1049         ff_celp_lp_synthesis_filter(out + i, &lpc[j * LPC_ORDER],
1050                                     out + i, SUBFRAME_LEN, LPC_ORDER,
1051                                     0, 1, 1 << 12);
1052     memcpy(p->synth_mem, out + FRAME_LEN, LPC_ORDER * sizeof(int16_t));
1053
1054     formant_postfilter(p, lpc, out);
1055
1056     memmove(out, out + LPC_ORDER, *data_size);
1057
1058     return frame_size[dec_mode];
1059 }
1060
1061 AVCodec ff_g723_1_decoder = {
1062     .name           = "g723_1",
1063     .type           = AVMEDIA_TYPE_AUDIO,
1064     .id             = CODEC_ID_G723_1,
1065     .priv_data_size = sizeof(G723_1_Context),
1066     .init           = g723_1_decode_init,
1067     .decode         = g723_1_decode_frame,
1068     .long_name      = NULL_IF_CONFIG_SMALL("G.723.1"),
1069     .capabilities   = CODEC_CAP_SUBFRAMES,
1070 };