]> 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     int limit = 1 << (bits - 1);
213
214     if (num) {
215         if (num == -1)
216             return bits;
217         if (num < 0)
218             num = ~num;
219         i= bits - av_log2(num) - 1;
220         i= FFMAX(i, 0);
221     }
222     return i;
223 }
224
225 /**
226  * Scale vector contents based on the largest of their absolutes.
227  */
228 static int scale_vector(int16_t *vector, int length)
229 {
230     int bits, scale, max = 0;
231     int i;
232
233     const int16_t shift_table[16] = {
234         0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
235         0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000, 0x7fff
236     };
237
238     for (i = 0; i < length; i++)
239         max = FFMAX(max, FFABS(vector[i]));
240
241     bits  = normalize_bits(max, 0);
242     scale = shift_table[bits];
243
244     for (i = 0; i < length; i++)
245         vector[i] = (vector[i] * scale) >> 3;
246
247     return bits - 3;
248 }
249
250 /**
251  * Perform inverse quantization of LSP frequencies.
252  *
253  * @param cur_lsp    the current LSP vector
254  * @param prev_lsp   the previous LSP vector
255  * @param lsp_index  VQ indices
256  * @param bad_frame  bad frame flag
257  */
258 static void inverse_quant(int16_t *cur_lsp, int16_t *prev_lsp,
259                           uint8_t *lsp_index, int bad_frame)
260 {
261     int min_dist, pred;
262     int i, j, temp, stable;
263
264     /* Check for frame erasure */
265     if (!bad_frame) {
266         min_dist     = 0x100;
267         pred         = 12288;
268     } else {
269         min_dist     = 0x200;
270         pred         = 23552;
271         lsp_index[0] = lsp_index[1] = lsp_index[2] = 0;
272     }
273
274     /* Get the VQ table entry corresponding to the transmitted index */
275     cur_lsp[0] = lsp_band0[lsp_index[0]][0];
276     cur_lsp[1] = lsp_band0[lsp_index[0]][1];
277     cur_lsp[2] = lsp_band0[lsp_index[0]][2];
278     cur_lsp[3] = lsp_band1[lsp_index[1]][0];
279     cur_lsp[4] = lsp_band1[lsp_index[1]][1];
280     cur_lsp[5] = lsp_band1[lsp_index[1]][2];
281     cur_lsp[6] = lsp_band2[lsp_index[2]][0];
282     cur_lsp[7] = lsp_band2[lsp_index[2]][1];
283     cur_lsp[8] = lsp_band2[lsp_index[2]][2];
284     cur_lsp[9] = lsp_band2[lsp_index[2]][3];
285
286     /* Add predicted vector & DC component to the previously quantized vector */
287     for (i = 0; i < LPC_ORDER; i++) {
288         temp        = ((prev_lsp[i] - dc_lsp[i]) * pred + (1 << 14)) >> 15;
289         cur_lsp[i] += dc_lsp[i] + temp;
290     }
291
292     for (i = 0; i < LPC_ORDER; i++) {
293         cur_lsp[0]             = FFMAX(cur_lsp[0],  0x180);
294         cur_lsp[LPC_ORDER - 1] = FFMIN(cur_lsp[LPC_ORDER - 1], 0x7e00);
295
296         /* Stability check */
297         for (j = 1; j < LPC_ORDER; j++) {
298             temp = min_dist + cur_lsp[j - 1] - cur_lsp[j];
299             if (temp > 0) {
300                 temp >>= 1;
301                 cur_lsp[j - 1] -= temp;
302                 cur_lsp[j]     += temp;
303             }
304         }
305         stable = 1;
306         for (j = 1; j < LPC_ORDER; j++) {
307             temp = cur_lsp[j - 1] + min_dist - cur_lsp[j] - 4;
308             if (temp > 0) {
309                 stable = 0;
310                 break;
311             }
312         }
313         if (stable)
314             break;
315     }
316     if (!stable)
317         memcpy(cur_lsp, prev_lsp, LPC_ORDER * sizeof(int16_t));
318 }
319
320 /**
321  * Bitexact implementation of 2ab scaled by 1/2^16.
322  *
323  * @param a 32 bit multiplicand
324  * @param b 16 bit multiplier
325  */
326 #define MULL2(a, b) \
327         MULL(a,b,15)
328
329 /**
330  * Convert LSP frequencies to LPC coefficients.
331  *
332  * @param lpc buffer for LPC coefficients
333  */
334 static void lsp2lpc(int16_t *lpc)
335 {
336     int f1[LPC_ORDER / 2 + 1];
337     int f2[LPC_ORDER / 2 + 1];
338     int i, j;
339
340     /* Calculate negative cosine */
341     for (j = 0; j < LPC_ORDER; j++) {
342         int index     = lpc[j] >> 7;
343         int offset    = lpc[j] & 0x7f;
344         int64_t temp1 = cos_tab[index] << 16;
345         int temp2     = (cos_tab[index + 1] - cos_tab[index]) *
346                           ((offset << 8) + 0x80) << 1;
347
348         lpc[j] = -(av_clipl_int32(((temp1 + temp2) << 1) + (1 << 15)) >> 16);
349     }
350
351     /*
352      * Compute sum and difference polynomial coefficients
353      * (bitexact alternative to lsp2poly() in lsp.c)
354      */
355     /* Initialize with values in Q28 */
356     f1[0] = 1 << 28;
357     f1[1] = (lpc[0] << 14) + (lpc[2] << 14);
358     f1[2] = lpc[0] * lpc[2] + (2 << 28);
359
360     f2[0] = 1 << 28;
361     f2[1] = (lpc[1] << 14) + (lpc[3] << 14);
362     f2[2] = lpc[1] * lpc[3] + (2 << 28);
363
364     /*
365      * Calculate and scale the coefficients by 1/2 in
366      * each iteration for a final scaling factor of Q25
367      */
368     for (i = 2; i < LPC_ORDER / 2; i++) {
369         f1[i + 1] = f1[i - 1] + MULL2(f1[i], lpc[2 * i]);
370         f2[i + 1] = f2[i - 1] + MULL2(f2[i], lpc[2 * i + 1]);
371
372         for (j = i; j >= 2; j--) {
373             f1[j] = MULL2(f1[j - 1], lpc[2 * i]) +
374                     (f1[j] >> 1) + (f1[j - 2] >> 1);
375             f2[j] = MULL2(f2[j - 1], lpc[2 * i + 1]) +
376                     (f2[j] >> 1) + (f2[j - 2] >> 1);
377         }
378
379         f1[0] >>= 1;
380         f2[0] >>= 1;
381         f1[1] = ((lpc[2 * i]     << 16 >> i) + f1[1]) >> 1;
382         f2[1] = ((lpc[2 * i + 1] << 16 >> i) + f2[1]) >> 1;
383     }
384
385     /* Convert polynomial coefficients to LPC coefficients */
386     for (i = 0; i < LPC_ORDER / 2; i++) {
387         int64_t ff1 = f1[i + 1] + f1[i];
388         int64_t ff2 = f2[i + 1] - f2[i];
389
390         lpc[i] = av_clipl_int32(((ff1 + ff2) << 3) + (1 << 15)) >> 16;
391         lpc[LPC_ORDER - i - 1] = av_clipl_int32(((ff1 - ff2) << 3) +
392                                                 (1 << 15)) >> 16;
393     }
394 }
395
396 /**
397  * Quantize LSP frequencies by interpolation and convert them to
398  * the corresponding LPC coefficients.
399  *
400  * @param lpc      buffer for LPC coefficients
401  * @param cur_lsp  the current LSP vector
402  * @param prev_lsp the previous LSP vector
403  */
404 static void lsp_interpolate(int16_t *lpc, int16_t *cur_lsp, int16_t *prev_lsp)
405 {
406     int i;
407     int16_t *lpc_ptr = lpc;
408
409     /* cur_lsp * 0.25 + prev_lsp * 0.75 */
410     ff_acelp_weighted_vector_sum(lpc, cur_lsp, prev_lsp,
411                                  4096, 12288, 1 << 13, 14, LPC_ORDER);
412     ff_acelp_weighted_vector_sum(lpc + LPC_ORDER, cur_lsp, prev_lsp,
413                                  8192, 8192, 1 << 13, 14, LPC_ORDER);
414     ff_acelp_weighted_vector_sum(lpc + 2 * LPC_ORDER, cur_lsp, prev_lsp,
415                                  12288, 4096, 1 << 13, 14, LPC_ORDER);
416     memcpy(lpc + 3 * LPC_ORDER, cur_lsp, LPC_ORDER * sizeof(int16_t));
417
418     for (i = 0; i < SUBFRAMES; i++) {
419         lsp2lpc(lpc_ptr);
420         lpc_ptr += LPC_ORDER;
421     }
422 }
423
424 /**
425  * Generate a train of dirac functions with period as pitch lag.
426  */
427 static void gen_dirac_train(int16_t *buf, int pitch_lag)
428 {
429     int16_t vector[SUBFRAME_LEN];
430     int i, j;
431
432     memcpy(vector, buf, SUBFRAME_LEN * sizeof(int16_t));
433     for (i = pitch_lag; i < SUBFRAME_LEN; i += pitch_lag) {
434         for (j = 0; j < SUBFRAME_LEN - i; j++)
435             buf[i + j] += vector[j];
436     }
437 }
438
439 /**
440  * Generate fixed codebook excitation vector.
441  *
442  * @param vector    decoded excitation vector
443  * @param subfrm    current subframe
444  * @param cur_rate  current bitrate
445  * @param pitch_lag closed loop pitch lag
446  * @param index     current subframe index
447  */
448 static void gen_fcb_excitation(int16_t *vector, G723_1_Subframe subfrm,
449                                Rate cur_rate, int pitch_lag, int index)
450 {
451     int temp, i, j;
452
453     memset(vector, 0, SUBFRAME_LEN * sizeof(int16_t));
454
455     if (cur_rate == Rate6k3) {
456         if (subfrm.pulse_pos >= max_pos[index])
457             return;
458
459         /* Decode amplitudes and positions */
460         j = PULSE_MAX - pulses[index];
461         temp = subfrm.pulse_pos;
462         for (i = 0; i < SUBFRAME_LEN / GRID_SIZE; i++) {
463             temp -= combinatorial_table[j][i];
464             if (temp >= 0)
465                 continue;
466             temp += combinatorial_table[j++][i];
467             if (subfrm.pulse_sign & (1 << (PULSE_MAX - j))) {
468                 vector[subfrm.grid_index + GRID_SIZE * i] =
469                                         -fixed_cb_gain[subfrm.amp_index];
470             } else {
471                 vector[subfrm.grid_index + GRID_SIZE * i] =
472                                          fixed_cb_gain[subfrm.amp_index];
473             }
474             if (j == PULSE_MAX)
475                 break;
476         }
477         if (subfrm.dirac_train == 1)
478             gen_dirac_train(vector, pitch_lag);
479     } else { /* Rate5k3 */
480         int cb_gain  = fixed_cb_gain[subfrm.amp_index];
481         int cb_shift = subfrm.grid_index;
482         int cb_sign  = subfrm.pulse_sign;
483         int cb_pos   = subfrm.pulse_pos;
484         int offset, beta, lag;
485
486         for (i = 0; i < 8; i += 2) {
487             offset         = ((cb_pos & 7) << 3) + cb_shift + i;
488             vector[offset] = (cb_sign & 1) ? cb_gain : -cb_gain;
489             cb_pos  >>= 3;
490             cb_sign >>= 1;
491         }
492
493         /* Enhance harmonic components */
494         lag  = pitch_contrib[subfrm.ad_cb_gain << 1] + pitch_lag +
495                subfrm.ad_cb_lag - 1;
496         beta = pitch_contrib[(subfrm.ad_cb_gain << 1) + 1];
497
498         if (lag < SUBFRAME_LEN - 2) {
499             for (i = lag; i < SUBFRAME_LEN; i++)
500                 vector[i] += beta * vector[i - lag] >> 15;
501         }
502     }
503 }
504
505 /**
506  * Get delayed contribution from the previous excitation vector.
507  */
508 static void get_residual(int16_t *residual, int16_t *prev_excitation, int lag)
509 {
510     int offset = PITCH_MAX - PITCH_ORDER / 2 - lag;
511     int i;
512
513     residual[0] = prev_excitation[offset];
514     residual[1] = prev_excitation[offset + 1];
515
516     offset += 2;
517     for (i = 2; i < SUBFRAME_LEN + PITCH_ORDER - 1; i++)
518         residual[i] = prev_excitation[offset + (i - 2) % lag];
519 }
520
521 /**
522  * Generate adaptive codebook excitation.
523  */
524 static void gen_acb_excitation(int16_t *vector, int16_t *prev_excitation,
525                                int pitch_lag, G723_1_Subframe subfrm,
526                                Rate cur_rate)
527 {
528     int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
529     const int16_t *cb_ptr;
530     int lag = pitch_lag + subfrm.ad_cb_lag - 1;
531
532     int i;
533     int64_t sum;
534
535     get_residual(residual, prev_excitation, lag);
536
537     /* Select quantization table */
538     if (cur_rate == Rate6k3 && pitch_lag < SUBFRAME_LEN - 2) {
539         cb_ptr = adaptive_cb_gain85;
540     } else
541         cb_ptr = adaptive_cb_gain170;
542
543     /* Calculate adaptive vector */
544     cb_ptr += subfrm.ad_cb_gain * 20;
545     for (i = 0; i < SUBFRAME_LEN; i++) {
546         sum = ff_dot_product(residual + i, cb_ptr, PITCH_ORDER);
547         vector[i] = av_clipl_int32((sum << 2) + (1 << 15)) >> 16;
548     }
549 }
550
551 /**
552  * Estimate maximum auto-correlation around pitch lag.
553  *
554  * @param p         the context
555  * @param offset    offset of the excitation vector
556  * @param ccr_max   pointer to the maximum auto-correlation
557  * @param pitch_lag decoded pitch lag
558  * @param length    length of autocorrelation
559  * @param dir       forward lag(1) / backward lag(-1)
560  */
561 static int autocorr_max(G723_1_Context *p, int offset, int *ccr_max,
562                         int pitch_lag, int length, int dir)
563 {
564     int limit, ccr, lag = 0;
565     int16_t *buf = p->excitation + offset;
566     int i;
567
568     pitch_lag = FFMIN(PITCH_MAX - 3, pitch_lag);
569     limit     = FFMIN(FRAME_LEN + PITCH_MAX - offset - length, pitch_lag + 3);
570
571     for (i = pitch_lag - 3; i <= limit; i++) {
572         ccr = ff_dot_product(buf, buf + dir * i, length)<<1;
573
574         if (ccr > *ccr_max) {
575             *ccr_max = ccr;
576             lag = i;
577         }
578     }
579     return lag;
580 }
581
582 /**
583  * Calculate pitch postfilter optimal and scaling gains.
584  *
585  * @param lag      pitch postfilter forward/backward lag
586  * @param ppf      pitch postfilter parameters
587  * @param cur_rate current bitrate
588  * @param tgt_eng  target energy
589  * @param ccr      cross-correlation
590  * @param res_eng  residual energy
591  */
592 static void comp_ppf_gains(int lag, PPFParam *ppf, Rate cur_rate,
593                            int tgt_eng, int ccr, int res_eng)
594 {
595     int pf_residual;     /* square of postfiltered residual */
596     int64_t temp1, temp2;
597
598     ppf->index = lag;
599
600     temp1 = tgt_eng * res_eng >> 1;
601     temp2 = ccr * ccr << 1;
602
603     if (temp2 > temp1) {
604         if (ccr >= res_eng) {
605             ppf->opt_gain = ppf_gain_weight[cur_rate];
606         } else {
607             ppf->opt_gain = (ccr << 15) / res_eng *
608                             ppf_gain_weight[cur_rate] >> 15;
609         }
610         /* pf_res^2 = tgt_eng + 2*ccr*gain + res_eng*gain^2 */
611         temp1       = (tgt_eng << 15) + (ccr * ppf->opt_gain << 1);
612         temp2       = (ppf->opt_gain * ppf->opt_gain >> 15) * res_eng;
613         pf_residual = av_clipl_int32(temp1 + temp2 + (1 << 15)) >> 16;
614
615         if (tgt_eng >= pf_residual << 1) {
616             temp1 = 0x7fff;
617         } else {
618             temp1 = (tgt_eng << 14) / pf_residual;
619         }
620
621         /* scaling_gain = sqrt(tgt_eng/pf_res^2) */
622         ppf->sc_gain = square_root(temp1 << 16);
623     } else {
624         ppf->opt_gain = 0;
625         ppf->sc_gain  = 0x7fff;
626     }
627
628     ppf->opt_gain = av_clip_int16(ppf->opt_gain * ppf->sc_gain >> 15);
629 }
630
631 /**
632  * Calculate pitch postfilter parameters.
633  *
634  * @param p         the context
635  * @param offset    offset of the excitation vector
636  * @param pitch_lag decoded pitch lag
637  * @param ppf       pitch postfilter parameters
638  * @param cur_rate  current bitrate
639  */
640 static void comp_ppf_coeff(G723_1_Context *p, int offset, int pitch_lag,
641                            PPFParam *ppf, Rate cur_rate)
642 {
643
644     int16_t scale;
645     int i;
646     int64_t temp1, temp2;
647
648     /*
649      * 0 - target energy
650      * 1 - forward cross-correlation
651      * 2 - forward residual energy
652      * 3 - backward cross-correlation
653      * 4 - backward residual energy
654      */
655     int energy[5] = {0, 0, 0, 0, 0};
656     int16_t *buf  = p->excitation + offset;
657     int fwd_lag   = autocorr_max(p, offset, &energy[1], pitch_lag,
658                                  SUBFRAME_LEN, 1);
659     int back_lag  = autocorr_max(p, offset, &energy[3], pitch_lag,
660                                  SUBFRAME_LEN, -1);
661
662     ppf->index    = 0;
663     ppf->opt_gain = 0;
664     ppf->sc_gain  = 0x7fff;
665
666     /* Case 0, Section 3.6 */
667     if (!back_lag && !fwd_lag)
668         return;
669
670     /* Compute target energy */
671     energy[0] = ff_dot_product(buf, buf, SUBFRAME_LEN)<<1;
672
673     /* Compute forward residual energy */
674     if (fwd_lag)
675         energy[2] = ff_dot_product(buf + fwd_lag, buf + fwd_lag,
676                                    SUBFRAME_LEN)<<1;
677
678     /* Compute backward residual energy */
679     if (back_lag)
680         energy[4] = ff_dot_product(buf - back_lag, buf - back_lag,
681                                    SUBFRAME_LEN)<<1;
682
683     /* Normalize and shorten */
684     temp1 = 0;
685     for (i = 0; i < 5; i++)
686         temp1 = FFMAX(energy[i], temp1);
687
688     scale = normalize_bits(temp1, 1);
689     for (i = 0; i < 5; i++)
690         energy[i] = av_clipl_int32(energy[i] << scale) >> 16;
691
692     if (fwd_lag && !back_lag) {  /* Case 1 */
693         comp_ppf_gains(fwd_lag,  ppf, cur_rate, energy[0], energy[1],
694                        energy[2]);
695     } else if (!fwd_lag) {       /* Case 2 */
696         comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
697                        energy[4]);
698     } else {                     /* Case 3 */
699
700         /*
701          * Select the largest of energy[1]^2/energy[2]
702          * and energy[3]^2/energy[4]
703          */
704         temp1 = energy[4] * ((energy[1] * energy[1] + (1 << 14)) >> 15);
705         temp2 = energy[2] * ((energy[3] * energy[3] + (1 << 14)) >> 15);
706         if (temp1 >= temp2) {
707             comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
708                            energy[2]);
709         } else {
710             comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
711                            energy[4]);
712         }
713     }
714 }
715
716 /**
717  * Classify frames as voiced/unvoiced.
718  *
719  * @param p         the context
720  * @param pitch_lag decoded pitch_lag
721  * @param exc_eng   excitation energy estimation
722  * @param scale     scaling factor of exc_eng
723  *
724  * @return residual interpolation index if voiced, 0 otherwise
725  */
726 static int comp_interp_index(G723_1_Context *p, int pitch_lag,
727                              int *exc_eng, int *scale)
728 {
729     int offset = PITCH_MAX + 2 * SUBFRAME_LEN;
730     int16_t *buf = p->excitation + offset;
731
732     int index, ccr, tgt_eng, best_eng, temp;
733
734     *scale = scale_vector(p->excitation, FRAME_LEN + PITCH_MAX);
735
736     /* Compute maximum backward cross-correlation */
737     ccr   = 0;
738     index = autocorr_max(p, offset, &ccr, pitch_lag, SUBFRAME_LEN * 2, -1);
739     ccr   = av_clipl_int32((int64_t)ccr + (1 << 15)) >> 16;
740
741     /* Compute target energy */
742     tgt_eng  = ff_dot_product(buf, buf, SUBFRAME_LEN * 2)<<1;
743     *exc_eng = av_clipl_int32(tgt_eng + (1 << 15)) >> 16;
744
745     if (ccr <= 0)
746         return 0;
747
748     /* Compute best energy */
749     best_eng = ff_dot_product(buf - index, buf - index,
750                               SUBFRAME_LEN * 2)<<1;
751     best_eng = av_clipl_int32((int64_t)best_eng + (1 << 15)) >> 16;
752
753     temp = best_eng * *exc_eng >> 3;
754
755     if (temp < ccr * ccr) {
756         return index;
757     } else
758         return 0;
759 }
760
761 /**
762  * Peform residual interpolation based on frame classification.
763  *
764  * @param buf   decoded excitation vector
765  * @param out   output vector
766  * @param lag   decoded pitch lag
767  * @param gain  interpolated gain
768  * @param rseed seed for random number generator
769  */
770 static void residual_interp(int16_t *buf, int16_t *out, int lag,
771                             int gain, int *rseed)
772 {
773     int i;
774     if (lag) { /* Voiced */
775         int16_t *vector_ptr = buf + PITCH_MAX;
776         /* Attenuate */
777         for (i = 0; i < lag; i++)
778             vector_ptr[i - lag] = vector_ptr[i - lag] * 3 >> 2;
779         av_memcpy_backptr((uint8_t*)vector_ptr, lag * sizeof(int16_t),
780                           FRAME_LEN * sizeof(int16_t));
781         memcpy(out, vector_ptr, FRAME_LEN * sizeof(int16_t));
782     } else {  /* Unvoiced */
783         for (i = 0; i < FRAME_LEN; i++) {
784             *rseed = *rseed * 521 + 259;
785             out[i] = gain * *rseed >> 15;
786         }
787         memset(buf, 0, (FRAME_LEN + PITCH_MAX) * sizeof(int16_t));
788     }
789 }
790
791 /**
792  * Perform IIR filtering.
793  *
794  * @param fir_coef FIR coefficients
795  * @param iir_coef IIR coefficients
796  * @param src      source vector
797  * @param dest     destination vector
798  * @param width    width of the output, 16 bits(0) / 32 bits(1)
799  */
800 #define iir_filter(fir_coef, iir_coef, src, dest, width)\
801 {\
802     int m, n;\
803     int res_shift = 16 & ~-(width);\
804     int in_shift  = 16 - res_shift;\
805 \
806     for (m = 0; m < SUBFRAME_LEN; m++) {\
807         int64_t filter = 0;\
808         for (n = 1; n <= LPC_ORDER; n++) {\
809             filter -= (fir_coef)[n - 1] * (src)[m - n] -\
810                       (iir_coef)[n - 1] * ((dest)[m - n] >> in_shift);\
811         }\
812 \
813         (dest)[m] = av_clipl_int32(((src)[m] << 16) + (filter << 3) +\
814                                    (1 << 15)) >> res_shift;\
815     }\
816 }
817
818 /**
819  * Adjust gain of postfiltered signal.
820  *
821  * @param p      the context
822  * @param buf    postfiltered output vector
823  * @param energy input energy coefficient
824  */
825 static void gain_scale(G723_1_Context *p, int16_t * buf, int energy)
826 {
827     int num, denom, gain, bits1, bits2;
828     int i;
829
830     num   = energy;
831     denom = 0;
832     for (i = 0; i < SUBFRAME_LEN; i++) {
833         int64_t temp = buf[i] >> 2;
834         temp  = av_clipl_int32(MUL64(temp, temp) << 1);
835         denom = av_clipl_int32(denom + temp);
836     }
837
838     if (num && denom) {
839         bits1   = normalize_bits(num, 1);
840         bits2   = normalize_bits(denom, 1);
841         num     = num << bits1 >> 1;
842         denom <<= bits2;
843
844         bits2 = 5 + bits1 - bits2;
845         bits2 = FFMAX(0, bits2);
846
847         gain = (num >> 1) / (denom >> 16);
848         gain = square_root(gain << 16 >> bits2);
849     } else {
850         gain = 1 << 12;
851     }
852
853     for (i = 0; i < SUBFRAME_LEN; i++) {
854         p->pf_gain = ((p->pf_gain << 4) - p->pf_gain + gain + (1 << 3)) >> 4;
855         buf[i]     = av_clip_int16((buf[i] * (p->pf_gain + (p->pf_gain >> 4)) +
856                                    (1 << 10)) >> 11);
857     }
858 }
859
860 /**
861  * Perform formant filtering.
862  *
863  * @param p   the context
864  * @param lpc quantized lpc coefficients
865  * @param buf output buffer
866  */
867 static void formant_postfilter(G723_1_Context *p, int16_t *lpc, int16_t *buf)
868 {
869     int16_t filter_coef[2][LPC_ORDER], *buf_ptr;
870     int filter_signal[LPC_ORDER + FRAME_LEN], *signal_ptr;
871     int i, j, k;
872
873     memcpy(buf, p->fir_mem, LPC_ORDER * sizeof(int16_t));
874     memcpy(filter_signal, p->iir_mem, LPC_ORDER * sizeof(int));
875
876     for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
877         for (k = 0; k < LPC_ORDER; k++) {
878             filter_coef[0][k] = (-lpc[k] * postfilter_tbl[0][k] +
879                                  (1 << 14)) >> 15;
880             filter_coef[1][k] = (-lpc[k] * postfilter_tbl[1][k] +
881                                  (1 << 14)) >> 15;
882         }
883         iir_filter(filter_coef[0], filter_coef[1], buf + i,
884                    filter_signal + i, 1);
885     }
886
887     memcpy(p->fir_mem, buf + FRAME_LEN, LPC_ORDER * sizeof(int16_t));
888     memcpy(p->iir_mem, filter_signal + FRAME_LEN, LPC_ORDER * sizeof(int));
889
890     buf_ptr    = buf + LPC_ORDER;
891     signal_ptr = filter_signal + LPC_ORDER;
892     for (i = 0; i < SUBFRAMES; i++) {
893         int16_t temp_vector[SUBFRAME_LEN];
894         int16_t temp;
895         int auto_corr[2];
896         int scale, energy;
897
898         /* Normalize */
899         memcpy(temp_vector, buf_ptr, SUBFRAME_LEN * sizeof(int16_t));
900         scale = scale_vector(temp_vector, SUBFRAME_LEN);
901
902         /* Compute auto correlation coefficients */
903         auto_corr[0] = ff_dot_product(temp_vector, temp_vector + 1,
904                                       SUBFRAME_LEN - 1)<<1;
905         auto_corr[1] = ff_dot_product(temp_vector, temp_vector,
906                                       SUBFRAME_LEN)<<1;
907
908         /* Compute reflection coefficient */
909         temp = auto_corr[1] >> 16;
910         if (temp) {
911             temp = (auto_corr[0] >> 2) / temp;
912         }
913         p->reflection_coef = ((p->reflection_coef << 2) - p->reflection_coef +
914                               temp + 2) >> 2;
915         temp = (p->reflection_coef * 0xffffc >> 3) & 0xfffc;
916
917         /* Compensation filter */
918         for (j = 0; j < SUBFRAME_LEN; j++) {
919             buf_ptr[j] = av_clipl_int32(signal_ptr[j] +
920                                         ((signal_ptr[j - 1] >> 16) *
921                                          temp << 1)) >> 16;
922         }
923
924         /* Compute normalized signal energy */
925         temp = 2 * scale + 4;
926         if (temp < 0) {
927             energy = av_clipl_int32((int64_t)auto_corr[1] << -temp);
928         } else
929             energy = auto_corr[1] >> temp;
930
931         gain_scale(p, buf_ptr, energy);
932
933         buf_ptr    += SUBFRAME_LEN;
934         signal_ptr += SUBFRAME_LEN;
935     }
936 }
937
938 static int g723_1_decode_frame(AVCodecContext *avctx, void *data,
939                                int *data_size, AVPacket *avpkt)
940 {
941     G723_1_Context *p  = avctx->priv_data;
942     const uint8_t *buf = avpkt->data;
943     int buf_size       = avpkt->size;
944     int16_t *out       = data;
945     int dec_mode       = buf[0] & 3;
946
947     PPFParam ppf[SUBFRAMES];
948     int16_t cur_lsp[LPC_ORDER];
949     int16_t lpc[SUBFRAMES * LPC_ORDER];
950     int16_t acb_vector[SUBFRAME_LEN];
951     int16_t *vector_ptr;
952     int bad_frame = 0, i, j;
953
954     if (!buf_size || buf_size < frame_size[dec_mode]) {
955         *data_size = 0;
956         return buf_size;
957     }
958
959     if (unpack_bitstream(p, buf, buf_size) < 0) {
960         bad_frame         = 1;
961         p->cur_frame_type = p->past_frame_type == ActiveFrame ?
962                             ActiveFrame : UntransmittedFrame;
963     }
964
965     *data_size = FRAME_LEN * sizeof(int16_t);
966     if(p->cur_frame_type == ActiveFrame) {
967         if (!bad_frame) {
968             p->erased_frames = 0;
969         } else if(p->erased_frames != 3)
970             p->erased_frames++;
971
972         inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, bad_frame);
973         lsp_interpolate(lpc, cur_lsp, p->prev_lsp);
974
975         /* Save the lsp_vector for the next frame */
976         memcpy(p->prev_lsp, cur_lsp, LPC_ORDER * sizeof(int16_t));
977
978         /* Generate the excitation for the frame */
979         memcpy(p->excitation, p->prev_excitation, PITCH_MAX * sizeof(int16_t));
980         vector_ptr = p->excitation + PITCH_MAX;
981         if (!p->erased_frames) {
982             /* Update interpolation gain memory */
983             p->interp_gain = fixed_cb_gain[(p->subframe[2].amp_index +
984                                             p->subframe[3].amp_index) >> 1];
985             for (i = 0; i < SUBFRAMES; i++) {
986                 gen_fcb_excitation(vector_ptr, p->subframe[i], p->cur_rate,
987                                    p->pitch_lag[i >> 1], i);
988                 gen_acb_excitation(acb_vector, &p->excitation[SUBFRAME_LEN * i],
989                                    p->pitch_lag[i >> 1], p->subframe[i],
990                                    p->cur_rate);
991                 /* Get the total excitation */
992                 for (j = 0; j < SUBFRAME_LEN; j++) {
993                     vector_ptr[j] = av_clip_int16(vector_ptr[j] << 1);
994                     vector_ptr[j] = av_clip_int16(vector_ptr[j] +
995                                                   acb_vector[j]);
996                 }
997                 vector_ptr += SUBFRAME_LEN;
998             }
999
1000             vector_ptr = p->excitation + PITCH_MAX;
1001
1002             /* Save the excitation */
1003             memcpy(out, vector_ptr, FRAME_LEN * sizeof(int16_t));
1004
1005             p->interp_index = comp_interp_index(p, p->pitch_lag[1],
1006                                                 &p->sid_gain, &p->cur_gain);
1007
1008             for (i = PITCH_MAX, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1009                 comp_ppf_coeff(p, i, p->pitch_lag[j >> 1],
1010                                ppf + j, p->cur_rate);
1011
1012             /* Restore the original excitation */
1013             memcpy(p->excitation, p->prev_excitation,
1014                    PITCH_MAX * sizeof(int16_t));
1015             memcpy(vector_ptr, out, FRAME_LEN * sizeof(int16_t));
1016
1017             /* Peform pitch postfiltering */
1018             for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1019                 ff_acelp_weighted_vector_sum(out + LPC_ORDER + i, vector_ptr + i,
1020                                              vector_ptr + i + ppf[j].index,
1021                                              ppf[j].sc_gain, ppf[j].opt_gain,
1022                                              1 << 14, 15, SUBFRAME_LEN);
1023         } else {
1024             p->interp_gain = (p->interp_gain * 3 + 2) >> 2;
1025             if (p->erased_frames == 3) {
1026                 /* Mute output */
1027                 memset(p->excitation, 0,
1028                        (FRAME_LEN + PITCH_MAX) * sizeof(int16_t));
1029                 memset(out, 0, (FRAME_LEN + LPC_ORDER) * sizeof(int16_t));
1030             } else {
1031                 /* Regenerate frame */
1032                 residual_interp(p->excitation, out + LPC_ORDER, p->interp_index,
1033                                 p->interp_gain, &p->random_seed);
1034             }
1035         }
1036         /* Save the excitation for the next frame */
1037         memcpy(p->prev_excitation, p->excitation + FRAME_LEN,
1038                PITCH_MAX * sizeof(int16_t));
1039     } else {
1040         memset(out, 0, *data_size);
1041         av_log(avctx, AV_LOG_WARNING,
1042                "G.723.1: Comfort noise generation not supported yet\n");
1043         return frame_size[dec_mode];
1044     }
1045
1046     p->past_frame_type = p->cur_frame_type;
1047
1048     memcpy(out, p->synth_mem, LPC_ORDER * sizeof(int16_t));
1049     for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1050         ff_celp_lp_synthesis_filter(out + i, &lpc[j * LPC_ORDER],
1051                                     out + i, SUBFRAME_LEN, LPC_ORDER,
1052                                     0, 1, 1 << 12);
1053     memcpy(p->synth_mem, out + FRAME_LEN, LPC_ORDER * sizeof(int16_t));
1054
1055     formant_postfilter(p, lpc, out);
1056
1057     memmove(out, out + LPC_ORDER, *data_size);
1058
1059     return frame_size[dec_mode];
1060 }
1061
1062 AVCodec ff_g723_1_decoder = {
1063     .name           = "g723_1",
1064     .type           = AVMEDIA_TYPE_AUDIO,
1065     .id             = CODEC_ID_G723_1,
1066     .priv_data_size = sizeof(G723_1_Context),
1067     .init           = g723_1_decode_init,
1068     .decode         = g723_1_decode_frame,
1069     .long_name      = NULL_IF_CONFIG_SMALL("G.723.1"),
1070     .capabilities   = CODEC_CAP_SUBFRAMES,
1071 };