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