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