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