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