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