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