]> git.sesse.net Git - ffmpeg/blob - libavcodec/evrcdec.c
aasc: fix 16bpp on big-endian
[ffmpeg] / libavcodec / evrcdec.c
1 /*
2  * Enhanced Variable Rate Codec, Service Option 3 decoder
3  * Copyright (c) 2013 Paul B Mahol
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * Enhanced Variable Rate Codec, Service Option 3 decoder
25  * @author Paul B Mahol
26  */
27
28 #include "libavutil/mathematics.h"
29 #include "avcodec.h"
30 #include "internal.h"
31 #include "get_bits.h"
32 #include "evrcdata.h"
33 #include "acelp_vectors.h"
34 #include "lsp.h"
35
36 #define MIN_LSP_SEP (0.05 / (2.0 * M_PI))
37 #define MIN_DELAY      20
38 #define MAX_DELAY     120
39 #define NB_SUBFRAMES    3
40 #define SUBFRAME_SIZE  54
41 #define FILTER_ORDER   10
42 #define ACB_SIZE      128
43
44 typedef enum {
45     RATE_ERRS = -1,
46     SILENCE,
47     RATE_QUANT,
48     RATE_QUARTER,
49     RATE_HALF,
50     RATE_FULL,
51 } evrc_packet_rate;
52
53 /**
54  * EVRC-A unpacked data frame
55  */
56 typedef struct EVRCAFrame {
57     uint8_t  lpc_flag;        ///< spectral change indicator
58     uint16_t lsp[4];          ///< index into LSP codebook
59     uint8_t  pitch_delay;     ///< pitch delay for entire frame
60     uint8_t  delay_diff;      ///< delay difference for entire frame
61     uint8_t  acb_gain[3];     ///< adaptive codebook gain
62     uint16_t fcb_shape[3][4]; ///< fixed codebook shape
63     uint8_t  fcb_gain[3];     ///< fixed codebook gain index
64     uint8_t  energy_gain;     ///< frame energy gain index
65     uint8_t  tty;             ///< tty baud rate bit
66 } EVRCAFrame;
67
68 typedef struct EVRCContext {
69     AVFrame          avframe;
70     GetBitContext    gb;
71     evrc_packet_rate bitrate;
72     evrc_packet_rate last_valid_bitrate;
73     EVRCAFrame       frame;
74
75     float            lspf[FILTER_ORDER];
76     float            prev_lspf[FILTER_ORDER];
77     float            synthesis[FILTER_ORDER];
78     float            postfilter_fir[FILTER_ORDER];
79     float            postfilter_iir[FILTER_ORDER];
80     float            postfilter_residual[ACB_SIZE + SUBFRAME_SIZE];
81     float            pitch_delay;
82     float            prev_pitch_delay;
83     float            avg_acb_gain;  ///< average adaptive codebook gain
84     float            avg_fcb_gain;  ///< average fixed codebook gain
85     float            pitch[ACB_SIZE + FILTER_ORDER + SUBFRAME_SIZE];
86     float            pitch_back[ACB_SIZE];
87     float            interpolation_coeffs[136];
88     float            energy_vector[NB_SUBFRAMES];
89     float            fade_scale;
90     float            last;
91
92     uint8_t          prev_energy_gain;
93     uint8_t          prev_error_flag;
94     uint8_t          warned_buf_mismatch_bitrate;
95 } EVRCContext;
96
97 /**
98  * Frame unpacking for RATE_FULL, RATE_HALF and RATE_QUANT
99  *
100  * @param e the context
101  *
102  * TIA/IS-127 Table 4.21-1
103  */
104 static void unpack_frame(EVRCContext *e)
105 {
106     EVRCAFrame *frame = &e->frame;
107     GetBitContext *gb = &e->gb;
108
109     switch (e->bitrate) {
110     case RATE_FULL:
111         frame->lpc_flag        = get_bits1(gb);
112         frame->lsp[0]          = get_bits(gb,  6);
113         frame->lsp[1]          = get_bits(gb,  6);
114         frame->lsp[2]          = get_bits(gb,  9);
115         frame->lsp[3]          = get_bits(gb,  7);
116         frame->pitch_delay     = get_bits(gb,  7);
117         frame->delay_diff      = get_bits(gb,  5);
118         frame->acb_gain[0]     = get_bits(gb,  3);
119         frame->fcb_shape[0][0] = get_bits(gb,  8);
120         frame->fcb_shape[0][1] = get_bits(gb,  8);
121         frame->fcb_shape[0][2] = get_bits(gb,  8);
122         frame->fcb_shape[0][3] = get_bits(gb, 11);
123         frame->fcb_gain[0]     = get_bits(gb,  5);
124         frame->acb_gain[1]     = get_bits(gb,  3);
125         frame->fcb_shape[1][0] = get_bits(gb,  8);
126         frame->fcb_shape[1][1] = get_bits(gb,  8);
127         frame->fcb_shape[1][2] = get_bits(gb,  8);
128         frame->fcb_shape[1][3] = get_bits(gb, 11);
129         frame->fcb_gain    [1] = get_bits(gb,  5);
130         frame->acb_gain    [2] = get_bits(gb,  3);
131         frame->fcb_shape[2][0] = get_bits(gb,  8);
132         frame->fcb_shape[2][1] = get_bits(gb,  8);
133         frame->fcb_shape[2][2] = get_bits(gb,  8);
134         frame->fcb_shape[2][3] = get_bits(gb, 11);
135         frame->fcb_gain    [2] = get_bits(gb,  5);
136         frame->tty             = get_bits1(gb);
137         break;
138     case RATE_HALF:
139         frame->lsp         [0] = get_bits(gb,  7);
140         frame->lsp         [1] = get_bits(gb,  7);
141         frame->lsp         [2] = get_bits(gb,  8);
142         frame->pitch_delay     = get_bits(gb,  7);
143         frame->acb_gain    [0] = get_bits(gb,  3);
144         frame->fcb_shape[0][0] = get_bits(gb, 10);
145         frame->fcb_gain    [0] = get_bits(gb,  4);
146         frame->acb_gain    [1] = get_bits(gb,  3);
147         frame->fcb_shape[1][0] = get_bits(gb, 10);
148         frame->fcb_gain    [1] = get_bits(gb,  4);
149         frame->acb_gain    [2] = get_bits(gb,  3);
150         frame->fcb_shape[2][0] = get_bits(gb, 10);
151         frame->fcb_gain    [2] = get_bits(gb,  4);
152         break;
153     case RATE_QUANT:
154         frame->lsp         [0] = get_bits(gb, 4);
155         frame->lsp         [1] = get_bits(gb, 4);
156         frame->energy_gain     = get_bits(gb, 8);
157         break;
158     }
159 }
160
161 static evrc_packet_rate buf_size2bitrate(const int buf_size)
162 {
163     switch (buf_size) {
164     case 23: return RATE_FULL;
165     case 11: return RATE_HALF;
166     case  6: return RATE_QUARTER;
167     case  3: return RATE_QUANT;
168     case  1: return SILENCE;
169     }
170
171     return RATE_ERRS;
172 }
173
174 /**
175  * Determine the bitrate from the frame size and/or the first byte of the frame.
176  *
177  * @param avctx the AV codec context
178  * @param buf_size length of the buffer
179  * @param buf the bufffer
180  *
181  * @return the bitrate on success,
182  *         RATE_ERRS  if the bitrate cannot be satisfactorily determined
183  */
184 static evrc_packet_rate determine_bitrate(AVCodecContext *avctx,
185                                           int *buf_size,
186                                           const uint8_t **buf)
187 {
188     evrc_packet_rate bitrate;
189
190     if ((bitrate = buf_size2bitrate(*buf_size)) >= 0) {
191         if (bitrate > **buf) {
192             EVRCContext *e = avctx->priv_data;
193             if (!e->warned_buf_mismatch_bitrate) {
194                 av_log(avctx, AV_LOG_WARNING,
195                        "Claimed bitrate and buffer size mismatch.\n");
196                 e->warned_buf_mismatch_bitrate = 1;
197             }
198             bitrate = **buf;
199         } else if (bitrate < **buf) {
200             av_log(avctx, AV_LOG_ERROR,
201                    "Buffer is too small for the claimed bitrate.\n");
202             return RATE_ERRS;
203         }
204         (*buf)++;
205         *buf_size -= 1;
206     } else if ((bitrate = buf_size2bitrate(*buf_size + 1)) >= 0) {
207         av_log(avctx, AV_LOG_DEBUG,
208                "Bitrate byte is missing, guessing the bitrate from packet size.\n");
209     } else
210         return RATE_ERRS;
211
212     return bitrate;
213 }
214
215 static void warn_insufficient_frame_quality(AVCodecContext *avctx,
216                                             const char *message)
217 {
218     av_log(avctx, AV_LOG_WARNING, "Frame #%d, %s\n",
219            avctx->frame_number, message);
220 }
221
222 /**
223  * Initialize the speech codec according to the specification.
224  *
225  * TIA/IS-127 5.2
226  */
227 static av_cold int evrc_decode_init(AVCodecContext *avctx)
228 {
229     EVRCContext *e = avctx->priv_data;
230     int i, n, idx = 0;
231     float denom = 2.0 / (2.0 * 8.0 + 1.0);
232
233     avcodec_get_frame_defaults(&e->avframe);
234     avctx->coded_frame = &e->avframe;
235
236     avctx->channels       = 1;
237     avctx->channel_layout = AV_CH_LAYOUT_MONO;
238     avctx->sample_fmt     = AV_SAMPLE_FMT_FLT;
239
240     for (i = 0; i < FILTER_ORDER; i++) {
241         e->prev_lspf[i] = (i + 1) * 0.048;
242         e->synthesis[i] = 0.0;
243     }
244
245     for (i = 0; i < ACB_SIZE; i++)
246         e->pitch[i] = e->pitch_back[i] = 0.0;
247
248     e->last_valid_bitrate = RATE_QUANT;
249     e->prev_pitch_delay   = 40.0;
250     e->fade_scale         = 1.0;
251     e->prev_error_flag    = 0;
252     e->avg_acb_gain = e->avg_fcb_gain = 0.0;
253
254     for (i = 0; i < 8; i++) {
255         float tt = ((float)i - 8.0 / 2.0) / 8.0;
256
257         for (n = -8; n <= 8; n++, idx++) {
258             float arg1 = M_PI * 0.9 * (tt - n);
259             float arg2 = M_PI * (tt - n);
260
261             e->interpolation_coeffs[idx] = 0.9;
262             if (arg1)
263                 e->interpolation_coeffs[idx] *= (0.54 + 0.46 * cos(arg2 * denom)) *
264                                                  sin(arg1) / arg1;
265         }
266     }
267
268     return 0;
269 }
270
271 /**
272  * Decode the 10 vector quantized line spectral pair frequencies from the LSP
273  * transmission codes of any bitrate and check for badly received packets.
274  *
275  * @param e the context
276  *
277  * @return 0 on success, -1 if the packet is badly received
278  *
279  * TIA/IS-127 5.2.1, 5.7.1
280  */
281 static int decode_lspf(EVRCContext *e)
282 {
283     const float **codebooks = evrc_lspq_codebooks[e->bitrate];
284     int i, j, k = 0;
285
286     for (i = 0; i < evrc_lspq_nb_codebooks[e->bitrate]; i++) {
287         int row_size = evrc_lspq_codebooks_row_sizes[e->bitrate][i];
288         const float *codebook = codebooks[i];
289
290         for (j = 0; j < row_size; j++)
291             e->lspf[k++] = codebook[e->frame.lsp[i] * row_size + j];
292     }
293
294     // check for monotonic LSPs
295     for (i = 1; i < FILTER_ORDER; i++)
296         if (e->lspf[i] <= e->lspf[i - 1])
297             return -1;
298
299     // check for minimum separation of LSPs at the splits
300     for (i = 0, k = 0; i < evrc_lspq_nb_codebooks[e->bitrate] - 1; i++) {
301         k += evrc_lspq_codebooks_row_sizes[e->bitrate][i];
302         if (e->lspf[k] - e->lspf[k - 1] <= MIN_LSP_SEP)
303             return -1;
304     }
305
306     return 0;
307 }
308
309 /*
310  * Interpolation of LSP parameters.
311  *
312  * TIA/IS-127 5.2.3.1, 5.7.3.2
313  */
314 static void interpolate_lsp(float *ilsp, const float *lsp,
315                             const float *prev, int index)
316 {
317     static const float lsp_interpolation_factors[] = { 0.1667, 0.5, 0.8333 };
318     ff_weighted_vector_sumf(ilsp, prev, lsp,
319                             1.0 - lsp_interpolation_factors[index],
320                             lsp_interpolation_factors[index], FILTER_ORDER);
321 }
322
323 /*
324  * Reconstruction of the delay contour.
325  *
326  * TIA/IS-127 5.2.2.3.2
327  */
328 static void interpolate_delay(float *dst, float current, float prev, int index)
329 {
330     static const float d_interpolation_factors[] = { 0, 0.3313, 0.6625, 1, 1 };
331     dst[0] = (1.0 - d_interpolation_factors[index    ]) * prev
332                   + d_interpolation_factors[index    ]  * current;
333     dst[1] = (1.0 - d_interpolation_factors[index + 1]) * prev
334                   + d_interpolation_factors[index + 1]  * current;
335     dst[2] = (1.0 - d_interpolation_factors[index + 2]) * prev
336                   + d_interpolation_factors[index + 2]  * current;
337 }
338
339 /*
340  * Convert the quantized, interpolated line spectral frequencies,
341  * to prediction coefficients.
342  *
343  * TIA/IS-127 5.2.3.2, 4.7.2.2
344  */
345 static void decode_predictor_coeffs(const float *ilspf, float *ilpc)
346 {
347     double lsp[FILTER_ORDER];
348     float a[FILTER_ORDER / 2 + 1], b[FILTER_ORDER / 2 + 1];
349     float a1[FILTER_ORDER / 2] = { 0 };
350     float a2[FILTER_ORDER / 2] = { 0 };
351     float b1[FILTER_ORDER / 2] = { 0 };
352     float b2[FILTER_ORDER / 2] = { 0 };
353     int i, k;
354
355     ff_acelp_lsf2lspd(lsp, ilspf, FILTER_ORDER);
356
357     for (k = 0; k <= FILTER_ORDER; k++) {
358         a[0] = k < 2 ? 0.25 : 0;
359         b[0] = k < 2 ? k < 1 ? 0.25 : -0.25 : 0;
360
361         for (i = 0; i < FILTER_ORDER / 2; i++) {
362             a[i + 1] = a[i] - 2 * lsp[i * 2    ] * a1[i] + a2[i];
363             b[i + 1] = b[i] - 2 * lsp[i * 2 + 1] * b1[i] + b2[i];
364             a2[i] = a1[i];
365             a1[i] = a[i];
366             b2[i] = b1[i];
367             b1[i] = b[i];
368         }
369
370         if (k)
371             ilpc[k - 1] = 2.0 * (a[FILTER_ORDER / 2] + b[FILTER_ORDER / 2]);
372     }
373 }
374
375 static void bl_intrp(EVRCContext *e, float *ex, float delay)
376 {
377     float *f;
378     int offset, i, coef_idx;
379     int16_t t;
380
381     offset = lrintf(fabs(delay));
382
383     t = (offset - delay + 0.5) * 8.0 + 0.5;
384     if (t == 8) {
385         t = 0;
386         offset--;
387     }
388
389     f = ex - offset - 8;
390
391     coef_idx = t * (2 * 8 + 1);
392
393     ex[0] = 0.0;
394     for (i = 0; i < 2 * 8 + 1; i++)
395         ex[0] += e->interpolation_coeffs[coef_idx + i] * f[i];
396 }
397
398 /*
399  * Adaptive codebook excitation.
400  *
401  * TIA/IS-127 5.2.2.3.3, 4.12.5.2
402  */
403 static void acb_excitation(EVRCContext *e, float *excitation, float gain,
404                            const float delay[3], int length)
405 {
406     float denom, locdelay, dpr, invl;
407     int i;
408
409     invl = 1.0 / ((float) length);
410     dpr = length;
411
412     /* first at-most extra samples */
413     denom = (delay[1] - delay[0]) * invl;
414     for (i = 0; i < dpr; i++) {
415         locdelay = delay[0] + i * denom;
416         bl_intrp(e, excitation + i, locdelay);
417     }
418
419     denom = (delay[2] - delay[1]) * invl;
420     /* interpolation */
421     for (i = dpr; i < dpr + 10; i++) {
422         locdelay = delay[1] + (i - dpr) * denom;
423         bl_intrp(e, excitation + i, locdelay);
424     }
425
426     for (i = 0; i < length; i++)
427         excitation[i] *= gain;
428 }
429
430 static void decode_8_pulses_35bits(const uint16_t *fixed_index, float *cod)
431 {
432     int i, pos1, pos2, offset;
433
434     offset = (fixed_index[3] >> 9) & 3;
435
436     for (i = 0; i < 3; i++) {
437         pos1 = ((fixed_index[i] & 0x7f) / 11) * 5 + ((i + offset) % 5);
438         pos2 = ((fixed_index[i] & 0x7f) % 11) * 5 + ((i + offset) % 5);
439
440         cod[pos1] = (fixed_index[i] & 0x80) ? -1.0 : 1.0;
441
442         if (pos2 < pos1)
443             cod[pos2]  = -cod[pos1];
444         else
445             cod[pos2] +=  cod[pos1];
446     }
447
448     pos1 = ((fixed_index[3] & 0x7f) / 11) * 5 + ((3 + offset) % 5);
449     pos2 = ((fixed_index[3] & 0x7f) % 11) * 5 + ((4 + offset) % 5);
450
451     cod[pos1] = (fixed_index[3] & 0x100) ? -1.0 : 1.0;
452     cod[pos2] = (fixed_index[3] & 0x80 ) ? -1.0 : 1.0;
453 }
454
455 static void decode_3_pulses_10bits(uint16_t fixed_index, float *cod)
456 {
457     float sign;
458     int pos;
459
460     sign = (fixed_index & 0x200) ? -1.0 : 1.0;
461
462     pos = ((fixed_index        & 0x7) * 7) + 4;
463     cod[pos] += sign;
464     pos = (((fixed_index >> 3) & 0x7) * 7) + 2;
465     cod[pos] -= sign;
466     pos = (((fixed_index >> 6) & 0x7) * 7);
467     cod[pos] += sign;
468 }
469
470 /*
471  * Reconstruction of ACELP fixed codebook excitation for full and half rate.
472  *
473  * TIA/IS-127 5.2.3.7
474  */
475 static void fcb_excitation(EVRCContext *e, const uint16_t *codebook,
476                            float *excitation, float pitch_gain,
477                            int pitch_lag, int subframe_size)
478 {
479     int i;
480
481     if (e->bitrate == RATE_FULL)
482         decode_8_pulses_35bits(codebook, excitation);
483     else
484         decode_3_pulses_10bits(*codebook, excitation);
485
486     pitch_gain = av_clipf(pitch_gain, 0.2, 0.9);
487
488     for (i = pitch_lag; i < subframe_size; i++)
489         excitation[i] += pitch_gain * excitation[i - pitch_lag];
490 }
491
492 /**
493  * Synthesis of the decoder output signal.
494  *
495  * param[in]     in              input signal
496  * param[in]     filter_coeffs   LPC coefficients
497  * param[in/out] memory          synthesis filter memory
498  * param         buffer_length   amount of data to process
499  * param[out]    samples         output samples
500  *
501  * TIA/IS-127 5.2.3.15, 5.7.3.4
502  */
503 static void synthesis_filter(const float *in, const float *filter_coeffs,
504                              float *memory, int buffer_length, float *samples)
505 {
506     int i, j;
507
508     for (i = 0; i < buffer_length; i++) {
509         samples[i] = in[i];
510         for (j = FILTER_ORDER - 1; j > 0; j--) {
511             samples[i] -= filter_coeffs[j] * memory[j];
512             memory[j]   = memory[j - 1];
513         }
514         samples[i] -= filter_coeffs[0] * memory[0];
515         memory[0]   = samples[i];
516     }
517 }
518
519 static void bandwidth_expansion(float *coeff, const float *inbuf, float gamma)
520 {
521     double fac = gamma;
522     int i;
523
524     for (i = 0; i < FILTER_ORDER; i++) {
525         coeff[i] = inbuf[i] * fac;
526         fac *= gamma;
527     }
528 }
529
530 static void residual_filter(float *output, const float *input,
531                             const float *coef, float *memory, int length)
532 {
533     float sum;
534     int i, j;
535
536     for (i = 0; i < length; i++) {
537         sum = input[i];
538
539         for (j = FILTER_ORDER - 1; j > 0; j--) {
540             sum      += coef[j] * memory[j];
541             memory[j] = memory[j - 1];
542         }
543         sum += coef[0] * memory[0];
544         memory[0] = input[i];
545         output[i] = sum;
546     }
547 }
548
549 /*
550  * TIA/IS-127 Table 5.9.1-1.
551  */
552 static const struct PfCoeff {
553     float tilt;
554     float ltgain;
555     float p1;
556     float p2;
557 } postfilter_coeffs[5] = {
558     { 0.0 , 0.0 , 0.0 , 0.0  },
559     { 0.0 , 0.0 , 0.57, 0.57 },
560     { 0.0 , 0.0 , 0.0 , 0.0  },
561     { 0.35, 0.50, 0.50, 0.75 },
562     { 0.20, 0.50, 0.57, 0.75 },
563 };
564
565 /*
566  * Adaptive postfilter.
567  *
568  * TIA/IS-127 5.9
569  */
570 static void postfilter(EVRCContext *e, float *in, const float *coeff,
571                        float *out, int idx, const struct PfCoeff *pfc,
572                        int length)
573 {
574     float wcoef1[FILTER_ORDER], wcoef2[FILTER_ORDER],
575           scratch[SUBFRAME_SIZE], temp[SUBFRAME_SIZE],
576           mem[SUBFRAME_SIZE];
577     float sum1 = 0.0, sum2 = 0.0, gamma, gain;
578     float tilt = pfc->tilt;
579     int i, n, best;
580
581     bandwidth_expansion(wcoef1, coeff, pfc->p1);
582     bandwidth_expansion(wcoef2, coeff, pfc->p2);
583
584     /* Tilt compensation filter, TIA/IS-127 5.9.1 */
585     for (i = 0; i < length - 1; i++)
586         sum2 += in[i] * in[i + 1];
587     if (sum2 < 0.0)
588         tilt = 0.0;
589
590     for (i = 0; i < length; i++) {
591         scratch[i] = in[i] - tilt * e->last;
592         e->last = in[i];
593     }
594
595     /* Short term residual filter, TIA/IS-127 5.9.2 */
596     residual_filter(&e->postfilter_residual[ACB_SIZE], scratch, wcoef1, e->postfilter_fir, length);
597
598     /* Long term postfilter */
599     best = idx;
600     for (i = FFMIN(MIN_DELAY, idx - 3); i <= FFMAX(MAX_DELAY, idx + 3); i++) {
601         for (n = ACB_SIZE, sum2 = 0; n < ACB_SIZE + length; n++)
602             sum2 += e->postfilter_residual[n] * e->postfilter_residual[n - i];
603         if (sum2 > sum1) {
604             sum1 = sum2;
605             best = i;
606         }
607     }
608
609     for (i = ACB_SIZE, sum1 = 0; i < ACB_SIZE + length; i++)
610         sum1 += e->postfilter_residual[i - best] * e->postfilter_residual[i - best];
611     for (i = ACB_SIZE, sum2 = 0; i < ACB_SIZE + length; i++)
612         sum2 += e->postfilter_residual[i] * e->postfilter_residual[i - best];
613
614     if (sum2 * sum1 == 0 || e->bitrate == RATE_QUANT) {
615         memcpy(temp, e->postfilter_residual + ACB_SIZE, length * sizeof(float));
616     } else {
617         gamma = sum2 / sum1;
618         if (gamma < 0.5)
619             memcpy(temp, e->postfilter_residual + ACB_SIZE, length * sizeof(float));
620         else {
621             gamma = FFMIN(gamma, 1.0);
622
623             for (i = 0; i < length; i++) {
624                 temp[i] = e->postfilter_residual[ACB_SIZE + i] + gamma *
625                     pfc->ltgain * e->postfilter_residual[ACB_SIZE + i - best];
626             }
627         }
628     }
629
630     memcpy(scratch, temp, length * sizeof(float));
631     memcpy(mem, e->postfilter_iir, FILTER_ORDER * sizeof(float));
632     synthesis_filter(scratch, wcoef2, mem, length, scratch);
633
634     /* Gain computation, TIA/IS-127 5.9.4-2 */
635     for (i = 0, sum1 = 0, sum2 = 0; i < length; i++) {
636         sum1 += in[i] * in[i];
637         sum2 += scratch[i] * scratch[i];
638     }
639     gain = sum2 ? sqrt(sum1 / sum2) : 1.0;
640
641     for (i = 0; i < length; i++)
642         temp[i] *= gain;
643
644     /* Short term postfilter */
645     synthesis_filter(temp, wcoef2, e->postfilter_iir, length, out);
646
647     memcpy(e->postfilter_residual,
648            e->postfilter_residual + length, ACB_SIZE * sizeof(float));
649 }
650
651 static void frame_erasure(EVRCContext *e, float *samples)
652 {
653     float ilspf[FILTER_ORDER], ilpc[FILTER_ORDER], idelay[NB_SUBFRAMES],
654           tmp[SUBFRAME_SIZE + 6], f;
655     int i, j;
656
657     for (i = 0; i < FILTER_ORDER; i++) {
658         if (e->bitrate != RATE_QUANT)
659             e->lspf[i] = e->prev_lspf[i] * 0.875 + 0.125 * (i + 1) * 0.048;
660         else
661             e->lspf[i] = e->prev_lspf[i];
662     }
663
664     if (e->prev_error_flag)
665         e->avg_acb_gain *= 0.75;
666     if (e->bitrate == RATE_FULL)
667         memcpy(e->pitch_back, e->pitch, ACB_SIZE * sizeof(float));
668     if (e->last_valid_bitrate == RATE_QUANT)
669         e->bitrate = RATE_QUANT;
670     else
671         e->bitrate = RATE_FULL;
672
673     if (e->bitrate == RATE_FULL || e->bitrate == RATE_HALF) {
674         e->pitch_delay = e->prev_pitch_delay;
675     } else {
676         float sum = 0;
677
678         idelay[0] = idelay[1] = idelay[2] = MIN_DELAY;
679
680         for (i = 0; i < NB_SUBFRAMES; i++)
681             sum += evrc_energy_quant[e->prev_energy_gain][i];
682         sum /= (float) NB_SUBFRAMES;
683         sum  = pow(10, sum);
684         for (i = 0; i < NB_SUBFRAMES; i++)
685             e->energy_vector[i] = sum;
686     }
687
688     if (fabs(e->pitch_delay - e->prev_pitch_delay) > 15)
689         e->prev_pitch_delay = e->pitch_delay;
690
691     for (i = 0; i < NB_SUBFRAMES; i++) {
692         int subframe_size = subframe_sizes[i];
693         int pitch_lag;
694
695         interpolate_lsp(ilspf, e->lspf, e->prev_lspf, i);
696
697         if (e->bitrate != RATE_QUANT) {
698             if (e->avg_acb_gain < 0.3) {
699                 idelay[0] = estimation_delay[i];
700                 idelay[1] = estimation_delay[i + 1];
701                 idelay[2] = estimation_delay[i + 2];
702             } else {
703                 interpolate_delay(idelay, e->pitch_delay, e->prev_pitch_delay, i);
704             }
705         }
706
707         pitch_lag = lrintf((idelay[1] + idelay[0]) / 2.0);
708         decode_predictor_coeffs(ilspf, ilpc);
709
710         if (e->bitrate != RATE_QUANT) {
711             acb_excitation(e, e->pitch + ACB_SIZE,
712                            e->avg_acb_gain, idelay, subframe_size);
713             for (j = 0; j < subframe_size; j++)
714                 e->pitch[ACB_SIZE + j] *= e->fade_scale;
715             e->fade_scale = FFMAX(e->fade_scale - 0.05, 0.0);
716         } else {
717             for (j = 0; j < subframe_size; j++)
718                 e->pitch[ACB_SIZE + j] = e->energy_vector[i];
719         }
720
721         memcpy(e->pitch, e->pitch + subframe_size, ACB_SIZE * sizeof(float));
722
723         if (e->bitrate != RATE_QUANT && e->avg_acb_gain < 0.4) {
724             f = 0.1 * e->avg_fcb_gain;
725             for (j = 0; j < subframe_size; j++)
726                 e->pitch[ACB_SIZE + j] += f;
727         } else if (e->bitrate == RATE_QUANT) {
728             for (j = 0; j < subframe_size; j++)
729                 e->pitch[ACB_SIZE + j] = e->energy_vector[i];
730         }
731
732         synthesis_filter(e->pitch + ACB_SIZE, ilpc,
733                          e->synthesis, subframe_size, tmp);
734         postfilter(e, tmp, ilpc, samples, pitch_lag,
735                    &postfilter_coeffs[e->bitrate], subframe_size);
736
737         samples += subframe_size;
738     }
739 }
740
741 static int evrc_decode_frame(AVCodecContext *avctx, void *data,
742                              int *got_frame_ptr, AVPacket *avpkt)
743 {
744     const uint8_t *buf = avpkt->data;
745     EVRCContext *e     = avctx->priv_data;
746     int buf_size       = avpkt->size;
747     float ilspf[FILTER_ORDER], ilpc[FILTER_ORDER], idelay[NB_SUBFRAMES];
748     float *samples;
749     int   i, j, ret, error_flag = 0;
750
751     e->avframe.nb_samples = 160;
752     if ((ret = ff_get_buffer(avctx, &e->avframe)) < 0)
753         return ret;
754     samples = (float *)e->avframe.data[0];
755
756     if ((e->bitrate = determine_bitrate(avctx, &buf_size, &buf)) == RATE_ERRS) {
757         warn_insufficient_frame_quality(avctx, "bitrate cannot be determined.");
758         goto erasure;
759     }
760     if (e->bitrate <= SILENCE || e->bitrate == RATE_QUARTER)
761         goto erasure;
762     if (e->bitrate == RATE_QUANT && e->last_valid_bitrate == RATE_FULL
763                                  && !e->prev_error_flag)
764         goto erasure;
765
766     init_get_bits(&e->gb, buf, 8 * buf_size);
767     memset(&e->frame, 0, sizeof(EVRCAFrame));
768
769     unpack_frame(e);
770
771     if (e->bitrate != RATE_QUANT) {
772         uint8_t *p = (uint8_t *) &e->frame;
773         for (i = 0; i < sizeof(EVRCAFrame); i++) {
774             if (p[i])
775                 break;
776         }
777         if (i == sizeof(EVRCAFrame))
778             goto erasure;
779     } else if (e->frame.lsp[0] == e->frame.lsp[1] == 0xf &&
780                e->frame.energy_gain == 0xff) {
781         goto erasure;
782     }
783
784     if (decode_lspf(e) < 0)
785         goto erasure;
786
787     if (e->bitrate == RATE_FULL || e->bitrate == RATE_HALF) {
788         /* Pitch delay parameter checking as per TIA/IS-127 5.1.5.1 */
789         if (e->frame.pitch_delay > MAX_DELAY - MIN_DELAY)
790             goto erasure;
791
792         e->pitch_delay = e->frame.pitch_delay + MIN_DELAY;
793
794         /* Delay diff parameter checking as per TIA/IS-127 5.1.5.2 */
795         if (e->frame.delay_diff) {
796             int p = e->pitch_delay - e->frame.delay_diff + 16;
797             if (p < MIN_DELAY || p > MAX_DELAY)
798                 goto erasure;
799         }
800
801         /* Delay contour reconstruction as per TIA/IS-127 5.2.2.2 */
802         if (e->frame.delay_diff &&
803             e->bitrate == RATE_FULL && e->prev_error_flag) {
804             float delay;
805
806             memcpy(e->pitch, e->pitch_back, ACB_SIZE * sizeof(float));
807
808             delay = e->prev_pitch_delay;
809             e->prev_pitch_delay = delay - e->frame.delay_diff + 16.0;
810
811             if (fabs(e->pitch_delay - delay) > 15)
812                 delay = e->pitch_delay;
813
814             for (i = 0; i < NB_SUBFRAMES; i++) {
815                 int subframe_size = subframe_sizes[i];
816
817                 interpolate_delay(idelay, delay, e->prev_pitch_delay, i);
818                 acb_excitation(e, e->pitch + ACB_SIZE, e->avg_acb_gain, idelay, subframe_size);
819                 memcpy(e->pitch, e->pitch + subframe_size, ACB_SIZE * sizeof(float));
820             }
821         }
822
823         /* Smoothing of the decoded delay as per TIA/IS-127 5.2.2.5 */
824         if (fabs(e->pitch_delay - e->prev_pitch_delay) > 15)
825             e->prev_pitch_delay = e->pitch_delay;
826
827         e->avg_acb_gain = e->avg_fcb_gain = 0.0;
828     } else {
829         idelay[0] = idelay[1] = idelay[2] = MIN_DELAY;
830
831         /* Decode frame energy vectors as per TIA/IS-127 5.7.2 */
832         for (i = 0; i < NB_SUBFRAMES; i++)
833             e->energy_vector[i] = pow(10, evrc_energy_quant[e->frame.energy_gain][i]);
834         e->prev_energy_gain = e->frame.energy_gain;
835     }
836
837     for (i = 0; i < NB_SUBFRAMES; i++) {
838         float tmp[SUBFRAME_SIZE + 6] = { 0 };
839         int subframe_size = subframe_sizes[i];
840         int pitch_lag;
841
842         interpolate_lsp(ilspf, e->lspf, e->prev_lspf, i);
843
844         if (e->bitrate != RATE_QUANT)
845             interpolate_delay(idelay, e->pitch_delay, e->prev_pitch_delay, i);
846
847         pitch_lag = lrintf((idelay[1] + idelay[0]) / 2.0);
848         decode_predictor_coeffs(ilspf, ilpc);
849
850         /* Bandwidth expansion as per TIA/IS-127 5.2.3.3 */
851         if (e->frame.lpc_flag && e->prev_error_flag)
852             bandwidth_expansion(ilpc, ilpc, 0.75);
853
854         if (e->bitrate != RATE_QUANT) {
855             float acb_sum, f;
856
857             f = exp((e->bitrate == RATE_HALF ? 0.5 : 0.25)
858                          * (e->frame.fcb_gain[i] + 1));
859             acb_sum = pitch_gain_vq[e->frame.acb_gain[i]];
860             e->avg_acb_gain += acb_sum / NB_SUBFRAMES;
861             e->avg_fcb_gain += f / NB_SUBFRAMES;
862
863             acb_excitation(e, e->pitch + ACB_SIZE,
864                            acb_sum, idelay, subframe_size);
865             fcb_excitation(e, e->frame.fcb_shape[i], tmp,
866                            acb_sum, pitch_lag, subframe_size);
867
868             /* Total excitation generation as per TIA/IS-127 5.2.3.9 */
869             for (j = 0; j < subframe_size; j++)
870                 e->pitch[ACB_SIZE + j] += f * tmp[j];
871             e->fade_scale = FFMIN(e->fade_scale + 0.2, 1.0);
872         } else {
873             for (j = 0; j < subframe_size; j++)
874                 e->pitch[ACB_SIZE + j] = e->energy_vector[i];
875         }
876
877         memcpy(e->pitch, e->pitch + subframe_size, ACB_SIZE * sizeof(float));
878
879         synthesis_filter(e->pitch + ACB_SIZE, ilpc,
880                          e->synthesis, subframe_size, tmp);
881         postfilter(e, tmp, ilpc, samples, pitch_lag,
882                    &postfilter_coeffs[e->bitrate], subframe_size);
883
884         samples += subframe_size;
885     }
886
887     if (error_flag) {
888 erasure:
889         error_flag = 1;
890         av_log(avctx, AV_LOG_WARNING, "frame erasure\n");
891         frame_erasure(e, samples);
892     }
893
894     memcpy(e->prev_lspf, e->lspf, sizeof(e->prev_lspf));
895     e->prev_error_flag    = error_flag;
896     e->last_valid_bitrate = e->bitrate;
897
898     if (e->bitrate != RATE_QUANT)
899         e->prev_pitch_delay = e->pitch_delay;
900
901     samples = (float *)e->avframe.data[0];
902     for (i = 0; i < 160; i++)
903         samples[i] /= 32768;
904
905     *got_frame_ptr   = 1;
906     *(AVFrame *)data = e->avframe;
907
908     return avpkt->size;
909 }
910
911 AVCodec ff_evrc_decoder = {
912     .name           = "evrc",
913     .type           = AVMEDIA_TYPE_AUDIO,
914     .id             = AV_CODEC_ID_EVRC,
915     .init           = evrc_decode_init,
916     .decode         = evrc_decode_frame,
917     .capabilities   = CODEC_CAP_DR1,
918     .priv_data_size = sizeof(EVRCContext),
919     .long_name      = NULL_IF_CONFIG_SMALL("EVRC (Enhanced Variable Rate Codec)"),
920 };