OSDN Git Service

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