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