twinvq.c 26.9 KB
Newer Older
Vitor Sessak's avatar
Vitor Sessak committed
1 2 3 4
/*
 * TwinVQ decoder
 * Copyright (c) 2009 Vitor Sessak
 *
5
 * This file is part of Libav.
Vitor Sessak's avatar
Vitor Sessak committed
6
 *
7
 * Libav is free software; you can redistribute it and/or
Vitor Sessak's avatar
Vitor Sessak committed
8 9 10 11
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
12
 * Libav is distributed in the hope that it will be useful,
Vitor Sessak's avatar
Vitor Sessak committed
13 14 15 16 17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with Libav; if not, write to the Free Software
Vitor Sessak's avatar
Vitor Sessak committed
19 20 21
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

22 23 24
#include <math.h>
#include <stdint.h>

25
#include "libavutil/channel_layout.h"
26
#include "libavutil/float_dsp.h"
Vitor Sessak's avatar
Vitor Sessak committed
27
#include "avcodec.h"
28
#include "fft.h"
29
#include "internal.h"
30
#include "lsp.h"
31
#include "sinewin.h"
32
#include "twinvq.h"
Vitor Sessak's avatar
Vitor Sessak committed
33 34 35 36 37

/**
 * Evaluate a single LPC amplitude spectrum envelope coefficient from the line
 * spectrum pairs.
 *
Diego Biurrun's avatar
Diego Biurrun committed
38
 * @param lsp a vector of the cosine of the LSP values
Vitor Sessak's avatar
Vitor Sessak committed
39 40 41 42 43
 * @param cos_val cos(PI*i/N) where i is the index of the LPC amplitude
 * @param order the order of the LSP (and the size of the *lsp buffer). Must
 *        be a multiple of four.
 * @return the LPC value
 *
44
 * @todo reuse code from Vorbis decoder: vorbis_floor0_decode
Vitor Sessak's avatar
Vitor Sessak committed
45 46 47 48
 */
static float eval_lpc_spectrum(const float *lsp, float cos_val, int order)
{
    int j;
49 50 51
    float p         = 0.5f;
    float q         = 0.5f;
    float two_cos_w = 2.0f * cos_val;
Vitor Sessak's avatar
Vitor Sessak committed
52

53
    for (j = 0; j + 1 < order; j += 2 * 2) {
Vitor Sessak's avatar
Vitor Sessak committed
54
        // Unroll the loop once since order is a multiple of four
55 56
        q *= lsp[j]     - two_cos_w;
        p *= lsp[j + 1] - two_cos_w;
Vitor Sessak's avatar
Vitor Sessak committed
57

58 59
        q *= lsp[j + 2] - two_cos_w;
        p *= lsp[j + 3] - two_cos_w;
Vitor Sessak's avatar
Vitor Sessak committed
60 61 62 63 64 65 66 67 68
    }

    p *= p * (2.0f - two_cos_w);
    q *= q * (2.0f + two_cos_w);

    return 0.5 / (p + q);
}

/**
69
 * Evaluate the LPC amplitude spectrum envelope from the line spectrum pairs.
Vitor Sessak's avatar
Vitor Sessak committed
70
 */
71
static void eval_lpcenv(TwinVQContext *tctx, const float *cos_vals, float *lpc)
Vitor Sessak's avatar
Vitor Sessak committed
72 73
{
    int i;
74
    const TwinVQModeTab *mtab = tctx->mtab;
75
    int size_s = mtab->size / mtab->fmode[TWINVQ_FT_SHORT].sub;
Vitor Sessak's avatar
Vitor Sessak committed
76

77
    for (i = 0; i < size_s / 2; i++) {
Vitor Sessak's avatar
Vitor Sessak committed
78
        float cos_i = tctx->cos_tabs[0][i];
79 80
        lpc[i]              = eval_lpc_spectrum(cos_vals,  cos_i, mtab->n_lsp);
        lpc[size_s - i - 1] = eval_lpc_spectrum(cos_vals, -cos_i, mtab->n_lsp);
Vitor Sessak's avatar
Vitor Sessak committed
81 82 83 84 85 86
    }
}

static void interpolate(float *out, float v1, float v2, int size)
{
    int i;
87
    float step = (v1 - v2) / (size + 1);
Vitor Sessak's avatar
Vitor Sessak committed
88

Vitor Sessak's avatar
Vitor Sessak committed
89
    for (i = 0; i < size; i++) {
90
        v2    += step;
Vitor Sessak's avatar
Vitor Sessak committed
91 92 93 94 95 96
        out[i] = v2;
    }
}

static inline float get_cos(int idx, int part, const float *cos_tab, int size)
{
97 98
    return part ? -cos_tab[size - idx - 1]
                :  cos_tab[idx];
Vitor Sessak's avatar
Vitor Sessak committed
99 100 101
}

/**
102
 * Evaluate the LPC amplitude spectrum envelope from the line spectrum pairs.
Vitor Sessak's avatar
Vitor Sessak committed
103 104 105 106 107 108 109
 * Probably for speed reasons, the coefficients are evaluated as
 * siiiibiiiisiiiibiiiisiiiibiiiisiiiibiiiis ...
 * where s is an evaluated value, i is a value interpolated from the others
 * and b might be either calculated or interpolated, depending on an
 * unexplained condition.
 *
 * @param step the size of a block "siiiibiiii"
Diego Biurrun's avatar
Diego Biurrun committed
110 111 112
 * @param in the cosine of the LSP data
 * @param part is 0 for 0...PI (positive cosine values) and 1 for PI...2PI
 *        (negative cosine values)
Vitor Sessak's avatar
Vitor Sessak committed
113 114
 * @param size the size of the whole output
 */
115 116
static inline void eval_lpcenv_or_interp(TwinVQContext *tctx,
                                         enum TwinVQFrameType ftype,
Vitor Sessak's avatar
Vitor Sessak committed
117 118 119 120
                                         float *out, const float *in,
                                         int size, int step, int part)
{
    int i;
121 122
    const TwinVQModeTab *mtab = tctx->mtab;
    const float *cos_tab      = tctx->cos_tabs[ftype];
Vitor Sessak's avatar
Vitor Sessak committed
123 124

    // Fill the 's'
Vitor Sessak's avatar
Vitor Sessak committed
125
    for (i = 0; i < size; i += step)
Vitor Sessak's avatar
Vitor Sessak committed
126 127 128 129 130 131
        out[i] =
            eval_lpc_spectrum(in,
                              get_cos(i, part, cos_tab, size),
                              mtab->n_lsp);

    // Fill the 'iiiibiiii'
132 133 134 135
    for (i = step; i <= size - 2 * step; i += step) {
        if (out[i + step] + out[i - step] > 1.95 * out[i] ||
            out[i + step]                 >= out[i - step]) {
            interpolate(out + i - step + 1, out[i], out[i - step], step - 1);
Vitor Sessak's avatar
Vitor Sessak committed
136
        } else {
137
            out[i - step / 2] =
Vitor Sessak's avatar
Vitor Sessak committed
138
                eval_lpc_spectrum(in,
139
                                  get_cos(i - step / 2, part, cos_tab, size),
Vitor Sessak's avatar
Vitor Sessak committed
140
                                  mtab->n_lsp);
141 142 143 144
            interpolate(out + i - step + 1, out[i - step / 2],
                        out[i - step], step / 2 - 1);
            interpolate(out + i - step / 2 + 1, out[i],
                        out[i - step / 2], step / 2 - 1);
Vitor Sessak's avatar
Vitor Sessak committed
145 146 147
        }
    }

148 149
    interpolate(out + size - 2 * step + 1, out[size - step],
                out[size - 2 * step], step - 1);
Vitor Sessak's avatar
Vitor Sessak committed
150 151
}

152
static void eval_lpcenv_2parts(TwinVQContext *tctx, enum TwinVQFrameType ftype,
Vitor Sessak's avatar
Vitor Sessak committed
153 154 155
                               const float *buf, float *lpc,
                               int size, int step)
{
156 157 158
    eval_lpcenv_or_interp(tctx, ftype, lpc, buf, size / 2, step, 0);
    eval_lpcenv_or_interp(tctx, ftype, lpc + size / 2, buf, size / 2,
                          2 * step, 1);
Vitor Sessak's avatar
Vitor Sessak committed
159

160 161
    interpolate(lpc + size / 2 - step + 1, lpc[size / 2],
                lpc[size / 2 - step], step);
Vitor Sessak's avatar
Vitor Sessak committed
162

163 164
    twinvq_memset_float(lpc + size - 2 * step + 1, lpc[size - 2 * step],
                        2 * step - 1);
Vitor Sessak's avatar
Vitor Sessak committed
165 166 167 168 169 170 171
}

/**
 * Inverse quantization. Read CB coefficients for cb1 and cb2 from the
 * bitstream, sum the corresponding vectors and write the result to *out
 * after permutation.
 */
172
static void dequant(TwinVQContext *tctx, const uint8_t *cb_bits, float *out,
173
                    enum TwinVQFrameType ftype,
Vitor Sessak's avatar
Vitor Sessak committed
174 175 176 177 178
                    const int16_t *cb0, const int16_t *cb1, int cb_len)
{
    int pos = 0;
    int i, j;

Vitor Sessak's avatar
Vitor Sessak committed
179
    for (i = 0; i < tctx->n_div[ftype]; i++) {
Vitor Sessak's avatar
Vitor Sessak committed
180 181 182 183 184 185 186 187
        int tmp0, tmp1;
        int sign0 = 1;
        int sign1 = 1;
        const int16_t *tab0, *tab1;
        int length = tctx->length[ftype][i >= tctx->length_change[ftype]];
        int bitstream_second_part = (i >= tctx->bits_main_spec_change[ftype]);

        int bits = tctx->bits_main_spec[0][ftype][bitstream_second_part];
188
        tmp0 = *cb_bits++;
Vitor Sessak's avatar
Vitor Sessak committed
189
        if (bits == 7) {
190
            if (tmp0 & 0x40)
Vitor Sessak's avatar
Vitor Sessak committed
191
                sign0 = -1;
192
            tmp0 &= 0x3F;
Vitor Sessak's avatar
Vitor Sessak committed
193 194 195
        }

        bits = tctx->bits_main_spec[1][ftype][bitstream_second_part];
196
        tmp1 = *cb_bits++;
Vitor Sessak's avatar
Vitor Sessak committed
197
        if (bits == 7) {
198
            if (tmp1 & 0x40)
Vitor Sessak's avatar
Vitor Sessak committed
199
                sign1 = -1;
200
            tmp1 &= 0x3F;
Vitor Sessak's avatar
Vitor Sessak committed
201 202
        }

203 204
        tab0 = cb0 + tmp0 * cb_len;
        tab1 = cb1 + tmp1 * cb_len;
Vitor Sessak's avatar
Vitor Sessak committed
205

Vitor Sessak's avatar
Vitor Sessak committed
206
        for (j = 0; j < length; j++)
207 208
            out[tctx->permut[ftype][pos + j]] = sign0 * tab0[j] +
                                                sign1 * tab1[j];
Vitor Sessak's avatar
Vitor Sessak committed
209 210 211 212 213

        pos += length;
    }
}

214
static void dec_gain(TwinVQContext *tctx,
215
                     enum TwinVQFrameType ftype, float *out)
Vitor Sessak's avatar
Vitor Sessak committed
216
{
217
    const TwinVQModeTab   *mtab =  tctx->mtab;
218
    const TwinVQFrameData *bits = &tctx->bits[tctx->cur_frame];
Vitor Sessak's avatar
Vitor Sessak committed
219
    int i, j;
220
    int sub        = mtab->fmode[ftype].sub;
221 222
    float step     = TWINVQ_AMP_MAX     / ((1 << TWINVQ_GAIN_BITS)     - 1);
    float sub_step = TWINVQ_SUB_AMP_MAX / ((1 << TWINVQ_SUB_GAIN_BITS) - 1);
Vitor Sessak's avatar
Vitor Sessak committed
223

224
    if (ftype == TWINVQ_FT_LONG) {
Vitor Sessak's avatar
Vitor Sessak committed
225
        for (i = 0; i < tctx->avctx->channels; i++)
226
            out[i] = (1.0 / (1 << 13)) *
227 228
                     twinvq_mulawinv(step * 0.5 + step * bits->gain_bits[i],
                                     TWINVQ_AMP_MAX, TWINVQ_MULAW_MU);
Vitor Sessak's avatar
Vitor Sessak committed
229
    } else {
Vitor Sessak's avatar
Vitor Sessak committed
230
        for (i = 0; i < tctx->avctx->channels; i++) {
231
            float val = (1.0 / (1 << 23)) *
232 233
                        twinvq_mulawinv(step * 0.5 + step * bits->gain_bits[i],
                                        TWINVQ_AMP_MAX, TWINVQ_MULAW_MU);
234 235 236

            for (j = 0; j < sub; j++)
                out[i * sub + j] =
237 238 239
                    val * twinvq_mulawinv(sub_step * 0.5 +
                                          sub_step * bits->sub_gain_bits[i * sub + j],
                                          TWINVQ_SUB_AMP_MAX, TWINVQ_MULAW_MU);
Vitor Sessak's avatar
Vitor Sessak committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253
        }
    }
}

/**
 * Rearrange the LSP coefficients so that they have a minimum distance of
 * min_dist. This function does it exactly as described in section of 3.2.4
 * of the G.729 specification (but interestingly is different from what the
 * reference decoder actually does).
 */
static void rearrange_lsp(int order, float *lsp, float min_dist)
{
    int i;
    float min_dist2 = min_dist * 0.5;
Vitor Sessak's avatar
Vitor Sessak committed
254
    for (i = 1; i < order; i++)
255 256
        if (lsp[i] - lsp[i - 1] < min_dist) {
            float avg = (lsp[i] + lsp[i - 1]) * 0.5;
Vitor Sessak's avatar
Vitor Sessak committed
257

258 259
            lsp[i - 1] = avg - min_dist2;
            lsp[i]     = avg + min_dist2;
Vitor Sessak's avatar
Vitor Sessak committed
260 261 262
        }
}

263
static void decode_lsp(TwinVQContext *tctx, int lpc_idx1, uint8_t *lpc_idx2,
Vitor Sessak's avatar
Vitor Sessak committed
264 265
                       int lpc_hist_idx, float *lsp, float *hist)
{
266
    const TwinVQModeTab *mtab = tctx->mtab;
Vitor Sessak's avatar
Vitor Sessak committed
267 268
    int i, j;

269 270 271
    const float *cb  = mtab->lspcodebook;
    const float *cb2 = cb  + (1 << mtab->lsp_bit1) * mtab->n_lsp;
    const float *cb3 = cb2 + (1 << mtab->lsp_bit2) * mtab->n_lsp;
Vitor Sessak's avatar
Vitor Sessak committed
272 273 274 275 276 277 278 279

    const int8_t funny_rounding[4] = {
        -2,
        mtab->lsp_split == 4 ? -2 : 1,
        mtab->lsp_split == 4 ? -2 : 1,
        0
    };

Vitor Sessak's avatar
Vitor Sessak committed
280 281
    j = 0;
    for (i = 0; i < mtab->lsp_split; i++) {
282 283
        int chunk_end = ((i + 1) * mtab->n_lsp + funny_rounding[i]) /
                        mtab->lsp_split;
Vitor Sessak's avatar
Vitor Sessak committed
284
        for (; j < chunk_end; j++)
285
            lsp[j] = cb[lpc_idx1     * mtab->n_lsp + j] +
Vitor Sessak's avatar
Vitor Sessak committed
286 287 288 289 290
                     cb2[lpc_idx2[i] * mtab->n_lsp + j];
    }

    rearrange_lsp(mtab->n_lsp, lsp, 0.0001);

Vitor Sessak's avatar
Vitor Sessak committed
291
    for (i = 0; i < mtab->n_lsp; i++) {
292
        float tmp1 = 1.0     - cb3[lpc_hist_idx * mtab->n_lsp + i];
293
        float tmp2 = hist[i] * cb3[lpc_hist_idx * mtab->n_lsp + i];
Vitor Sessak's avatar
Vitor Sessak committed
294 295 296 297 298 299
        hist[i] = lsp[i];
        lsp[i]  = lsp[i] * tmp1 + tmp2;
    }

    rearrange_lsp(mtab->n_lsp, lsp, 0.0001);
    rearrange_lsp(mtab->n_lsp, lsp, 0.000095);
300
    ff_sort_nearly_sorted_floats(lsp, mtab->n_lsp);
Vitor Sessak's avatar
Vitor Sessak committed
301 302
}

303 304
static void dec_lpc_spectrum_inv(TwinVQContext *tctx, float *lsp,
                                 enum TwinVQFrameType ftype, float *lpc)
Vitor Sessak's avatar
Vitor Sessak committed
305 306 307 308
{
    int i;
    int size = tctx->mtab->size / tctx->mtab->fmode[ftype].sub;

Vitor Sessak's avatar
Vitor Sessak committed
309
    for (i = 0; i < tctx->mtab->n_lsp; i++)
310
        lsp[i] = 2 * cos(lsp[i]);
Vitor Sessak's avatar
Vitor Sessak committed
311 312

    switch (ftype) {
313
    case TWINVQ_FT_LONG:
Vitor Sessak's avatar
Vitor Sessak committed
314 315
        eval_lpcenv_2parts(tctx, ftype, lsp, lpc, size, 8);
        break;
316
    case TWINVQ_FT_MEDIUM:
Vitor Sessak's avatar
Vitor Sessak committed
317 318
        eval_lpcenv_2parts(tctx, ftype, lsp, lpc, size, 2);
        break;
319
    case TWINVQ_FT_SHORT:
Vitor Sessak's avatar
Vitor Sessak committed
320 321 322 323 324
        eval_lpcenv(tctx, lsp, lpc);
        break;
    }
}

325 326
static const uint8_t wtype_to_wsize[] = { 0, 0, 2, 2, 2, 1, 0, 1, 1 };

327 328
static void imdct_and_window(TwinVQContext *tctx, enum TwinVQFrameType ftype,
                             int wtype, float *in, float *prev, int ch)
Vitor Sessak's avatar
Vitor Sessak committed
329
{
330 331 332 333 334
    FFTContext *mdct = &tctx->mdct_ctx[ftype];
    const TwinVQModeTab *mtab = tctx->mtab;
    int bsize = mtab->size / mtab->fmode[ftype].sub;
    int size  = mtab->size;
    float *buf1 = tctx->tmp_buf;
335 336
    int j, first_wsize, wsize; // Window size
    float *out  = tctx->curr_frame + 2 * ch * mtab->size;
Vitor Sessak's avatar
Vitor Sessak committed
337 338 339
    float *out2 = out;
    float *prev_buf;
    int types_sizes[] = {
340 341 342
        mtab->size /  mtab->fmode[TWINVQ_FT_LONG].sub,
        mtab->size /  mtab->fmode[TWINVQ_FT_MEDIUM].sub,
        mtab->size / (mtab->fmode[TWINVQ_FT_SHORT].sub * 2),
Vitor Sessak's avatar
Vitor Sessak committed
343 344
    };

345
    wsize       = types_sizes[wtype_to_wsize[wtype]];
Vitor Sessak's avatar
Vitor Sessak committed
346
    first_wsize = wsize;
347
    prev_buf    = prev + (size - bsize) / 2;
Vitor Sessak's avatar
Vitor Sessak committed
348

Vitor Sessak's avatar
Vitor Sessak committed
349
    for (j = 0; j < mtab->fmode[ftype].sub; j++) {
350
        int sub_wtype = ftype == TWINVQ_FT_MEDIUM ? 8 : wtype;
Vitor Sessak's avatar
Vitor Sessak committed
351 352 353

        if (!j && wtype == 4)
            sub_wtype = 4;
354
        else if (j == mtab->fmode[ftype].sub - 1 && wtype == 7)
Vitor Sessak's avatar
Vitor Sessak committed
355 356 357 358
            sub_wtype = 7;

        wsize = types_sizes[wtype_to_wsize[sub_wtype]];

359
        mdct->imdct_half(mdct, buf1 + bsize * j, in + bsize * j);
Vitor Sessak's avatar
Vitor Sessak committed
360

361
        tctx->fdsp.vector_fmul_window(out2, prev_buf + (bsize - wsize) / 2,
362 363 364
                                      buf1 + bsize * j,
                                      ff_sine_windows[av_log2(wsize)],
                                      wsize / 2);
Vitor Sessak's avatar
Vitor Sessak committed
365 366
        out2 += wsize;

367 368
        memcpy(out2, buf1 + bsize * j + wsize / 2,
               (bsize - wsize / 2) * sizeof(float));
Vitor Sessak's avatar
Vitor Sessak committed
369

370
        out2 += ftype == TWINVQ_FT_MEDIUM ? (bsize - wsize) / 2 : bsize - wsize;
Vitor Sessak's avatar
Vitor Sessak committed
371

372
        prev_buf = buf1 + bsize * j + bsize / 2;
Vitor Sessak's avatar
Vitor Sessak committed
373 374
    }

375
    tctx->last_block_pos[ch] = (size + first_wsize) / 2;
Vitor Sessak's avatar
Vitor Sessak committed
376 377
}

378
static void imdct_output(TwinVQContext *tctx, enum TwinVQFrameType ftype,
379
                         int wtype, float **out, int offset)
Vitor Sessak's avatar
Vitor Sessak committed
380
{
381 382
    const TwinVQModeTab *mtab = tctx->mtab;
    float *prev_buf           = tctx->prev_frame + tctx->last_block_pos[0];
383
    int size1, size2, i;
384
    float *out1, *out2;
Vitor Sessak's avatar
Vitor Sessak committed
385

386
    for (i = 0; i < tctx->avctx->channels; i++)
Vitor Sessak's avatar
Vitor Sessak committed
387
        imdct_and_window(tctx, ftype, wtype,
388 389
                         tctx->spectrum + i * mtab->size,
                         prev_buf + 2 * i * mtab->size,
Vitor Sessak's avatar
Vitor Sessak committed
390 391
                         i);

392 393 394
    if (!out)
        return;

395 396
    size2 = tctx->last_block_pos[0];
    size1 = mtab->size - size2;
Vitor Sessak's avatar
Vitor Sessak committed
397

398 399 400
    out1 = &out[0][0] + offset;
    memcpy(out1,         prev_buf,         size1 * sizeof(*out1));
    memcpy(out1 + size1, tctx->curr_frame, size2 * sizeof(*out1));
Vitor Sessak's avatar
Vitor Sessak committed
401

402
    if (tctx->avctx->channels == 2) {
403 404 405 406 407 408
        out2 = &out[1][0] + offset;
        memcpy(out2, &prev_buf[2 * mtab->size],
               size1 * sizeof(*out2));
        memcpy(out2 + size1, &tctx->curr_frame[2 * mtab->size],
               size2 * sizeof(*out2));
        tctx->fdsp.butterflies_float(out1, out2, mtab->size);
Vitor Sessak's avatar
Vitor Sessak committed
409 410 411
    }
}

412 413
static void read_and_decode_spectrum(TwinVQContext *tctx, float *out,
                                     enum TwinVQFrameType ftype)
Vitor Sessak's avatar
Vitor Sessak committed
414
{
415
    const TwinVQModeTab *mtab = tctx->mtab;
416
    TwinVQFrameData *bits     = &tctx->bits[tctx->cur_frame];
417 418 419
    int channels              = tctx->avctx->channels;
    int sub        = mtab->fmode[ftype].sub;
    int block_size = mtab->size / sub;
420 421
    float gain[TWINVQ_CHANNELS_MAX * TWINVQ_SUBBLOCKS_MAX];
    float ppc_shape[TWINVQ_PPC_SHAPE_LEN_MAX * TWINVQ_CHANNELS_MAX * 4];
Vitor Sessak's avatar
Vitor Sessak committed
422

423
    int i, j;
Vitor Sessak's avatar
Vitor Sessak committed
424

425
    dequant(tctx, bits->main_coeffs, out, ftype,
Vitor Sessak's avatar
Vitor Sessak committed
426 427 428
            mtab->fmode[ftype].cb0, mtab->fmode[ftype].cb1,
            mtab->fmode[ftype].cb_len_read);

429
    dec_gain(tctx, ftype, gain);
Vitor Sessak's avatar
Vitor Sessak committed
430

431
    if (ftype == TWINVQ_FT_LONG) {
432 433
        int cb_len_p = (tctx->n_div[3] + mtab->ppc_shape_len * channels - 1) /
                       tctx->n_div[3];
434 435 436 437
        dequant(tctx, bits->ppc_coeffs, ppc_shape,
                TWINVQ_FT_PPC, mtab->ppc_shape_cb,
                mtab->ppc_shape_cb + cb_len_p * TWINVQ_PPC_SHAPE_CB_SIZE,
                cb_len_p);
Vitor Sessak's avatar
Vitor Sessak committed
438 439
    }

Vitor Sessak's avatar
Vitor Sessak committed
440
    for (i = 0; i < channels; i++) {
Vitor Sessak's avatar
Vitor Sessak committed
441
        float *chunk = out + mtab->size * i;
442
        float lsp[TWINVQ_LSP_COEFS_MAX];
Vitor Sessak's avatar
Vitor Sessak committed
443

Vitor Sessak's avatar
Vitor Sessak committed
444
        for (j = 0; j < sub; j++) {
445 446 447
            tctx->dec_bark_env(tctx, bits->bark1[i][j],
                               bits->bark_use_hist[i][j], i,
                               tctx->tmp_buf, gain[sub * i + j], ftype);
Vitor Sessak's avatar
Vitor Sessak committed
448

449 450
            tctx->fdsp.vector_fmul(chunk + block_size * j,
                                   chunk + block_size * j,
451
                                   tctx->tmp_buf, block_size);
Vitor Sessak's avatar
Vitor Sessak committed
452 453
        }

454 455 456
        if (ftype == TWINVQ_FT_LONG)
            tctx->decode_ppc(tctx, bits->p_coef[i], bits->g_coef[i],
                             ppc_shape + i * mtab->ppc_shape_len, chunk);
Vitor Sessak's avatar
Vitor Sessak committed
457

458 459
        decode_lsp(tctx, bits->lpc_idx1[i], bits->lpc_idx2[i],
                   bits->lpc_hist_idx[i], lsp, tctx->lsp_hist[i]);
Vitor Sessak's avatar
Vitor Sessak committed
460 461 462

        dec_lpc_spectrum_inv(tctx, lsp, ftype, tctx->tmp_buf);

Vitor Sessak's avatar
Vitor Sessak committed
463
        for (j = 0; j < mtab->fmode[ftype].sub; j++) {
464
            tctx->fdsp.vector_fmul(chunk, chunk, tctx->tmp_buf, block_size);
Vitor Sessak's avatar
Vitor Sessak committed
465 466 467 468 469
            chunk += block_size;
        }
    }
}

470
const enum TwinVQFrameType ff_twinvq_wtype_to_ftype_table[] = {
471 472 473
    TWINVQ_FT_LONG,   TWINVQ_FT_LONG, TWINVQ_FT_SHORT, TWINVQ_FT_LONG,
    TWINVQ_FT_MEDIUM, TWINVQ_FT_LONG, TWINVQ_FT_LONG,  TWINVQ_FT_MEDIUM,
    TWINVQ_FT_MEDIUM
474 475
};

476 477
int ff_twinvq_decode_frame(AVCodecContext *avctx, void *data,
                           int *got_frame_ptr, AVPacket *avpkt)
Vitor Sessak's avatar
Vitor Sessak committed
478
{
479
    AVFrame *frame     = data;
Vitor Sessak's avatar
Vitor Sessak committed
480
    const uint8_t *buf = avpkt->data;
481
    int buf_size       = avpkt->size;
482 483 484
    TwinVQContext *tctx = avctx->priv_data;
    const TwinVQModeTab *mtab = tctx->mtab;
    float **out = NULL;
485
    int ret;
Vitor Sessak's avatar
Vitor Sessak committed
486

487 488
    /* get output buffer */
    if (tctx->discarded_packets >= 2) {
489
        frame->nb_samples = mtab->size * tctx->frames_per_packet;
490
        if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
491 492 493
            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
            return ret;
        }
494
        out = (float **)frame->extended_data;
495 496
    }

497 498 499 500 501 502
    if (buf_size < avctx->block_align) {
        av_log(avctx, AV_LOG_ERROR,
               "Frame too small (%d bytes). Truncated file?\n", buf_size);
        return AVERROR(EINVAL);
    }

503
    if ((ret = tctx->read_bitstream(avctx, tctx, buf, buf_size)) < 0)
504
        return ret;
Vitor Sessak's avatar
Vitor Sessak committed
505

506 507 508 509
    for (tctx->cur_frame = 0; tctx->cur_frame < tctx->frames_per_packet;
         tctx->cur_frame++) {
        read_and_decode_spectrum(tctx, tctx->spectrum,
                                 tctx->bits[tctx->cur_frame].ftype);
Vitor Sessak's avatar
Vitor Sessak committed
510

511 512 513
        imdct_output(tctx, tctx->bits[tctx->cur_frame].ftype,
                     tctx->bits[tctx->cur_frame].window_type, out,
                     tctx->cur_frame * mtab->size);
Vitor Sessak's avatar
Vitor Sessak committed
514

515 516
        FFSWAP(float *, tctx->curr_frame, tctx->prev_frame);
    }
Vitor Sessak's avatar
Vitor Sessak committed
517

518 519 520
    if (tctx->discarded_packets < 2) {
        tctx->discarded_packets++;
        *got_frame_ptr = 0;
Vitor Sessak's avatar
Vitor Sessak committed
521 522 523
        return buf_size;
    }

524
    *got_frame_ptr = 1;
Vitor Sessak's avatar
Vitor Sessak committed
525

526 527 528
    // VQF can deliver packets 1 byte greater than block align
    if (buf_size == avctx->block_align + 1)
        return buf_size;
529
    return avctx->block_align;
Vitor Sessak's avatar
Vitor Sessak committed
530 531 532 533 534
}

/**
 * Init IMDCT and windowing tables
 */
535
static av_cold int init_mdct_win(TwinVQContext *tctx)
Vitor Sessak's avatar
Vitor Sessak committed
536
{
537
    int i, j, ret;
538
    const TwinVQModeTab *mtab = tctx->mtab;
539 540
    int size_s = mtab->size / mtab->fmode[TWINVQ_FT_SHORT].sub;
    int size_m = mtab->size / mtab->fmode[TWINVQ_FT_MEDIUM].sub;
541 542
    int channels = tctx->avctx->channels;
    float norm = channels == 1 ? 2.0 : 1.0;
Vitor Sessak's avatar
Vitor Sessak committed
543

Vitor Sessak's avatar
Vitor Sessak committed
544
    for (i = 0; i < 3; i++) {
545
        int bsize = tctx->mtab->size / tctx->mtab->fmode[i].sub;
546
        if ((ret = ff_mdct_init(&tctx->mdct_ctx[i], av_log2(bsize) + 1, 1,
547
                                -sqrt(norm / bsize) / (1 << 15))))
548
            return ret;
Vitor Sessak's avatar
Vitor Sessak committed
549 550
    }

551 552
    FF_ALLOC_OR_GOTO(tctx->avctx, tctx->tmp_buf,
                     mtab->size * sizeof(*tctx->tmp_buf), alloc_fail);
Vitor Sessak's avatar
Vitor Sessak committed
553

554 555 556 557 558 559 560 561 562
    FF_ALLOC_OR_GOTO(tctx->avctx, tctx->spectrum,
                     2 * mtab->size * channels * sizeof(*tctx->spectrum),
                     alloc_fail);
    FF_ALLOC_OR_GOTO(tctx->avctx, tctx->curr_frame,
                     2 * mtab->size * channels * sizeof(*tctx->curr_frame),
                     alloc_fail);
    FF_ALLOC_OR_GOTO(tctx->avctx, tctx->prev_frame,
                     2 * mtab->size * channels * sizeof(*tctx->prev_frame),
                     alloc_fail);
Vitor Sessak's avatar
Vitor Sessak committed
563

Vitor Sessak's avatar
Vitor Sessak committed
564
    for (i = 0; i < 3; i++) {
565 566
        int m       = 4 * mtab->size / mtab->fmode[i].sub;
        double freq = 2 * M_PI / m;
567 568
        FF_ALLOC_OR_GOTO(tctx->avctx, tctx->cos_tabs[i],
                         (m / 4) * sizeof(*tctx->cos_tabs[i]), alloc_fail);
Vitor Sessak's avatar
Vitor Sessak committed
569

570 571 572 573
        for (j = 0; j <= m / 8; j++)
            tctx->cos_tabs[i][j] = cos((2 * j + 1) * freq);
        for (j = 1; j < m / 8; j++)
            tctx->cos_tabs[i][m / 4 - j] = tctx->cos_tabs[i][j];
Vitor Sessak's avatar
Vitor Sessak committed
574 575
    }

576
    ff_init_ff_sine_windows(av_log2(size_m));
577
    ff_init_ff_sine_windows(av_log2(size_s / 2));
578
    ff_init_ff_sine_windows(av_log2(mtab->size));
579 580

    return 0;
581

582 583
alloc_fail:
    return AVERROR(ENOMEM);
Vitor Sessak's avatar
Vitor Sessak committed
584 585 586 587 588 589 590 591 592 593 594
}

/**
 * Interpret the data as if it were a num_blocks x line_len[0] matrix and for
 * each line do a cyclic permutation, i.e.
 * abcdefghijklm -> defghijklmabc
 * where the amount to be shifted is evaluated depending on the column.
 */
static void permutate_in_line(int16_t *tab, int num_vect, int num_blocks,
                              int block_size,
                              const uint8_t line_len[2], int length_div,
595
                              enum TwinVQFrameType ftype)
Vitor Sessak's avatar
Vitor Sessak committed
596
{
597
    int i, j;
Vitor Sessak's avatar
Vitor Sessak committed
598

Vitor Sessak's avatar
Vitor Sessak committed
599
    for (i = 0; i < line_len[0]; i++) {
Vitor Sessak's avatar
Vitor Sessak committed
600 601
        int shift;

602 603 604
        if (num_blocks == 1                                    ||
            (ftype == TWINVQ_FT_LONG && num_vect % num_blocks) ||
            (ftype != TWINVQ_FT_LONG && num_vect & 1)          ||
Vitor Sessak's avatar
Vitor Sessak committed
605 606
            i == line_len[1]) {
            shift = 0;
607
        } else if (ftype == TWINVQ_FT_LONG) {
Vitor Sessak's avatar
Vitor Sessak committed
608 609
            shift = i;
        } else
610
            shift = i * i;
Vitor Sessak's avatar
Vitor Sessak committed
611

612 613
        for (j = 0; j < num_vect && (j + num_vect * i < block_size * num_blocks); j++)
            tab[i * num_vect + j] = i * num_vect + (j + shift) % num_vect;
Vitor Sessak's avatar
Vitor Sessak committed
614 615 616 617 618 619
    }
}

/**
 * Interpret the input data as in the following table:
 *
620
 * @verbatim
Vitor Sessak's avatar
Vitor Sessak committed
621 622 623 624 625 626
 *
 * abcdefgh
 * ijklmnop
 * qrstuvw
 * x123456
 *
627
 * @endverbatim
Vitor Sessak's avatar
Vitor Sessak committed
628 629 630 631 632 633 634
 *
 * and transpose it, giving the output
 * aiqxbjr1cks2dlt3emu4fvn5gow6hp
 */
static void transpose_perm(int16_t *out, int16_t *in, int num_vect,
                           const uint8_t line_len[2], int length_div)
{
635 636 637
    int i, j;
    int cont = 0;

Vitor Sessak's avatar
Vitor Sessak committed
638 639
    for (i = 0; i < num_vect; i++)
        for (j = 0; j < line_len[i >= length_div]; j++)
640
            out[cont++] = in[j * num_vect + i];
Vitor Sessak's avatar
Vitor Sessak committed
641 642 643 644
}

static void linear_perm(int16_t *out, int16_t *in, int n_blocks, int size)
{
645
    int block_size = size / n_blocks;
Vitor Sessak's avatar
Vitor Sessak committed
646 647
    int i;

Vitor Sessak's avatar
Vitor Sessak committed
648
    for (i = 0; i < size; i++)
Vitor Sessak's avatar
Vitor Sessak committed
649 650 651
        out[i] = block_size * (in[i] % n_blocks) + in[i] / n_blocks;
}

652 653
static av_cold void construct_perm_table(TwinVQContext *tctx,
                                         enum TwinVQFrameType ftype)
Vitor Sessak's avatar
Vitor Sessak committed
654
{
655
    int block_size, size;
656
    const TwinVQModeTab *mtab = tctx->mtab;
657
    int16_t *tmp_perm = (int16_t *)tctx->tmp_buf;
Vitor Sessak's avatar
Vitor Sessak committed
658

659
    if (ftype == TWINVQ_FT_PPC) {
660
        size       = tctx->avctx->channels;
Vitor Sessak's avatar
Vitor Sessak committed
661
        block_size = mtab->ppc_shape_len;
662 663
    } else {
        size       = tctx->avctx->channels * mtab->fmode[ftype].sub;
Vitor Sessak's avatar
Vitor Sessak committed
664
        block_size = mtab->size / mtab->fmode[ftype].sub;
665
    }
Vitor Sessak's avatar
Vitor Sessak committed
666 667 668 669 670 671 672 673 674

    permutate_in_line(tmp_perm, tctx->n_div[ftype], size,
                      block_size, tctx->length[ftype],
                      tctx->length_change[ftype], ftype);

    transpose_perm(tctx->permut[ftype], tmp_perm, tctx->n_div[ftype],
                   tctx->length[ftype], tctx->length_change[ftype]);

    linear_perm(tctx->permut[ftype], tctx->permut[ftype], size,
675
                size * block_size);
Vitor Sessak's avatar
Vitor Sessak committed
676 677
}

678
static av_cold void init_bitstream_params(TwinVQContext *tctx)
Vitor Sessak's avatar
Vitor Sessak committed
679
{
680 681 682 683
    const TwinVQModeTab *mtab = tctx->mtab;
    int n_ch                  = tctx->avctx->channels;
    int total_fr_bits         = tctx->avctx->bit_rate * mtab->size /
                                tctx->avctx->sample_rate;
Vitor Sessak's avatar
Vitor Sessak committed
684

685 686
    int lsp_bits_per_block = n_ch * (mtab->lsp_bit0 + mtab->lsp_bit1 +
                                     mtab->lsp_split * mtab->lsp_bit2);
Vitor Sessak's avatar
Vitor Sessak committed
687

688 689
    int ppc_bits = n_ch * (mtab->pgain_bit + mtab->ppc_shape_bit +
                           mtab->ppc_period_bit);
Vitor Sessak's avatar
Vitor Sessak committed
690

691
    int bsize_no_main_cb[3], bse_bits[3], i;
692
    enum TwinVQFrameType frametype;
Vitor Sessak's avatar
Vitor Sessak committed
693

Vitor Sessak's avatar
Vitor Sessak committed
694
    for (i = 0; i < 3; i++)
Vitor Sessak's avatar
Vitor Sessak committed
695 696
        // +1 for history usage switch
        bse_bits[i] = n_ch *
697 698
                      (mtab->fmode[i].bark_n_coef *
                       mtab->fmode[i].bark_n_bit + 1);
Vitor Sessak's avatar
Vitor Sessak committed
699 700

    bsize_no_main_cb[2] = bse_bits[2] + lsp_bits_per_block + ppc_bits +
701
                          TWINVQ_WINDOW_TYPE_BITS + n_ch * TWINVQ_GAIN_BITS;
Vitor Sessak's avatar
Vitor Sessak committed
702

Vitor Sessak's avatar
Vitor Sessak committed
703
    for (i = 0; i < 2; i++)
Vitor Sessak's avatar
Vitor Sessak committed
704
        bsize_no_main_cb[i] =
705 706 707
            lsp_bits_per_block + n_ch * TWINVQ_GAIN_BITS +
            TWINVQ_WINDOW_TYPE_BITS +
            mtab->fmode[i].sub * (bse_bits[i] + n_ch * TWINVQ_SUB_GAIN_BITS);
Vitor Sessak's avatar
Vitor Sessak committed
708

709
    if (tctx->codec == TWINVQ_CODEC_METASOUND && !tctx->is_6kbps) {
710 711 712 713
        bsize_no_main_cb[1] += 2;
        bsize_no_main_cb[2] += 2;
    }

Vitor Sessak's avatar
Vitor Sessak committed
714
    // The remaining bits are all used for the main spectrum coefficients
Vitor Sessak's avatar
Vitor Sessak committed
715
    for (i = 0; i < 4; i++) {
716
        int bit_size, vect_size;
Vitor Sessak's avatar
Vitor Sessak committed
717 718 719 720 721
        int rounded_up, rounded_down, num_rounded_down, num_rounded_up;
        if (i == 3) {
            bit_size  = n_ch * mtab->ppc_shape_bit;
            vect_size = n_ch * mtab->ppc_shape_len;
        } else {
722
            bit_size  = total_fr_bits - bsize_no_main_cb[i];
Vitor Sessak's avatar
Vitor Sessak committed
723 724 725 726 727
            vect_size = n_ch * mtab->size;
        }

        tctx->n_div[i] = (bit_size + 13) / 14;

728 729 730 731 732 733 734 735 736
        rounded_up                     = (bit_size + tctx->n_div[i] - 1) /
                                         tctx->n_div[i];
        rounded_down                   = (bit_size) / tctx->n_div[i];
        num_rounded_down               = rounded_up * tctx->n_div[i] - bit_size;
        num_rounded_up                 = tctx->n_div[i] - num_rounded_down;
        tctx->bits_main_spec[0][i][0]  = (rounded_up + 1)   / 2;
        tctx->bits_main_spec[1][i][0]  =  rounded_up        / 2;
        tctx->bits_main_spec[0][i][1]  = (rounded_down + 1) / 2;
        tctx->bits_main_spec[1][i][1]  =  rounded_down      / 2;
Vitor Sessak's avatar
Vitor Sessak committed
737 738
        tctx->bits_main_spec_change[i] = num_rounded_up;

739 740 741 742 743 744 745
        rounded_up             = (vect_size + tctx->n_div[i] - 1) /
                                 tctx->n_div[i];
        rounded_down           = (vect_size) / tctx->n_div[i];
        num_rounded_down       = rounded_up * tctx->n_div[i] - vect_size;
        num_rounded_up         = tctx->n_div[i] - num_rounded_down;
        tctx->length[i][0]     = rounded_up;
        tctx->length[i][1]     = rounded_down;
Vitor Sessak's avatar
Vitor Sessak committed
746 747 748
        tctx->length_change[i] = num_rounded_up;
    }

749
    for (frametype = TWINVQ_FT_SHORT; frametype <= TWINVQ_FT_PPC; frametype++)
750
        construct_perm_table(tctx, frametype);
Vitor Sessak's avatar
Vitor Sessak committed
751 752
}

753
av_cold int ff_twinvq_decode_close(AVCodecContext *avctx)
754
{
755
    TwinVQContext *tctx = avctx->priv_data;
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
    int i;

    for (i = 0; i < 3; i++) {
        ff_mdct_end(&tctx->mdct_ctx[i]);
        av_free(tctx->cos_tabs[i]);
    }

    av_free(tctx->curr_frame);
    av_free(tctx->spectrum);
    av_free(tctx->prev_frame);
    av_free(tctx->tmp_buf);

    return 0;
}

771
av_cold int ff_twinvq_decode_init(AVCodecContext *avctx)
Vitor Sessak's avatar
Vitor Sessak committed
772
{
773
    int ret;
774
    TwinVQContext *tctx = avctx->priv_data;
Vitor Sessak's avatar
Vitor Sessak committed
775 776

    tctx->avctx       = avctx;
777
    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
Vitor Sessak's avatar
Vitor Sessak committed
778

779 780 781 782 783 784 785 786 787 788 789 790 791 792
    if (!avctx->block_align) {
        avctx->block_align = tctx->frame_size + 7 >> 3;
    } else if (avctx->block_align * 8 < tctx->frame_size) {
        av_log(avctx, AV_LOG_ERROR, "Block align is %d bits, expected %d\n",
               avctx->block_align * 8, tctx->frame_size);
        return AVERROR_INVALIDDATA;
    }
    tctx->frames_per_packet = avctx->block_align * 8 / tctx->frame_size;
    if (tctx->frames_per_packet > TWINVQ_MAX_FRAMES_PER_PACKET) {
        av_log(avctx, AV_LOG_ERROR, "Too many frames per packet (%d)\n",
               tctx->frames_per_packet);
        return AVERROR_INVALIDDATA;
    }

793
    avpriv_float_dsp_init(&tctx->fdsp, avctx->flags & AV_CODEC_FLAG_BITEXACT);
794 795
    if ((ret = init_mdct_win(tctx))) {
        av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");
796
        ff_twinvq_decode_close(avctx);
797 798
        return ret;
    }
Vitor Sessak's avatar
Vitor Sessak committed
799 800
    init_bitstream_params(tctx);

801 802
    twinvq_memset_float(tctx->bark_hist[0][0], 0.1,
                        FF_ARRAY_ELEMS(tctx->bark_hist));
Vitor Sessak's avatar
Vitor Sessak committed
803 804 805

    return 0;
}