imc.c 31.2 KB
Newer Older
Kostya Shishkov's avatar
Kostya Shishkov committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
 * IMC compatible decoder
 * Copyright (c) 2002-2004 Maxim Poliakovski
 * Copyright (c) 2006 Benjamin Larsson
 * Copyright (c) 2006 Konstantin Shishkov
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * 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.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * 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
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/**
25 26
 *  @file
 *  IMC - Intel Music Coder
Kostya Shishkov's avatar
Kostya Shishkov committed
27
 *  A mdct based codec using a 256 points large transform
Kostya Shishkov's avatar
Kostya Shishkov committed
28
 *  divided into 32 bands with some mix of scale factors.
Kostya Shishkov's avatar
Kostya Shishkov committed
29 30 31 32 33 34 35 36 37
 *  Only mono is supported.
 *
 */


#include <math.h>
#include <stddef.h>
#include <stdio.h>

38
#include "libavutil/channel_layout.h"
39
#include "libavutil/libm.h"
Kostya Shishkov's avatar
Kostya Shishkov committed
40
#include "avcodec.h"
41
#include "get_bits.h"
Kostya Shishkov's avatar
Kostya Shishkov committed
42
#include "dsputil.h"
43
#include "fft.h"
44
#include "sinewin.h"
Kostya Shishkov's avatar
Kostya Shishkov committed
45 46 47

#include "imcdata.h"

48
#define IMC_BLOCK_SIZE 64
Kostya Shishkov's avatar
Kostya Shishkov committed
49 50 51 52
#define IMC_FRAME_ID 0x21
#define BANDS 32
#define COEFFS 256

53
typedef struct IMCChannel {
Kostya Shishkov's avatar
Kostya Shishkov committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    float old_floor[BANDS];
    float flcoeffs1[BANDS];
    float flcoeffs2[BANDS];
    float flcoeffs3[BANDS];
    float flcoeffs4[BANDS];
    float flcoeffs5[BANDS];
    float flcoeffs6[BANDS];
    float CWdecoded[COEFFS];

    int bandWidthT[BANDS];     ///< codewords per band
    int bitsBandT[BANDS];      ///< how many bits per codeword in band
    int CWlengthT[COEFFS];     ///< how many bits in each codeword
    int levlCoeffBuf[BANDS];
    int bandFlagsBuf[BANDS];   ///< flags for each band
    int sumLenArr[BANDS];      ///< bits for all coeffs in band
    int skipFlagRaw[BANDS];    ///< skip flags are stored in raw form or not
    int skipFlagBits[BANDS];   ///< bits used to code skip flags
    int skipFlagCount[BANDS];  ///< skipped coeffients per band
    int skipFlags[COEFFS];     ///< skip coefficient decoding or not
    int codewords[COEFFS];     ///< raw codewords read from bitstream
74 75 76 77 78 79 80 81 82

    float last_fft_im[COEFFS];

    int decoder_reset;
} IMCChannel;

typedef struct {
    AVFrame frame;

Kostya Shishkov's avatar
Kostya Shishkov committed
83
    IMCChannel chctx[2];
84 85 86 87 88 89 90 91 92 93

    /** MDCT tables */
    //@{
    float mdct_sine_window[COEFFS];
    float post_cos[COEFFS];
    float post_sin[COEFFS];
    float pre_coef1[COEFFS];
    float pre_coef2[COEFFS];
    //@}

Kostya Shishkov's avatar
Kostya Shishkov committed
94 95 96 97 98
    float sqrt_tab[30];
    GetBitContext gb;

    DSPContext dsp;
    FFTContext fft;
Kostya Shishkov's avatar
Kostya Shishkov committed
99
    DECLARE_ALIGNED(32, FFTComplex, samples)[COEFFS / 2];
100
    float *out_samples;
Kostya Shishkov's avatar
Kostya Shishkov committed
101 102 103

    int8_t cyclTab[32], cyclTab2[32];
    float  weights1[31], weights2[31];
Kostya Shishkov's avatar
Kostya Shishkov committed
104 105
} IMCContext;

106 107 108 109 110 111
static VLC huffman_vlc[4][4];

#define VLC_TABLES_SIZE 9512

static const int vlc_offsets[17] = {
    0,     640, 1156, 1732, 2308, 2852, 3396, 3924,
Kostya Shishkov's avatar
Kostya Shishkov committed
112 113
    4452, 5220, 5860, 6628, 7268, 7908, 8424, 8936, VLC_TABLES_SIZE
};
114 115

static VLC_TYPE vlc_tables[VLC_TABLES_SIZE][2];
Kostya Shishkov's avatar
Kostya Shishkov committed
116

117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
static inline double freq2bark(double freq)
{
    return 3.5 * atan((freq / 7500.0) * (freq / 7500.0)) + 13.0 * atan(freq * 0.00076);
}

static av_cold void iac_generate_tabs(IMCContext *q, int sampling_rate)
{
    double freqmin[32], freqmid[32], freqmax[32];
    double scale = sampling_rate / (256.0 * 2.0 * 2.0);
    double nyquist_freq = sampling_rate * 0.5;
    double freq, bark, prev_bark = 0, tf, tb;
    int i, j;

    for (i = 0; i < 32; i++) {
        freq = (band_tab[i] + band_tab[i + 1] - 1) * scale;
        bark = freq2bark(freq);

        if (i > 0) {
            tb = bark - prev_bark;
            q->weights1[i - 1] = pow(10.0, -1.0 * tb);
            q->weights2[i - 1] = pow(10.0, -2.7 * tb);
        }
        prev_bark = bark;

        freqmid[i] = freq;

        tf = freq;
        while (tf < nyquist_freq) {
            tf += 0.5;
            tb =  freq2bark(tf);
            if (tb > bark + 0.5)
                break;
        }
        freqmax[i] = tf;

        tf = freq;
        while (tf > 0.0) {
            tf -= 0.5;
            tb =  freq2bark(tf);
            if (tb <= bark - 0.5)
                break;
        }
        freqmin[i] = tf;
    }

    for (i = 0; i < 32; i++) {
        freq = freqmax[i];
        for (j = 31; j > 0 && freq <= freqmid[j]; j--);
        q->cyclTab[i] = j + 1;

        freq = freqmin[i];
        for (j = 0; j < 32 && freq >= freqmid[j]; j++);
        q->cyclTab2[i] = j - 1;
    }
}

Kostya Shishkov's avatar
Kostya Shishkov committed
173
static av_cold int imc_decode_init(AVCodecContext *avctx)
Kostya Shishkov's avatar
Kostya Shishkov committed
174
{
175
    int i, j, ret;
Kostya Shishkov's avatar
Kostya Shishkov committed
176 177 178
    IMCContext *q = avctx->priv_data;
    double r1, r2;

179 180 181 182
    if (avctx->codec_id == AV_CODEC_ID_IMC)
        avctx->channels = 1;

    if (avctx->channels > 2) {
183 184 185 186
        av_log_ask_for_sample(avctx, "Number of channels is not supported\n");
        return AVERROR_PATCHWELCOME;
    }

187 188
    for (j = 0; j < avctx->channels; j++) {
        q->chctx[j].decoder_reset = 1;
Kostya Shishkov's avatar
Kostya Shishkov committed
189

190 191 192 193 194 195
        for (i = 0; i < BANDS; i++)
            q->chctx[j].old_floor[i] = 1.0;

        for (i = 0; i < COEFFS / 2; i++)
            q->chctx[j].last_fft_im[i] = 0;
    }
Kostya Shishkov's avatar
Kostya Shishkov committed
196 197

    /* Build mdct window, a simple sine window normalized with sqrt(2) */
198
    ff_sine_window_init(q->mdct_sine_window, COEFFS);
Kostya Shishkov's avatar
Kostya Shishkov committed
199
    for (i = 0; i < COEFFS; i++)
200
        q->mdct_sine_window[i] *= sqrt(2.0);
Kostya Shishkov's avatar
Kostya Shishkov committed
201
    for (i = 0; i < COEFFS / 2; i++) {
202 203
        q->post_cos[i] = (1.0f / 32768) * cos(i / 256.0 * M_PI);
        q->post_sin[i] = (1.0f / 32768) * sin(i / 256.0 * M_PI);
Kostya Shishkov's avatar
Kostya Shishkov committed
204 205 206 207

        r1 = sin((i * 4.0 + 1.0) / 1024.0 * M_PI);
        r2 = cos((i * 4.0 + 1.0) / 1024.0 * M_PI);

Kostya Shishkov's avatar
Kostya Shishkov committed
208
        if (i & 0x1) {
Kostya Shishkov's avatar
Kostya Shishkov committed
209 210
            q->pre_coef1[i] =  (r1 + r2) * sqrt(2.0);
            q->pre_coef2[i] = -(r1 - r2) * sqrt(2.0);
Kostya Shishkov's avatar
Kostya Shishkov committed
211
        } else {
Kostya Shishkov's avatar
Kostya Shishkov committed
212 213 214 215 216 217 218
            q->pre_coef1[i] = -(r1 + r2) * sqrt(2.0);
            q->pre_coef2[i] =  (r1 - r2) * sqrt(2.0);
        }
    }

    /* Generate a square root table */

Kostya Shishkov's avatar
Kostya Shishkov committed
219
    for (i = 0; i < 30; i++)
Kostya Shishkov's avatar
Kostya Shishkov committed
220 221 222
        q->sqrt_tab[i] = sqrt(i);

    /* initialize the VLC tables */
Kostya Shishkov's avatar
Kostya Shishkov committed
223 224
    for (i = 0; i < 4 ; i++) {
        for (j = 0; j < 4; j++) {
225
            huffman_vlc[i][j].table = &vlc_tables[vlc_offsets[i * 4 + j]];
226 227
            huffman_vlc[i][j].table_allocated = vlc_offsets[i * 4 + j + 1] - vlc_offsets[i * 4 + j];
            init_vlc(&huffman_vlc[i][j], 9, imc_huffman_sizes[i],
Kostya Shishkov's avatar
Kostya Shishkov committed
228
                     imc_huffman_lens[i][j], 1, 1,
229
                     imc_huffman_bits[i][j], 2, 2, INIT_VLC_USE_NEW_STATIC);
Kostya Shishkov's avatar
Kostya Shishkov committed
230 231
        }
    }
232

233
    if (avctx->codec_id == AV_CODEC_ID_IAC) {
234
        iac_generate_tabs(q, avctx->sample_rate);
Kostya Shishkov's avatar
Kostya Shishkov committed
235
    } else {
236 237
        memcpy(q->cyclTab,  cyclTab,  sizeof(cyclTab));
        memcpy(q->cyclTab2, cyclTab2, sizeof(cyclTab2));
Kostya Shishkov's avatar
Kostya Shishkov committed
238 239 240 241
        memcpy(q->weights1, imc_weights1, sizeof(imc_weights1));
        memcpy(q->weights2, imc_weights2, sizeof(imc_weights2));
    }

242 243 244 245
    if ((ret = ff_fft_init(&q->fft, 7, 1))) {
        av_log(avctx, AV_LOG_INFO, "FFT init failed\n");
        return ret;
    }
246
    ff_dsputil_init(&q->dsp, avctx);
247
    avctx->sample_fmt     = AV_SAMPLE_FMT_FLTP;
248 249
    avctx->channel_layout = avctx->channels == 1 ? AV_CH_LAYOUT_MONO
                                                 : AV_CH_LAYOUT_STEREO;
250 251 252 253

    avcodec_get_frame_defaults(&q->frame);
    avctx->coded_frame = &q->frame;

Kostya Shishkov's avatar
Kostya Shishkov committed
254 255 256
    return 0;
}

Kostya Shishkov's avatar
Kostya Shishkov committed
257 258 259
static void imc_calculate_coeffs(IMCContext *q, float *flcoeffs1,
                                 float *flcoeffs2, int *bandWidthT,
                                 float *flcoeffs3, float *flcoeffs5)
Kostya Shishkov's avatar
Kostya Shishkov committed
260 261 262 263 264 265 266 267
{
    float   workT1[BANDS];
    float   workT2[BANDS];
    float   workT3[BANDS];
    float   snr_limit = 1.e-30;
    float   accum = 0.0;
    int i, cnt2;

Kostya Shishkov's avatar
Kostya Shishkov committed
268
    for (i = 0; i < BANDS; i++) {
Kostya Shishkov's avatar
Kostya Shishkov committed
269
        flcoeffs5[i] = workT2[i] = 0.0;
Kostya Shishkov's avatar
Kostya Shishkov committed
270
        if (bandWidthT[i]) {
Kostya Shishkov's avatar
Kostya Shishkov committed
271 272 273
            workT1[i] = flcoeffs1[i] * flcoeffs1[i];
            flcoeffs3[i] = 2.0 * flcoeffs2[i];
        } else {
Kostya Shishkov's avatar
Kostya Shishkov committed
274
            workT1[i]    = 0.0;
Kostya Shishkov's avatar
Kostya Shishkov committed
275 276 277 278 279 280 281
            flcoeffs3[i] = -30000.0;
        }
        workT3[i] = bandWidthT[i] * workT1[i] * 0.01;
        if (workT3[i] <= snr_limit)
            workT3[i] = 0.0;
    }

Kostya Shishkov's avatar
Kostya Shishkov committed
282
    for (i = 0; i < BANDS; i++) {
Kostya Shishkov's avatar
Kostya Shishkov committed
283
        for (cnt2 = i; cnt2 < q->cyclTab[i]; cnt2++)
Kostya Shishkov's avatar
Kostya Shishkov committed
284
            flcoeffs5[cnt2] = flcoeffs5[cnt2] + workT3[i];
Kostya Shishkov's avatar
Kostya Shishkov committed
285
        workT2[cnt2 - 1] = workT2[cnt2 - 1] + workT3[i];
Kostya Shishkov's avatar
Kostya Shishkov committed
286 287
    }

Kostya Shishkov's avatar
Kostya Shishkov committed
288
    for (i = 1; i < BANDS; i++) {
Kostya Shishkov's avatar
Kostya Shishkov committed
289
        accum = (workT2[i - 1] + accum) * q->weights1[i - 1];
Kostya Shishkov's avatar
Kostya Shishkov committed
290 291 292
        flcoeffs5[i] += accum;
    }

Kostya Shishkov's avatar
Kostya Shishkov committed
293
    for (i = 0; i < BANDS; i++)
Kostya Shishkov's avatar
Kostya Shishkov committed
294 295
        workT2[i] = 0.0;

Kostya Shishkov's avatar
Kostya Shishkov committed
296
    for (i = 0; i < BANDS; i++) {
Kostya Shishkov's avatar
Kostya Shishkov committed
297
        for (cnt2 = i - 1; cnt2 > q->cyclTab2[i]; cnt2--)
Kostya Shishkov's avatar
Kostya Shishkov committed
298 299 300 301 302 303
            flcoeffs5[cnt2] += workT3[i];
        workT2[cnt2+1] += workT3[i];
    }

    accum = 0.0;

Kostya Shishkov's avatar
Kostya Shishkov committed
304
    for (i = BANDS-2; i >= 0; i--) {
Kostya Shishkov's avatar
Kostya Shishkov committed
305
        accum = (workT2[i+1] + accum) * q->weights2[i];
Kostya Shishkov's avatar
Kostya Shishkov committed
306
        flcoeffs5[i] += accum;
Kostya Shishkov's avatar
Kostya Shishkov committed
307
        // there is missing code here, but it seems to never be triggered
Kostya Shishkov's avatar
Kostya Shishkov committed
308 309 310 311
    }
}


Kostya Shishkov's avatar
Kostya Shishkov committed
312 313
static void imc_read_level_coeffs(IMCContext *q, int stream_format_code,
                                  int *levlCoeffs)
Kostya Shishkov's avatar
Kostya Shishkov committed
314 315 316 317 318 319 320 321
{
    int i;
    VLC *hufftab[4];
    int start = 0;
    const uint8_t *cb_sel;
    int s;

    s = stream_format_code >> 1;
322 323 324 325
    hufftab[0] = &huffman_vlc[s][0];
    hufftab[1] = &huffman_vlc[s][1];
    hufftab[2] = &huffman_vlc[s][2];
    hufftab[3] = &huffman_vlc[s][3];
Kostya Shishkov's avatar
Kostya Shishkov committed
326 327
    cb_sel = imc_cb_select[s];

Kostya Shishkov's avatar
Kostya Shishkov committed
328
    if (stream_format_code & 4)
Kostya Shishkov's avatar
Kostya Shishkov committed
329
        start = 1;
Kostya Shishkov's avatar
Kostya Shishkov committed
330
    if (start)
Kostya Shishkov's avatar
Kostya Shishkov committed
331
        levlCoeffs[0] = get_bits(&q->gb, 7);
Kostya Shishkov's avatar
Kostya Shishkov committed
332 333 334 335
    for (i = start; i < BANDS; i++) {
        levlCoeffs[i] = get_vlc2(&q->gb, hufftab[cb_sel[i]]->table,
                                 hufftab[cb_sel[i]]->bits, 2);
        if (levlCoeffs[i] == 17)
Kostya Shishkov's avatar
Kostya Shishkov committed
336 337 338 339
            levlCoeffs[i] += get_bits(&q->gb, 4);
    }
}

Kostya Shishkov's avatar
Kostya Shishkov committed
340 341
static void imc_decode_level_coefficients(IMCContext *q, int *levlCoeffBuf,
                                          float *flcoeffs1, float *flcoeffs2)
Kostya Shishkov's avatar
Kostya Shishkov committed
342 343 344
{
    int i, level;
    float tmp, tmp2;
Kostya Shishkov's avatar
Kostya Shishkov committed
345
    // maybe some frequency division thingy
Kostya Shishkov's avatar
Kostya Shishkov committed
346

347
    flcoeffs1[0] = 20000.0 / exp2 (levlCoeffBuf[0] * 0.18945); // 0.18945 = log2(10) * 0.05703125
348
    flcoeffs2[0] = log2f(flcoeffs1[0]);
Kostya Shishkov's avatar
Kostya Shishkov committed
349
    tmp  = flcoeffs1[0];
Kostya Shishkov's avatar
Kostya Shishkov committed
350 351
    tmp2 = flcoeffs2[0];

Kostya Shishkov's avatar
Kostya Shishkov committed
352
    for (i = 1; i < BANDS; i++) {
Kostya Shishkov's avatar
Kostya Shishkov committed
353 354 355 356 357 358
        level = levlCoeffBuf[i];
        if (level == 16) {
            flcoeffs1[i] = 1.0;
            flcoeffs2[i] = 0.0;
        } else {
            if (level < 17)
Kostya Shishkov's avatar
Kostya Shishkov committed
359
                level -= 7;
Kostya Shishkov's avatar
Kostya Shishkov committed
360
            else if (level <= 24)
Kostya Shishkov's avatar
Kostya Shishkov committed
361
                level -= 32;
Kostya Shishkov's avatar
Kostya Shishkov committed
362
            else
Kostya Shishkov's avatar
Kostya Shishkov committed
363
                level -= 16;
Kostya Shishkov's avatar
Kostya Shishkov committed
364 365

            tmp  *= imc_exp_tab[15 + level];
Benjamin Larsson's avatar
Benjamin Larsson committed
366
            tmp2 += 0.83048 * level;  // 0.83048 = log2(10) * 0.25
Kostya Shishkov's avatar
Kostya Shishkov committed
367 368 369 370 371 372 373
            flcoeffs1[i] = tmp;
            flcoeffs2[i] = tmp2;
        }
    }
}


Kostya Shishkov's avatar
Kostya Shishkov committed
374 375 376 377
static void imc_decode_level_coefficients2(IMCContext *q, int *levlCoeffBuf,
                                           float *old_floor, float *flcoeffs1,
                                           float *flcoeffs2)
{
Kostya Shishkov's avatar
Kostya Shishkov committed
378
    int i;
Kostya Shishkov's avatar
Kostya Shishkov committed
379 380 381 382 383
    /* FIXME maybe flag_buf = noise coding and flcoeffs1 = new scale factors
     *       and flcoeffs2 old scale factors
     *       might be incomplete due to a missing table that is in the binary code
     */
    for (i = 0; i < BANDS; i++) {
Kostya Shishkov's avatar
Kostya Shishkov committed
384
        flcoeffs1[i] = 0;
Kostya Shishkov's avatar
Kostya Shishkov committed
385
        if (levlCoeffBuf[i] < 16) {
Kostya Shishkov's avatar
Kostya Shishkov committed
386
            flcoeffs1[i] = imc_exp_tab2[levlCoeffBuf[i]] * old_floor[i];
Kostya Shishkov's avatar
Kostya Shishkov committed
387
            flcoeffs2[i] = (levlCoeffBuf[i] - 7) * 0.83048 + flcoeffs2[i]; // 0.83048 = log2(10) * 0.25
Kostya Shishkov's avatar
Kostya Shishkov committed
388 389 390 391 392 393 394 395 396
        } else {
            flcoeffs1[i] = old_floor[i];
        }
    }
}

/**
 * Perform bit allocation depending on bits available
 */
397 398
static int bit_allocation(IMCContext *q, IMCChannel *chctx,
                          int stream_format_code, int freebits, int flag)
Kostya Shishkov's avatar
Kostya Shishkov committed
399
{
Kostya Shishkov's avatar
Kostya Shishkov committed
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
    int i, j;
    const float limit = -1.e20;
    float highest = 0.0;
    int indx;
    int t1 = 0;
    int t2 = 1;
    float summa = 0.0;
    int iacc = 0;
    int summer = 0;
    int rres, cwlen;
    float lowest = 1.e10;
    int low_indx = 0;
    float workT[32];
    int flg;
    int found_indx = 0;

Kostya Shishkov's avatar
Kostya Shishkov committed
416
    for (i = 0; i < BANDS; i++)
417
        highest = FFMAX(highest, chctx->flcoeffs1[i]);
Kostya Shishkov's avatar
Kostya Shishkov committed
418

Kostya Shishkov's avatar
Kostya Shishkov committed
419
    for (i = 0; i < BANDS - 1; i++)
420
        chctx->flcoeffs4[i] = chctx->flcoeffs3[i] - log2f(chctx->flcoeffs5[i]);
421
    chctx->flcoeffs4[BANDS - 1] = limit;
Kostya Shishkov's avatar
Kostya Shishkov committed
422 423 424

    highest = highest * 0.25;

Kostya Shishkov's avatar
Kostya Shishkov committed
425
    for (i = 0; i < BANDS; i++) {
Kostya Shishkov's avatar
Kostya Shishkov committed
426
        indx = -1;
427
        if ((band_tab[i + 1] - band_tab[i]) == chctx->bandWidthT[i])
Kostya Shishkov's avatar
Kostya Shishkov committed
428 429
            indx = 0;

430
        if ((band_tab[i + 1] - band_tab[i]) > chctx->bandWidthT[i])
Kostya Shishkov's avatar
Kostya Shishkov committed
431 432
            indx = 1;

433
        if (((band_tab[i + 1] - band_tab[i]) / 2) >= chctx->bandWidthT[i])
Kostya Shishkov's avatar
Kostya Shishkov committed
434 435 436
            indx = 2;

        if (indx == -1)
437
            return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
438

439
        chctx->flcoeffs4[i] += xTab[(indx * 2 + (chctx->flcoeffs1[i] < highest)) * 2 + flag];
Kostya Shishkov's avatar
Kostya Shishkov committed
440 441 442
    }

    if (stream_format_code & 0x2) {
443 444 445 446
        chctx->flcoeffs4[0] = limit;
        chctx->flcoeffs4[1] = limit;
        chctx->flcoeffs4[2] = limit;
        chctx->flcoeffs4[3] = limit;
Kostya Shishkov's avatar
Kostya Shishkov committed
447 448
    }

Kostya Shishkov's avatar
Kostya Shishkov committed
449
    for (i = (stream_format_code & 0x2) ? 4 : 0; i < BANDS - 1; i++) {
450 451
        iacc  += chctx->bandWidthT[i];
        summa += chctx->bandWidthT[i] * chctx->flcoeffs4[i];
Kostya Shishkov's avatar
Kostya Shishkov committed
452
    }
453
    chctx->bandWidthT[BANDS - 1] = 0;
Kostya Shishkov's avatar
Kostya Shishkov committed
454 455 456
    summa = (summa * 0.5 - freebits) / iacc;


Kostya Shishkov's avatar
Kostya Shishkov committed
457
    for (i = 0; i < BANDS / 2; i++) {
Kostya Shishkov's avatar
Kostya Shishkov committed
458
        rres = summer - freebits;
Kostya Shishkov's avatar
Kostya Shishkov committed
459 460
        if ((rres >= -8) && (rres <= 8))
            break;
Kostya Shishkov's avatar
Kostya Shishkov committed
461 462

        summer = 0;
Kostya Shishkov's avatar
Kostya Shishkov committed
463
        iacc   = 0;
Kostya Shishkov's avatar
Kostya Shishkov committed
464

Kostya Shishkov's avatar
Kostya Shishkov committed
465
        for (j = (stream_format_code & 0x2) ? 4 : 0; j < BANDS; j++) {
466
            cwlen = av_clipf(((chctx->flcoeffs4[j] * 0.5) - summa + 0.5), 0, 6);
Kostya Shishkov's avatar
Kostya Shishkov committed
467

468 469
            chctx->bitsBandT[j] = cwlen;
            summer += chctx->bandWidthT[j] * cwlen;
Kostya Shishkov's avatar
Kostya Shishkov committed
470 471

            if (cwlen > 0)
472
                iacc += chctx->bandWidthT[j];
Kostya Shishkov's avatar
Kostya Shishkov committed
473 474 475 476 477 478 479 480
        }

        flg = t2;
        t2 = 1;
        if (freebits < summer)
            t2 = -1;
        if (i == 0)
            flg = t2;
Kostya Shishkov's avatar
Kostya Shishkov committed
481
        if (flg != t2)
Kostya Shishkov's avatar
Kostya Shishkov committed
482 483 484 485 486
            t1++;

        summa = (float)(summer - freebits) / ((t1 + 1) * iacc) + summa;
    }

Kostya Shishkov's avatar
Kostya Shishkov committed
487 488
    for (i = (stream_format_code & 0x2) ? 4 : 0; i < BANDS; i++) {
        for (j = band_tab[i]; j < band_tab[i + 1]; j++)
489
            chctx->CWlengthT[j] = chctx->bitsBandT[i];
Kostya Shishkov's avatar
Kostya Shishkov committed
490 491 492
    }

    if (freebits > summer) {
Kostya Shishkov's avatar
Kostya Shishkov committed
493
        for (i = 0; i < BANDS; i++) {
494 495
            workT[i] = (chctx->bitsBandT[i] == 6) ? -1.e20
                                              : (chctx->bitsBandT[i] * -2 + chctx->flcoeffs4[i] - 0.415);
Kostya Shishkov's avatar
Kostya Shishkov committed
496 497 498 499
        }

        highest = 0.0;

Kostya Shishkov's avatar
Kostya Shishkov committed
500
        do {
Kostya Shishkov's avatar
Kostya Shishkov committed
501 502 503 504 505 506
            if (highest <= -1.e20)
                break;

            found_indx = 0;
            highest = -1.e20;

Kostya Shishkov's avatar
Kostya Shishkov committed
507
            for (i = 0; i < BANDS; i++) {
Kostya Shishkov's avatar
Kostya Shishkov committed
508 509 510 511 512 513 514 515
                if (workT[i] > highest) {
                    highest = workT[i];
                    found_indx = i;
                }
            }

            if (highest > -1.e20) {
                workT[found_indx] -= 2.0;
516
                if (++chctx->bitsBandT[found_indx] == 6)
Kostya Shishkov's avatar
Kostya Shishkov committed
517 518
                    workT[found_indx] = -1.e20;

Kostya Shishkov's avatar
Kostya Shishkov committed
519
                for (j = band_tab[found_indx]; j < band_tab[found_indx + 1] && (freebits > summer); j++) {
520
                    chctx->CWlengthT[j]++;
Kostya Shishkov's avatar
Kostya Shishkov committed
521 522 523
                    summer++;
                }
            }
Kostya Shishkov's avatar
Kostya Shishkov committed
524
        } while (freebits > summer);
Kostya Shishkov's avatar
Kostya Shishkov committed
525 526
    }
    if (freebits < summer) {
Kostya Shishkov's avatar
Kostya Shishkov committed
527
        for (i = 0; i < BANDS; i++) {
528
            workT[i] = chctx->bitsBandT[i] ? (chctx->bitsBandT[i] * -2 + chctx->flcoeffs4[i] + 1.585)
Kostya Shishkov's avatar
Kostya Shishkov committed
529
                                       : 1.e20;
Kostya Shishkov's avatar
Kostya Shishkov committed
530 531 532 533 534 535 536
        }
        if (stream_format_code & 0x2) {
            workT[0] = 1.e20;
            workT[1] = 1.e20;
            workT[2] = 1.e20;
            workT[3] = 1.e20;
        }
Kostya Shishkov's avatar
Kostya Shishkov committed
537 538
        while (freebits < summer) {
            lowest   = 1.e10;
Kostya Shishkov's avatar
Kostya Shishkov committed
539
            low_indx = 0;
Kostya Shishkov's avatar
Kostya Shishkov committed
540
            for (i = 0; i < BANDS; i++) {
Kostya Shishkov's avatar
Kostya Shishkov committed
541
                if (workT[i] < lowest) {
Kostya Shishkov's avatar
Kostya Shishkov committed
542
                    lowest   = workT[i];
Kostya Shishkov's avatar
Kostya Shishkov committed
543 544 545
                    low_indx = i;
                }
            }
Kostya Shishkov's avatar
Kostya Shishkov committed
546 547
            // if (lowest >= 1.e10)
            //     break;
Kostya Shishkov's avatar
Kostya Shishkov committed
548 549
            workT[low_indx] = lowest + 2.0;

550
            if (!--chctx->bitsBandT[low_indx])
Kostya Shishkov's avatar
Kostya Shishkov committed
551 552
                workT[low_indx] = 1.e20;

Kostya Shishkov's avatar
Kostya Shishkov committed
553
            for (j = band_tab[low_indx]; j < band_tab[low_indx+1] && (freebits < summer); j++) {
554 555
                if (chctx->CWlengthT[j] > 0) {
                    chctx->CWlengthT[j]--;
Kostya Shishkov's avatar
Kostya Shishkov committed
556 557 558 559 560 561 562 563
                    summer--;
                }
            }
        }
    }
    return 0;
}

564
static void imc_get_skip_coeff(IMCContext *q, IMCChannel *chctx)
Kostya Shishkov's avatar
Kostya Shishkov committed
565
{
Kostya Shishkov's avatar
Kostya Shishkov committed
566 567
    int i, j;

568 569
    memset(chctx->skipFlagBits,  0, sizeof(chctx->skipFlagBits));
    memset(chctx->skipFlagCount, 0, sizeof(chctx->skipFlagCount));
Kostya Shishkov's avatar
Kostya Shishkov committed
570
    for (i = 0; i < BANDS; i++) {
571
        if (!chctx->bandFlagsBuf[i] || !chctx->bandWidthT[i])
Kostya Shishkov's avatar
Kostya Shishkov committed
572 573
            continue;

574 575
        if (!chctx->skipFlagRaw[i]) {
            chctx->skipFlagBits[i] = band_tab[i + 1] - band_tab[i];
Kostya Shishkov's avatar
Kostya Shishkov committed
576

Kostya Shishkov's avatar
Kostya Shishkov committed
577
            for (j = band_tab[i]; j < band_tab[i + 1]; j++) {
578 579 580
                chctx->skipFlags[j] = get_bits1(&q->gb);
                if (chctx->skipFlags[j])
                    chctx->skipFlagCount[i]++;
Kostya Shishkov's avatar
Kostya Shishkov committed
581 582
            }
        } else {
Kostya Shishkov's avatar
Kostya Shishkov committed
583 584
            for (j = band_tab[i]; j < band_tab[i + 1] - 1; j += 2) {
                if (!get_bits1(&q->gb)) { // 0
585 586 587 588
                    chctx->skipFlagBits[i]++;
                    chctx->skipFlags[j]      = 1;
                    chctx->skipFlags[j + 1]  = 1;
                    chctx->skipFlagCount[i] += 2;
Kostya Shishkov's avatar
Kostya Shishkov committed
589 590
                } else {
                    if (get_bits1(&q->gb)) { // 11
591 592 593 594
                        chctx->skipFlagBits[i] += 2;
                        chctx->skipFlags[j]     = 0;
                        chctx->skipFlags[j + 1] = 1;
                        chctx->skipFlagCount[i]++;
Kostya Shishkov's avatar
Kostya Shishkov committed
595
                    } else {
596 597
                        chctx->skipFlagBits[i] += 3;
                        chctx->skipFlags[j + 1] = 0;
Kostya Shishkov's avatar
Kostya Shishkov committed
598
                        if (!get_bits1(&q->gb)) { // 100
599 600
                            chctx->skipFlags[j] = 1;
                            chctx->skipFlagCount[i]++;
Kostya Shishkov's avatar
Kostya Shishkov committed
601
                        } else { // 101
602
                            chctx->skipFlags[j] = 0;
Kostya Shishkov's avatar
Kostya Shishkov committed
603 604 605 606 607
                        }
                    }
                }
            }

Kostya Shishkov's avatar
Kostya Shishkov committed
608
            if (j < band_tab[i + 1]) {
609 610 611
                chctx->skipFlagBits[i]++;
                if ((chctx->skipFlags[j] = get_bits1(&q->gb)))
                    chctx->skipFlagCount[i]++;
Kostya Shishkov's avatar
Kostya Shishkov committed
612 613 614 615 616 617 618 619
            }
        }
    }
}

/**
 * Increase highest' band coefficient sizes as some bits won't be used
 */
620 621
static void imc_adjust_bit_allocation(IMCContext *q, IMCChannel *chctx,
                                      int summer)
Kostya Shishkov's avatar
Kostya Shishkov committed
622
{
Kostya Shishkov's avatar
Kostya Shishkov committed
623 624 625
    float workT[32];
    int corrected = 0;
    int i, j;
Kostya Shishkov's avatar
Kostya Shishkov committed
626 627
    float highest  = 0;
    int found_indx = 0;
Kostya Shishkov's avatar
Kostya Shishkov committed
628

Kostya Shishkov's avatar
Kostya Shishkov committed
629
    for (i = 0; i < BANDS; i++) {
630 631
        workT[i] = (chctx->bitsBandT[i] == 6) ? -1.e20
                                          : (chctx->bitsBandT[i] * -2 + chctx->flcoeffs4[i] - 0.415);
Kostya Shishkov's avatar
Kostya Shishkov committed
632 633 634
    }

    while (corrected < summer) {
Kostya Shishkov's avatar
Kostya Shishkov committed
635
        if (highest <= -1.e20)
Kostya Shishkov's avatar
Kostya Shishkov committed
636 637 638 639
            break;

        highest = -1.e20;

Kostya Shishkov's avatar
Kostya Shishkov committed
640
        for (i = 0; i < BANDS; i++) {
Kostya Shishkov's avatar
Kostya Shishkov committed
641 642 643 644 645 646 647 648
            if (workT[i] > highest) {
                highest = workT[i];
                found_indx = i;
            }
        }

        if (highest > -1.e20) {
            workT[found_indx] -= 2.0;
649
            if (++(chctx->bitsBandT[found_indx]) == 6)
Kostya Shishkov's avatar
Kostya Shishkov committed
650 651
                workT[found_indx] = -1.e20;

Kostya Shishkov's avatar
Kostya Shishkov committed
652
            for (j = band_tab[found_indx]; j < band_tab[found_indx+1] && (corrected < summer); j++) {
653 654
                if (!chctx->skipFlags[j] && (chctx->CWlengthT[j] < 6)) {
                    chctx->CWlengthT[j]++;
Kostya Shishkov's avatar
Kostya Shishkov committed
655 656 657 658 659 660 661
                    corrected++;
                }
            }
        }
    }
}

662
static void imc_imdct256(IMCContext *q, IMCChannel *chctx, int channels)
Kostya Shishkov's avatar
Kostya Shishkov committed
663
{
Kostya Shishkov's avatar
Kostya Shishkov committed
664 665
    int i;
    float re, im;
666
    float *dst1 = q->out_samples;
667
    float *dst2 = q->out_samples + (COEFFS - 1);
Kostya Shishkov's avatar
Kostya Shishkov committed
668 669

    /* prerotation */
Kostya Shishkov's avatar
Kostya Shishkov committed
670
    for (i = 0; i < COEFFS / 2; i++) {
671 672 673 674
        q->samples[i].re = -(q->pre_coef1[i] * chctx->CWdecoded[COEFFS - 1 - i * 2]) -
                            (q->pre_coef2[i] * chctx->CWdecoded[i * 2]);
        q->samples[i].im =  (q->pre_coef2[i] * chctx->CWdecoded[COEFFS - 1 - i * 2]) -
                            (q->pre_coef1[i] * chctx->CWdecoded[i * 2]);
Kostya Shishkov's avatar
Kostya Shishkov committed
675 676 677
    }

    /* FFT */
678
    q->fft.fft_permute(&q->fft, q->samples);
Kostya Shishkov's avatar
Kostya Shishkov committed
679
    q->fft.fft_calc(&q->fft, q->samples);
Kostya Shishkov's avatar
Kostya Shishkov committed
680 681

    /* postrotation, window and reorder */
Kostya Shishkov's avatar
Kostya Shishkov committed
682 683 684
    for (i = 0; i < COEFFS / 2; i++) {
        re = ( q->samples[i].re * q->post_cos[i]) + (-q->samples[i].im * q->post_sin[i]);
        im = (-q->samples[i].im * q->post_cos[i]) - ( q->samples[i].re * q->post_sin[i]);
685 686 687 688
        *dst1 =  (q->mdct_sine_window[COEFFS - 1 - i * 2] * chctx->last_fft_im[i])
               + (q->mdct_sine_window[i * 2] * re);
        *dst2 =  (q->mdct_sine_window[i * 2] * chctx->last_fft_im[i])
               - (q->mdct_sine_window[COEFFS - 1 - i * 2] * re);
689 690
        dst1 += 2;
        dst2 -= 2;
691
        chctx->last_fft_im[i] = im;
Kostya Shishkov's avatar
Kostya Shishkov committed
692 693 694
    }
}

695 696
static int inverse_quant_coeff(IMCContext *q, IMCChannel *chctx,
                               int stream_format_code)
Kostya Shishkov's avatar
Kostya Shishkov committed
697
{
Kostya Shishkov's avatar
Kostya Shishkov committed
698 699
    int i, j;
    int middle_value, cw_len, max_size;
Kostya Shishkov's avatar
Kostya Shishkov committed
700
    const float *quantizer;
Kostya Shishkov's avatar
Kostya Shishkov committed
701

Kostya Shishkov's avatar
Kostya Shishkov committed
702 703
    for (i = 0; i < BANDS; i++) {
        for (j = band_tab[i]; j < band_tab[i + 1]; j++) {
704 705
            chctx->CWdecoded[j] = 0;
            cw_len = chctx->CWlengthT[j];
Kostya Shishkov's avatar
Kostya Shishkov committed
706

707
            if (cw_len <= 0 || chctx->skipFlags[j])
Kostya Shishkov's avatar
Kostya Shishkov committed
708 709
                continue;

Kostya Shishkov's avatar
Kostya Shishkov committed
710
            max_size     = 1 << cw_len;
Kostya Shishkov's avatar
Kostya Shishkov committed
711 712
            middle_value = max_size >> 1;

713
            if (chctx->codewords[j] >= max_size || chctx->codewords[j] < 0)
714
                return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
715

Kostya Shishkov's avatar
Kostya Shishkov committed
716
            if (cw_len >= 4) {
Kostya Shishkov's avatar
Kostya Shishkov committed
717
                quantizer = imc_quantizer2[(stream_format_code & 2) >> 1];
718 719
                if (chctx->codewords[j] >= middle_value)
                    chctx->CWdecoded[j] =  quantizer[chctx->codewords[j] - 8]                * chctx->flcoeffs6[i];
Kostya Shishkov's avatar
Kostya Shishkov committed
720
                else
721
                    chctx->CWdecoded[j] = -quantizer[max_size - chctx->codewords[j] - 8 - 1] * chctx->flcoeffs6[i];
Kostya Shishkov's avatar
Kostya Shishkov committed
722
            }else{
723 724 725
                quantizer = imc_quantizer1[((stream_format_code & 2) >> 1) | (chctx->bandFlagsBuf[i] << 1)];
                if (chctx->codewords[j] >= middle_value)
                    chctx->CWdecoded[j] =  quantizer[chctx->codewords[j] - 1]            * chctx->flcoeffs6[i];
Kostya Shishkov's avatar
Kostya Shishkov committed
726
                else
727
                    chctx->CWdecoded[j] = -quantizer[max_size - 2 - chctx->codewords[j]] * chctx->flcoeffs6[i];
Kostya Shishkov's avatar
Kostya Shishkov committed
728 729 730 731 732 733 734
            }
        }
    }
    return 0;
}


735
static int imc_get_coeffs(IMCContext *q, IMCChannel *chctx)
Kostya Shishkov's avatar
Kostya Shishkov committed
736
{
Kostya Shishkov's avatar
Kostya Shishkov committed
737 738
    int i, j, cw_len, cw;

Kostya Shishkov's avatar
Kostya Shishkov committed
739
    for (i = 0; i < BANDS; i++) {
740
        if (!chctx->sumLenArr[i])
Kostya Shishkov's avatar
Kostya Shishkov committed
741
            continue;
742
        if (chctx->bandFlagsBuf[i] || chctx->bandWidthT[i]) {
Kostya Shishkov's avatar
Kostya Shishkov committed
743
            for (j = band_tab[i]; j < band_tab[i + 1]; j++) {
744
                cw_len = chctx->CWlengthT[j];
Kostya Shishkov's avatar
Kostya Shishkov committed
745 746
                cw = 0;

Kostya Shishkov's avatar
Kostya Shishkov committed
747
                if (get_bits_count(&q->gb) + cw_len > 512) {
748
                    av_dlog(NULL, "Band %i coeff %i cw_len %i\n", i, j, cw_len);
749
                    return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
750 751
                }

752
                if (cw_len && (!chctx->bandFlagsBuf[i] || !chctx->skipFlags[j]))
Kostya Shishkov's avatar
Kostya Shishkov committed
753 754
                    cw = get_bits(&q->gb, cw_len);

755
                chctx->codewords[j] = cw;
Kostya Shishkov's avatar
Kostya Shishkov committed
756 757 758 759 760 761
            }
        }
    }
    return 0;
}

762
static int imc_decode_block(AVCodecContext *avctx, IMCContext *q, int ch)
Kostya Shishkov's avatar
Kostya Shishkov committed
763 764
{
    int stream_format_code;
765
    int imc_hdr, i, j, ret;
Kostya Shishkov's avatar
Kostya Shishkov committed
766 767 768
    int flag;
    int bits, summer;
    int counter, bitscount;
769
    IMCChannel *chctx = q->chctx + ch;
Kostya Shishkov's avatar
Kostya Shishkov committed
770 771 772 773


    /* Check the frame header */
    imc_hdr = get_bits(&q->gb, 9);
Kostya Shishkov's avatar
Kostya Shishkov committed
774 775 776
    if (imc_hdr & 0x18) {
        av_log(avctx, AV_LOG_ERROR, "frame header check failed!\n");
        av_log(avctx, AV_LOG_ERROR, "got %X.\n", imc_hdr);
777
        return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
778 779 780
    }
    stream_format_code = get_bits(&q->gb, 3);

Kostya Shishkov's avatar
Kostya Shishkov committed
781
    if (stream_format_code & 1) {
Kostya Shishkov's avatar
Kostya Shishkov committed
782 783 784
        av_log_ask_for_sample(avctx, "Stream format %X is not supported\n",
                              stream_format_code);
        return AVERROR_PATCHWELCOME;
Kostya Shishkov's avatar
Kostya Shishkov committed
785 786 787
    }

    if (stream_format_code & 0x04)
788
        chctx->decoder_reset = 1;
Kostya Shishkov's avatar
Kostya Shishkov committed
789

790
    if (chctx->decoder_reset) {
Kostya Shishkov's avatar
Kostya Shishkov committed
791
        for (i = 0; i < BANDS; i++)
792
            chctx->old_floor[i] = 1.0;
Kostya Shishkov's avatar
Kostya Shishkov committed
793
        for (i = 0; i < COEFFS; i++)
794 795
            chctx->CWdecoded[i] = 0;
        chctx->decoder_reset = 0;
Kostya Shishkov's avatar
Kostya Shishkov committed
796 797 798
    }

    flag = get_bits1(&q->gb);
799
    imc_read_level_coeffs(q, stream_format_code, chctx->levlCoeffBuf);
Kostya Shishkov's avatar
Kostya Shishkov committed
800 801

    if (stream_format_code & 0x4)
802 803
        imc_decode_level_coefficients(q, chctx->levlCoeffBuf,
                                      chctx->flcoeffs1, chctx->flcoeffs2);
Kostya Shishkov's avatar
Kostya Shishkov committed
804
    else
805 806
        imc_decode_level_coefficients2(q, chctx->levlCoeffBuf, chctx->old_floor,
                                       chctx->flcoeffs1, chctx->flcoeffs2);
Kostya Shishkov's avatar
Kostya Shishkov committed
807

808 809 810 811 812 813 814
    for(i=0; i<BANDS; i++) {
        if(chctx->flcoeffs1[i] > INT_MAX) {
            av_log(avctx, AV_LOG_ERROR, "scalefactor out of range\n");
            return AVERROR_INVALIDDATA;
        }
    }

815
    memcpy(chctx->old_floor, chctx->flcoeffs1, 32 * sizeof(float));
Kostya Shishkov's avatar
Kostya Shishkov committed
816 817

    counter = 0;
Kostya Shishkov's avatar
Kostya Shishkov committed
818
    for (i = 0; i < BANDS; i++) {
819 820
        if (chctx->levlCoeffBuf[i] == 16) {
            chctx->bandWidthT[i] = 0;
Kostya Shishkov's avatar
Kostya Shishkov committed
821 822
            counter++;
        } else
823
            chctx->bandWidthT[i] = band_tab[i + 1] - band_tab[i];
Kostya Shishkov's avatar
Kostya Shishkov committed
824
    }
825
    memset(chctx->bandFlagsBuf, 0, BANDS * sizeof(int));
Kostya Shishkov's avatar
Kostya Shishkov committed
826
    for (i = 0; i < BANDS - 1; i++) {
827 828
        if (chctx->bandWidthT[i])
            chctx->bandFlagsBuf[i] = get_bits1(&q->gb);
Kostya Shishkov's avatar
Kostya Shishkov committed
829 830
    }

831
    imc_calculate_coeffs(q, chctx->flcoeffs1, chctx->flcoeffs2, chctx->bandWidthT, chctx->flcoeffs3, chctx->flcoeffs5);
Kostya Shishkov's avatar
Kostya Shishkov committed
832 833 834 835 836 837

    bitscount = 0;
    /* first 4 bands will be assigned 5 bits per coefficient */
    if (stream_format_code & 0x2) {
        bitscount += 15;

838 839 840 841
        chctx->bitsBandT[0] = 5;
        chctx->CWlengthT[0] = 5;
        chctx->CWlengthT[1] = 5;
        chctx->CWlengthT[2] = 5;
Kostya Shishkov's avatar
Kostya Shishkov committed
842
        for (i = 1; i < 4; i++) {
843 844
            bits = (chctx->levlCoeffBuf[i] == 16) ? 0 : 5;
            chctx->bitsBandT[i] = bits;
Kostya Shishkov's avatar
Kostya Shishkov committed
845
            for (j = band_tab[i]; j < band_tab[i + 1]; j++) {
846
                chctx->CWlengthT[j] = bits;
Kostya Shishkov's avatar
Kostya Shishkov committed
847
                bitscount      += bits;
Kostya Shishkov's avatar
Kostya Shishkov committed
848 849 850
            }
        }
    }
851
    if (avctx->codec_id == AV_CODEC_ID_IAC) {
Kostya Shishkov's avatar
Kostya Shishkov committed
852 853 854 855
        bitscount += !!chctx->bandWidthT[BANDS - 1];
        if (!(stream_format_code & 0x2))
            bitscount += 16;
    }
Kostya Shishkov's avatar
Kostya Shishkov committed
856

857
    if ((ret = bit_allocation(q, chctx, stream_format_code,
Kostya Shishkov's avatar
Kostya Shishkov committed
858 859
                              512 - bitscount - get_bits_count(&q->gb),
                              flag)) < 0) {
Kostya Shishkov's avatar
Kostya Shishkov committed
860
        av_log(avctx, AV_LOG_ERROR, "Bit allocations failed\n");
861
        chctx->decoder_reset = 1;
862
        return ret;
Kostya Shishkov's avatar
Kostya Shishkov committed
863 864
    }

Kostya Shishkov's avatar
Kostya Shishkov committed
865
    for (i = 0; i < BANDS; i++) {
866 867
        chctx->sumLenArr[i]   = 0;
        chctx->skipFlagRaw[i] = 0;
Kostya Shishkov's avatar
Kostya Shishkov committed
868
        for (j = band_tab[i]; j < band_tab[i + 1]; j++)
869 870 871 872
            chctx->sumLenArr[i] += chctx->CWlengthT[j];
        if (chctx->bandFlagsBuf[i])
            if ((((band_tab[i + 1] - band_tab[i]) * 1.5) > chctx->sumLenArr[i]) && (chctx->sumLenArr[i] > 0))
                chctx->skipFlagRaw[i] = 1;
Kostya Shishkov's avatar
Kostya Shishkov committed
873 874
    }

875
    imc_get_skip_coeff(q, chctx);
Kostya Shishkov's avatar
Kostya Shishkov committed
876

Kostya Shishkov's avatar
Kostya Shishkov committed
877
    for (i = 0; i < BANDS; i++) {
878
        chctx->flcoeffs6[i] = chctx->flcoeffs1[i];
Kostya Shishkov's avatar
Kostya Shishkov committed
879
        /* band has flag set and at least one coded coefficient */
880 881 882
        if (chctx->bandFlagsBuf[i] && (band_tab[i + 1] - band_tab[i]) != chctx->skipFlagCount[i]) {
            chctx->flcoeffs6[i] *= q->sqrt_tab[ band_tab[i + 1] - band_tab[i]] /
                                   q->sqrt_tab[(band_tab[i + 1] - band_tab[i] - chctx->skipFlagCount[i])];
Kostya Shishkov's avatar
Kostya Shishkov committed
883 884 885 886 887 888
        }
    }

    /* calculate bits left, bits needed and adjust bit allocation */
    bits = summer = 0;

Kostya Shishkov's avatar
Kostya Shishkov committed
889
    for (i = 0; i < BANDS; i++) {
890
        if (chctx->bandFlagsBuf[i]) {
Kostya Shishkov's avatar
Kostya Shishkov committed
891
            for (j = band_tab[i]; j < band_tab[i + 1]; j++) {
892 893 894
                if (chctx->skipFlags[j]) {
                    summer += chctx->CWlengthT[j];
                    chctx->CWlengthT[j] = 0;
Kostya Shishkov's avatar
Kostya Shishkov committed
895 896
                }
            }
897 898
            bits   += chctx->skipFlagBits[i];
            summer -= chctx->skipFlagBits[i];
Kostya Shishkov's avatar
Kostya Shishkov committed
899 900
        }
    }
901
    imc_adjust_bit_allocation(q, chctx, summer);
Kostya Shishkov's avatar
Kostya Shishkov committed
902

Kostya Shishkov's avatar
Kostya Shishkov committed
903
    for (i = 0; i < BANDS; i++) {
904
        chctx->sumLenArr[i] = 0;
Kostya Shishkov's avatar
Kostya Shishkov committed
905

Kostya Shishkov's avatar
Kostya Shishkov committed
906
        for (j = band_tab[i]; j < band_tab[i + 1]; j++)
907 908
            if (!chctx->skipFlags[j])
                chctx->sumLenArr[i] += chctx->CWlengthT[j];
Kostya Shishkov's avatar
Kostya Shishkov committed
909 910
    }

911
    memset(chctx->codewords, 0, sizeof(chctx->codewords));
Kostya Shishkov's avatar
Kostya Shishkov committed
912

913
    if (imc_get_coeffs(q, chctx) < 0) {
Kostya Shishkov's avatar
Kostya Shishkov committed
914
        av_log(avctx, AV_LOG_ERROR, "Read coefficients failed\n");
915
        chctx->decoder_reset = 1;
916
        return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
917 918
    }

919
    if (inverse_quant_coeff(q, chctx, stream_format_code) < 0) {
Kostya Shishkov's avatar
Kostya Shishkov committed
920
        av_log(avctx, AV_LOG_ERROR, "Inverse quantization of coefficients failed\n");
921
        chctx->decoder_reset = 1;
922
        return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
923 924
    }

925 926
    memset(chctx->skipFlags, 0, sizeof(chctx->skipFlags));

927
    imc_imdct256(q, chctx, avctx->channels);
928 929 930 931 932 933 934 935 936 937

    return 0;
}

static int imc_decode_frame(AVCodecContext *avctx, void *data,
                            int *got_frame_ptr, AVPacket *avpkt)
{
    const uint8_t *buf = avpkt->data;
    int buf_size = avpkt->size;
    int ret, i;
Kostya Shishkov's avatar
Kostya Shishkov committed
938

939 940 941 942
    IMCContext *q = avctx->priv_data;

    LOCAL_ALIGNED_16(uint16_t, buf16, [IMC_BLOCK_SIZE / 2]);

Kostya Shishkov's avatar
Kostya Shishkov committed
943 944
    if (buf_size < IMC_BLOCK_SIZE * avctx->channels) {
        av_log(avctx, AV_LOG_ERROR, "frame too small!\n");
945
        return AVERROR_INVALIDDATA;
Kostya Shishkov's avatar
Kostya Shishkov committed
946 947
    }

948 949 950 951 952 953
    /* get output buffer */
    q->frame.nb_samples = COEFFS;
    if ((ret = avctx->get_buffer(avctx, &q->frame)) < 0) {
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
        return ret;
    }
Kostya Shishkov's avatar
Kostya Shishkov committed
954

955
    for (i = 0; i < avctx->channels; i++) {
956
        q->out_samples = (float *)q->frame.extended_data[i];
957 958 959 960 961 962 963 964 965 966

        q->dsp.bswap16_buf(buf16, (const uint16_t*)buf, IMC_BLOCK_SIZE / 2);

        init_get_bits(&q->gb, (const uint8_t*)buf16, IMC_BLOCK_SIZE * 8);

        buf += IMC_BLOCK_SIZE;

        if ((ret = imc_decode_block(avctx, q, i)) < 0)
            return ret;
    }
Kostya Shishkov's avatar
Kostya Shishkov committed
967

Kostya Shishkov's avatar
Kostya Shishkov committed
968
    if (avctx->channels == 2) {
969 970
        q->dsp.butterflies_float((float *)q->frame.extended_data[0],
                                 (float *)q->frame.extended_data[1], COEFFS);
Kostya Shishkov's avatar
Kostya Shishkov committed
971
    }
Kostya Shishkov's avatar
Kostya Shishkov committed
972

973 974
    *got_frame_ptr   = 1;
    *(AVFrame *)data = q->frame;
Kostya Shishkov's avatar
Kostya Shishkov committed
975

976
    return IMC_BLOCK_SIZE * avctx->channels;
Kostya Shishkov's avatar
Kostya Shishkov committed
977 978 979
}


980
static av_cold int imc_decode_close(AVCodecContext * avctx)
Kostya Shishkov's avatar
Kostya Shishkov committed
981 982 983 984
{
    IMCContext *q = avctx->priv_data;

    ff_fft_end(&q->fft);
985

Kostya Shishkov's avatar
Kostya Shishkov committed
986 987 988
    return 0;
}

Michael Niedermayer's avatar
Michael Niedermayer committed
989 990 991 992 993 994 995 996
static av_cold void flush(AVCodecContext *avctx)
{
    IMCContext *q = avctx->priv_data;

    q->chctx[0].decoder_reset =
    q->chctx[1].decoder_reset = 1;
}

997
#if CONFIG_IMC_DECODER
998
AVCodec ff_imc_decoder = {
999 1000
    .name           = "imc",
    .type           = AVMEDIA_TYPE_AUDIO,
1001
    .id             = AV_CODEC_ID_IMC,
Kostya Shishkov's avatar
Kostya Shishkov committed
1002
    .priv_data_size = sizeof(IMCContext),
1003 1004 1005
    .init           = imc_decode_init,
    .close          = imc_decode_close,
    .decode         = imc_decode_frame,
Michael Niedermayer's avatar
Michael Niedermayer committed
1006
    .flush          = flush,
1007 1008
    .capabilities   = CODEC_CAP_DR1,
    .long_name      = NULL_IF_CONFIG_SMALL("IMC (Intel Music Coder)"),
1009 1010
    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
                                                      AV_SAMPLE_FMT_NONE },
Kostya Shishkov's avatar
Kostya Shishkov committed
1011
};
1012 1013
#endif
#if CONFIG_IAC_DECODER
Kostya Shishkov's avatar
Kostya Shishkov committed
1014 1015 1016
AVCodec ff_iac_decoder = {
    .name           = "iac",
    .type           = AVMEDIA_TYPE_AUDIO,
1017
    .id             = AV_CODEC_ID_IAC,
Kostya Shishkov's avatar
Kostya Shishkov committed
1018 1019 1020 1021
    .priv_data_size = sizeof(IMCContext),
    .init           = imc_decode_init,
    .close          = imc_decode_close,
    .decode         = imc_decode_frame,
Michael Niedermayer's avatar
Michael Niedermayer committed
1022
    .flush          = flush,
Kostya Shishkov's avatar
Kostya Shishkov committed
1023 1024
    .capabilities   = CODEC_CAP_DR1,
    .long_name      = NULL_IF_CONFIG_SMALL("IAC (Indeo Audio Coder)"),
1025 1026
    .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
                                                      AV_SAMPLE_FMT_NONE },
Kostya Shishkov's avatar
Kostya Shishkov committed
1027
};
1028
#endif