1/*
2 * IMC compatible decoder
3 * Copyright (c) 2002-2004 Maxim Poliakovski
4 * Copyright (c) 2006 Benjamin Larsson
5 * Copyright (c) 2006 Konstantin Shishkov
6 *
7 * This file is part of Libav.
8 *
9 * Libav is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * Libav is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with Libav; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23
24/**
25 *  @file
26 *  IMC - Intel Music Coder
27 *  A mdct based codec using a 256 points large transform
28 *  divied into 32 bands with some mix of scale factors.
29 *  Only mono is supported.
30 *
31 */
32
33
34#include <math.h>
35#include <stddef.h>
36#include <stdio.h>
37
38#include "avcodec.h"
39#include "get_bits.h"
40#include "dsputil.h"
41#include "fft.h"
42#include "libavutil/audioconvert.h"
43#include "sinewin.h"
44
45#include "imcdata.h"
46
47#define IMC_BLOCK_SIZE 64
48#define IMC_FRAME_ID 0x21
49#define BANDS 32
50#define COEFFS 256
51
52typedef struct {
53    AVFrame frame;
54
55    float old_floor[BANDS];
56    float flcoeffs1[BANDS];
57    float flcoeffs2[BANDS];
58    float flcoeffs3[BANDS];
59    float flcoeffs4[BANDS];
60    float flcoeffs5[BANDS];
61    float flcoeffs6[BANDS];
62    float CWdecoded[COEFFS];
63
64    /** MDCT tables */
65    //@{
66    float mdct_sine_window[COEFFS];
67    float post_cos[COEFFS];
68    float post_sin[COEFFS];
69    float pre_coef1[COEFFS];
70    float pre_coef2[COEFFS];
71    float last_fft_im[COEFFS];
72    //@}
73
74    int bandWidthT[BANDS];     ///< codewords per band
75    int bitsBandT[BANDS];      ///< how many bits per codeword in band
76    int CWlengthT[COEFFS];     ///< how many bits in each codeword
77    int levlCoeffBuf[BANDS];
78    int bandFlagsBuf[BANDS];   ///< flags for each band
79    int sumLenArr[BANDS];      ///< bits for all coeffs in band
80    int skipFlagRaw[BANDS];    ///< skip flags are stored in raw form or not
81    int skipFlagBits[BANDS];   ///< bits used to code skip flags
82    int skipFlagCount[BANDS];  ///< skipped coeffients per band
83    int skipFlags[COEFFS];     ///< skip coefficient decoding or not
84    int codewords[COEFFS];     ///< raw codewords read from bitstream
85    float sqrt_tab[30];
86    GetBitContext gb;
87    int decoder_reset;
88    float one_div_log2;
89
90    DSPContext dsp;
91    FFTContext fft;
92    DECLARE_ALIGNED(32, FFTComplex, samples)[COEFFS/2];
93    float *out_samples;
94} IMCContext;
95
96static VLC huffman_vlc[4][4];
97
98#define VLC_TABLES_SIZE 9512
99
100static const int vlc_offsets[17] = {
101    0,     640, 1156, 1732, 2308, 2852, 3396, 3924,
102    4452, 5220, 5860, 6628, 7268, 7908, 8424, 8936, VLC_TABLES_SIZE};
103
104static VLC_TYPE vlc_tables[VLC_TABLES_SIZE][2];
105
106static av_cold int imc_decode_init(AVCodecContext * avctx)
107{
108    int i, j, ret;
109    IMCContext *q = avctx->priv_data;
110    double r1, r2;
111
112    if (avctx->channels != 1) {
113        av_log_ask_for_sample(avctx, "Number of channels is not supported\n");
114        return AVERROR_PATCHWELCOME;
115    }
116
117    q->decoder_reset = 1;
118
119    for(i = 0; i < BANDS; i++)
120        q->old_floor[i] = 1.0;
121
122    /* Build mdct window, a simple sine window normalized with sqrt(2) */
123    ff_sine_window_init(q->mdct_sine_window, COEFFS);
124    for(i = 0; i < COEFFS; i++)
125        q->mdct_sine_window[i] *= sqrt(2.0);
126    for(i = 0; i < COEFFS/2; i++){
127        q->post_cos[i] = (1.0f / 32768) * cos(i / 256.0 * M_PI);
128        q->post_sin[i] = (1.0f / 32768) * sin(i / 256.0 * M_PI);
129
130        r1 = sin((i * 4.0 + 1.0) / 1024.0 * M_PI);
131        r2 = cos((i * 4.0 + 1.0) / 1024.0 * M_PI);
132
133        if (i & 0x1)
134        {
135            q->pre_coef1[i] =  (r1 + r2) * sqrt(2.0);
136            q->pre_coef2[i] = -(r1 - r2) * sqrt(2.0);
137        }
138        else
139        {
140            q->pre_coef1[i] = -(r1 + r2) * sqrt(2.0);
141            q->pre_coef2[i] =  (r1 - r2) * sqrt(2.0);
142        }
143
144        q->last_fft_im[i] = 0;
145    }
146
147    /* Generate a square root table */
148
149    for(i = 0; i < 30; i++) {
150        q->sqrt_tab[i] = sqrt(i);
151    }
152
153    /* initialize the VLC tables */
154    for(i = 0; i < 4 ; i++) {
155        for(j = 0; j < 4; j++) {
156            huffman_vlc[i][j].table = &vlc_tables[vlc_offsets[i * 4 + j]];
157            huffman_vlc[i][j].table_allocated = vlc_offsets[i * 4 + j + 1] - vlc_offsets[i * 4 + j];
158            init_vlc(&huffman_vlc[i][j], 9, imc_huffman_sizes[i],
159                     imc_huffman_lens[i][j], 1, 1,
160                     imc_huffman_bits[i][j], 2, 2, INIT_VLC_USE_NEW_STATIC);
161        }
162    }
163    q->one_div_log2 = 1/log(2);
164
165    if ((ret = ff_fft_init(&q->fft, 7, 1))) {
166        av_log(avctx, AV_LOG_INFO, "FFT init failed\n");
167        return ret;
168    }
169    dsputil_init(&q->dsp, avctx);
170    avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
171    avctx->channel_layout = AV_CH_LAYOUT_MONO;
172
173    avcodec_get_frame_defaults(&q->frame);
174    avctx->coded_frame = &q->frame;
175
176    return 0;
177}
178
179static void imc_calculate_coeffs(IMCContext* q, float* flcoeffs1, float* flcoeffs2, int* bandWidthT,
180                                float* flcoeffs3, float* flcoeffs5)
181{
182    float   workT1[BANDS];
183    float   workT2[BANDS];
184    float   workT3[BANDS];
185    float   snr_limit = 1.e-30;
186    float   accum = 0.0;
187    int i, cnt2;
188
189    for(i = 0; i < BANDS; i++) {
190        flcoeffs5[i] = workT2[i] = 0.0;
191        if (bandWidthT[i]){
192            workT1[i] = flcoeffs1[i] * flcoeffs1[i];
193            flcoeffs3[i] = 2.0 * flcoeffs2[i];
194        } else {
195            workT1[i] = 0.0;
196            flcoeffs3[i] = -30000.0;
197        }
198        workT3[i] = bandWidthT[i] * workT1[i] * 0.01;
199        if (workT3[i] <= snr_limit)
200            workT3[i] = 0.0;
201    }
202
203    for(i = 0; i < BANDS; i++) {
204        for(cnt2 = i; cnt2 < cyclTab[i]; cnt2++)
205            flcoeffs5[cnt2] = flcoeffs5[cnt2] + workT3[i];
206        workT2[cnt2-1] = workT2[cnt2-1] + workT3[i];
207    }
208
209    for(i = 1; i < BANDS; i++) {
210        accum = (workT2[i-1] + accum) * imc_weights1[i-1];
211        flcoeffs5[i] += accum;
212    }
213
214    for(i = 0; i < BANDS; i++)
215        workT2[i] = 0.0;
216
217    for(i = 0; i < BANDS; i++) {
218        for(cnt2 = i-1; cnt2 > cyclTab2[i]; cnt2--)
219            flcoeffs5[cnt2] += workT3[i];
220        workT2[cnt2+1] += workT3[i];
221    }
222
223    accum = 0.0;
224
225    for(i = BANDS-2; i >= 0; i--) {
226        accum = (workT2[i+1] + accum) * imc_weights2[i];
227        flcoeffs5[i] += accum;
228        //there is missing code here, but it seems to never be triggered
229    }
230}
231
232
233static void imc_read_level_coeffs(IMCContext* q, int stream_format_code, int* levlCoeffs)
234{
235    int i;
236    VLC *hufftab[4];
237    int start = 0;
238    const uint8_t *cb_sel;
239    int s;
240
241    s = stream_format_code >> 1;
242    hufftab[0] = &huffman_vlc[s][0];
243    hufftab[1] = &huffman_vlc[s][1];
244    hufftab[2] = &huffman_vlc[s][2];
245    hufftab[3] = &huffman_vlc[s][3];
246    cb_sel = imc_cb_select[s];
247
248    if(stream_format_code & 4)
249        start = 1;
250    if(start)
251        levlCoeffs[0] = get_bits(&q->gb, 7);
252    for(i = start; i < BANDS; i++){
253        levlCoeffs[i] = get_vlc2(&q->gb, hufftab[cb_sel[i]]->table, hufftab[cb_sel[i]]->bits, 2);
254        if(levlCoeffs[i] == 17)
255            levlCoeffs[i] += get_bits(&q->gb, 4);
256    }
257}
258
259static void imc_decode_level_coefficients(IMCContext* q, int* levlCoeffBuf, float* flcoeffs1,
260                                         float* flcoeffs2)
261{
262    int i, level;
263    float tmp, tmp2;
264    //maybe some frequency division thingy
265
266    flcoeffs1[0] = 20000.0 / pow (2, levlCoeffBuf[0] * 0.18945); // 0.18945 = log2(10) * 0.05703125
267    flcoeffs2[0] = log(flcoeffs1[0])/log(2);
268    tmp = flcoeffs1[0];
269    tmp2 = flcoeffs2[0];
270
271    for(i = 1; i < BANDS; i++) {
272        level = levlCoeffBuf[i];
273        if (level == 16) {
274            flcoeffs1[i] = 1.0;
275            flcoeffs2[i] = 0.0;
276        } else {
277            if (level < 17)
278                level -=7;
279            else if (level <= 24)
280                level -=32;
281            else
282                level -=16;
283
284            tmp  *= imc_exp_tab[15 + level];
285            tmp2 += 0.83048 * level;  // 0.83048 = log2(10) * 0.25
286            flcoeffs1[i] = tmp;
287            flcoeffs2[i] = tmp2;
288        }
289    }
290}
291
292
293static void imc_decode_level_coefficients2(IMCContext* q, int* levlCoeffBuf, float* old_floor, float* flcoeffs1,
294                                          float* flcoeffs2) {
295    int i;
296        //FIXME maybe flag_buf = noise coding and flcoeffs1 = new scale factors
297        //      and flcoeffs2 old scale factors
298        //      might be incomplete due to a missing table that is in the binary code
299    for(i = 0; i < BANDS; i++) {
300        flcoeffs1[i] = 0;
301        if(levlCoeffBuf[i] < 16) {
302            flcoeffs1[i] = imc_exp_tab2[levlCoeffBuf[i]] * old_floor[i];
303            flcoeffs2[i] = (levlCoeffBuf[i]-7) * 0.83048 + flcoeffs2[i]; // 0.83048 = log2(10) * 0.25
304        } else {
305            flcoeffs1[i] = old_floor[i];
306        }
307    }
308}
309
310/**
311 * Perform bit allocation depending on bits available
312 */
313static int bit_allocation (IMCContext* q, int stream_format_code, int freebits, int flag) {
314    int i, j;
315    const float limit = -1.e20;
316    float highest = 0.0;
317    int indx;
318    int t1 = 0;
319    int t2 = 1;
320    float summa = 0.0;
321    int iacc = 0;
322    int summer = 0;
323    int rres, cwlen;
324    float lowest = 1.e10;
325    int low_indx = 0;
326    float workT[32];
327    int flg;
328    int found_indx = 0;
329
330    for(i = 0; i < BANDS; i++)
331        highest = FFMAX(highest, q->flcoeffs1[i]);
332
333    for(i = 0; i < BANDS-1; i++) {
334        q->flcoeffs4[i] = q->flcoeffs3[i] - log(q->flcoeffs5[i])/log(2);
335    }
336    q->flcoeffs4[BANDS - 1] = limit;
337
338    highest = highest * 0.25;
339
340    for(i = 0; i < BANDS; i++) {
341        indx = -1;
342        if ((band_tab[i+1] - band_tab[i]) == q->bandWidthT[i])
343            indx = 0;
344
345        if ((band_tab[i+1] - band_tab[i]) > q->bandWidthT[i])
346            indx = 1;
347
348        if (((band_tab[i+1] - band_tab[i])/2) >= q->bandWidthT[i])
349            indx = 2;
350
351        if (indx == -1)
352            return AVERROR_INVALIDDATA;
353
354        q->flcoeffs4[i] = q->flcoeffs4[i] + xTab[(indx*2 + (q->flcoeffs1[i] < highest)) * 2 + flag];
355    }
356
357    if (stream_format_code & 0x2) {
358        q->flcoeffs4[0] = limit;
359        q->flcoeffs4[1] = limit;
360        q->flcoeffs4[2] = limit;
361        q->flcoeffs4[3] = limit;
362    }
363
364    for(i = (stream_format_code & 0x2)?4:0; i < BANDS-1; i++) {
365        iacc += q->bandWidthT[i];
366        summa += q->bandWidthT[i] * q->flcoeffs4[i];
367    }
368    q->bandWidthT[BANDS-1] = 0;
369    summa = (summa * 0.5 - freebits) / iacc;
370
371
372    for(i = 0; i < BANDS/2; i++) {
373        rres = summer - freebits;
374        if((rres >= -8) && (rres <= 8)) break;
375
376        summer = 0;
377        iacc = 0;
378
379        for(j = (stream_format_code & 0x2)?4:0; j < BANDS; j++) {
380            cwlen = av_clipf(((q->flcoeffs4[j] * 0.5) - summa + 0.5), 0, 6);
381
382            q->bitsBandT[j] = cwlen;
383            summer += q->bandWidthT[j] * cwlen;
384
385            if (cwlen > 0)
386                iacc += q->bandWidthT[j];
387        }
388
389        flg = t2;
390        t2 = 1;
391        if (freebits < summer)
392            t2 = -1;
393        if (i == 0)
394            flg = t2;
395        if(flg != t2)
396            t1++;
397
398        summa = (float)(summer - freebits) / ((t1 + 1) * iacc) + summa;
399    }
400
401    for(i = (stream_format_code & 0x2)?4:0; i < BANDS; i++) {
402        for(j = band_tab[i]; j < band_tab[i+1]; j++)
403            q->CWlengthT[j] = q->bitsBandT[i];
404    }
405
406    if (freebits > summer) {
407        for(i = 0; i < BANDS; i++) {
408            workT[i] = (q->bitsBandT[i] == 6) ? -1.e20 : (q->bitsBandT[i] * -2 + q->flcoeffs4[i] - 0.415);
409        }
410
411        highest = 0.0;
412
413        do{
414            if (highest <= -1.e20)
415                break;
416
417            found_indx = 0;
418            highest = -1.e20;
419
420            for(i = 0; i < BANDS; i++) {
421                if (workT[i] > highest) {
422                    highest = workT[i];
423                    found_indx = i;
424                }
425            }
426
427            if (highest > -1.e20) {
428                workT[found_indx] -= 2.0;
429                if (++(q->bitsBandT[found_indx]) == 6)
430                    workT[found_indx] = -1.e20;
431
432                for(j = band_tab[found_indx]; j < band_tab[found_indx+1] && (freebits > summer); j++){
433                    q->CWlengthT[j]++;
434                    summer++;
435                }
436            }
437        }while (freebits > summer);
438    }
439    if (freebits < summer) {
440        for(i = 0; i < BANDS; i++) {
441            workT[i] = q->bitsBandT[i] ? (q->bitsBandT[i] * -2 + q->flcoeffs4[i] + 1.585) : 1.e20;
442        }
443        if (stream_format_code & 0x2) {
444            workT[0] = 1.e20;
445            workT[1] = 1.e20;
446            workT[2] = 1.e20;
447            workT[3] = 1.e20;
448        }
449        while (freebits < summer){
450            lowest = 1.e10;
451            low_indx = 0;
452            for(i = 0; i < BANDS; i++) {
453                if (workT[i] < lowest) {
454                    lowest = workT[i];
455                    low_indx = i;
456                }
457            }
458            //if(lowest >= 1.e10) break;
459            workT[low_indx] = lowest + 2.0;
460
461            if (!(--q->bitsBandT[low_indx]))
462                workT[low_indx] = 1.e20;
463
464            for(j = band_tab[low_indx]; j < band_tab[low_indx+1] && (freebits < summer); j++){
465                if(q->CWlengthT[j] > 0){
466                    q->CWlengthT[j]--;
467                    summer--;
468                }
469            }
470        }
471    }
472    return 0;
473}
474
475static void imc_get_skip_coeff(IMCContext* q) {
476    int i, j;
477
478    memset(q->skipFlagBits, 0, sizeof(q->skipFlagBits));
479    memset(q->skipFlagCount, 0, sizeof(q->skipFlagCount));
480    for(i = 0; i < BANDS; i++) {
481        if (!q->bandFlagsBuf[i] || !q->bandWidthT[i])
482            continue;
483
484        if (!q->skipFlagRaw[i]) {
485            q->skipFlagBits[i] = band_tab[i+1] - band_tab[i];
486
487            for(j = band_tab[i]; j < band_tab[i+1]; j++) {
488                if ((q->skipFlags[j] = get_bits1(&q->gb)))
489                    q->skipFlagCount[i]++;
490            }
491        } else {
492            for(j = band_tab[i]; j < (band_tab[i+1]-1); j += 2) {
493                if(!get_bits1(&q->gb)){//0
494                    q->skipFlagBits[i]++;
495                    q->skipFlags[j]=1;
496                    q->skipFlags[j+1]=1;
497                    q->skipFlagCount[i] += 2;
498                }else{
499                    if(get_bits1(&q->gb)){//11
500                        q->skipFlagBits[i] +=2;
501                        q->skipFlags[j]=0;
502                        q->skipFlags[j+1]=1;
503                        q->skipFlagCount[i]++;
504                    }else{
505                        q->skipFlagBits[i] +=3;
506                        q->skipFlags[j+1]=0;
507                        if(!get_bits1(&q->gb)){//100
508                            q->skipFlags[j]=1;
509                            q->skipFlagCount[i]++;
510                        }else{//101
511                            q->skipFlags[j]=0;
512                        }
513                    }
514                }
515            }
516
517            if (j < band_tab[i+1]) {
518                q->skipFlagBits[i]++;
519                if ((q->skipFlags[j] = get_bits1(&q->gb)))
520                    q->skipFlagCount[i]++;
521            }
522        }
523    }
524}
525
526/**
527 * Increase highest' band coefficient sizes as some bits won't be used
528 */
529static void imc_adjust_bit_allocation (IMCContext* q, int summer) {
530    float workT[32];
531    int corrected = 0;
532    int i, j;
533    float highest = 0;
534    int found_indx=0;
535
536    for(i = 0; i < BANDS; i++) {
537        workT[i] = (q->bitsBandT[i] == 6) ? -1.e20 : (q->bitsBandT[i] * -2 + q->flcoeffs4[i] - 0.415);
538    }
539
540    while (corrected < summer) {
541        if(highest <= -1.e20)
542            break;
543
544        highest = -1.e20;
545
546        for(i = 0; i < BANDS; i++) {
547            if (workT[i] > highest) {
548                highest = workT[i];
549                found_indx = i;
550            }
551        }
552
553        if (highest > -1.e20) {
554            workT[found_indx] -= 2.0;
555            if (++(q->bitsBandT[found_indx]) == 6)
556                workT[found_indx] = -1.e20;
557
558            for(j = band_tab[found_indx]; j < band_tab[found_indx+1] && (corrected < summer); j++) {
559                if (!q->skipFlags[j] && (q->CWlengthT[j] < 6)) {
560                    q->CWlengthT[j]++;
561                    corrected++;
562                }
563            }
564        }
565    }
566}
567
568static void imc_imdct256(IMCContext *q) {
569    int i;
570    float re, im;
571
572    /* prerotation */
573    for(i=0; i < COEFFS/2; i++){
574        q->samples[i].re = -(q->pre_coef1[i] * q->CWdecoded[COEFFS-1-i*2]) -
575                           (q->pre_coef2[i] * q->CWdecoded[i*2]);
576        q->samples[i].im = (q->pre_coef2[i] * q->CWdecoded[COEFFS-1-i*2]) -
577                           (q->pre_coef1[i] * q->CWdecoded[i*2]);
578    }
579
580    /* FFT */
581    q->fft.fft_permute(&q->fft, q->samples);
582    q->fft.fft_calc   (&q->fft, q->samples);
583
584    /* postrotation, window and reorder */
585    for(i = 0; i < COEFFS/2; i++){
586        re = (q->samples[i].re * q->post_cos[i]) + (-q->samples[i].im * q->post_sin[i]);
587        im = (-q->samples[i].im * q->post_cos[i]) - (q->samples[i].re * q->post_sin[i]);
588        q->out_samples[i*2] = (q->mdct_sine_window[COEFFS-1-i*2] * q->last_fft_im[i]) + (q->mdct_sine_window[i*2] * re);
589        q->out_samples[COEFFS-1-i*2] = (q->mdct_sine_window[i*2] * q->last_fft_im[i]) - (q->mdct_sine_window[COEFFS-1-i*2] * re);
590        q->last_fft_im[i] = im;
591    }
592}
593
594static int inverse_quant_coeff (IMCContext* q, int stream_format_code) {
595    int i, j;
596    int middle_value, cw_len, max_size;
597    const float* quantizer;
598
599    for(i = 0; i < BANDS; i++) {
600        for(j = band_tab[i]; j < band_tab[i+1]; j++) {
601            q->CWdecoded[j] = 0;
602            cw_len = q->CWlengthT[j];
603
604            if (cw_len <= 0 || q->skipFlags[j])
605                continue;
606
607            max_size = 1 << cw_len;
608            middle_value = max_size >> 1;
609
610            if (q->codewords[j] >= max_size || q->codewords[j] < 0)
611                return AVERROR_INVALIDDATA;
612
613            if (cw_len >= 4){
614                quantizer = imc_quantizer2[(stream_format_code & 2) >> 1];
615                if (q->codewords[j] >= middle_value)
616                    q->CWdecoded[j] = quantizer[q->codewords[j] - 8] * q->flcoeffs6[i];
617                else
618                    q->CWdecoded[j] = -quantizer[max_size - q->codewords[j] - 8 - 1] * q->flcoeffs6[i];
619            }else{
620                quantizer = imc_quantizer1[((stream_format_code & 2) >> 1) | (q->bandFlagsBuf[i] << 1)];
621                if (q->codewords[j] >= middle_value)
622                    q->CWdecoded[j] = quantizer[q->codewords[j] - 1] * q->flcoeffs6[i];
623                else
624                    q->CWdecoded[j] = -quantizer[max_size - 2 - q->codewords[j]] * q->flcoeffs6[i];
625            }
626        }
627    }
628    return 0;
629}
630
631
632static int imc_get_coeffs (IMCContext* q) {
633    int i, j, cw_len, cw;
634
635    for(i = 0; i < BANDS; i++) {
636        if(!q->sumLenArr[i]) continue;
637        if (q->bandFlagsBuf[i] || q->bandWidthT[i]) {
638            for(j = band_tab[i]; j < band_tab[i+1]; j++) {
639                cw_len = q->CWlengthT[j];
640                cw = 0;
641
642                if (get_bits_count(&q->gb) + cw_len > 512){
643//av_log(NULL,0,"Band %i coeff %i cw_len %i\n",i,j,cw_len);
644                    return AVERROR_INVALIDDATA;
645                }
646
647                if(cw_len && (!q->bandFlagsBuf[i] || !q->skipFlags[j]))
648                    cw = get_bits(&q->gb, cw_len);
649
650                q->codewords[j] = cw;
651            }
652        }
653    }
654    return 0;
655}
656
657static int imc_decode_frame(AVCodecContext * avctx, void *data,
658                            int *got_frame_ptr, AVPacket *avpkt)
659{
660    const uint8_t *buf = avpkt->data;
661    int buf_size = avpkt->size;
662
663    IMCContext *q = avctx->priv_data;
664
665    int stream_format_code;
666    int imc_hdr, i, j, ret;
667    int flag;
668    int bits, summer;
669    int counter, bitscount;
670    LOCAL_ALIGNED_16(uint16_t, buf16, [IMC_BLOCK_SIZE / 2]);
671
672    if (buf_size < IMC_BLOCK_SIZE) {
673        av_log(avctx, AV_LOG_ERROR, "imc frame too small!\n");
674        return AVERROR_INVALIDDATA;
675    }
676
677    /* get output buffer */
678    q->frame.nb_samples = COEFFS;
679    if ((ret = avctx->get_buffer(avctx, &q->frame)) < 0) {
680        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
681        return ret;
682    }
683    q->out_samples = (float *)q->frame.data[0];
684
685    q->dsp.bswap16_buf(buf16, (const uint16_t*)buf, IMC_BLOCK_SIZE / 2);
686
687    init_get_bits(&q->gb, (const uint8_t*)buf16, IMC_BLOCK_SIZE * 8);
688
689    /* Check the frame header */
690    imc_hdr = get_bits(&q->gb, 9);
691    if (imc_hdr != IMC_FRAME_ID) {
692        av_log(avctx, AV_LOG_ERROR, "imc frame header check failed!\n");
693        av_log(avctx, AV_LOG_ERROR, "got %x instead of 0x21.\n", imc_hdr);
694        return AVERROR_INVALIDDATA;
695    }
696    stream_format_code = get_bits(&q->gb, 3);
697
698    if(stream_format_code & 1){
699        av_log(avctx, AV_LOG_ERROR, "Stream code format %X is not supported\n", stream_format_code);
700        return AVERROR_INVALIDDATA;
701    }
702
703//    av_log(avctx, AV_LOG_DEBUG, "stream_format_code = %d\n", stream_format_code);
704
705    if (stream_format_code & 0x04)
706        q->decoder_reset = 1;
707
708    if(q->decoder_reset) {
709        memset(q->out_samples, 0, sizeof(q->out_samples));
710        for(i = 0; i < BANDS; i++)q->old_floor[i] = 1.0;
711        for(i = 0; i < COEFFS; i++)q->CWdecoded[i] = 0;
712        q->decoder_reset = 0;
713    }
714
715    flag = get_bits1(&q->gb);
716    imc_read_level_coeffs(q, stream_format_code, q->levlCoeffBuf);
717
718    if (stream_format_code & 0x4)
719        imc_decode_level_coefficients(q, q->levlCoeffBuf, q->flcoeffs1, q->flcoeffs2);
720    else
721        imc_decode_level_coefficients2(q, q->levlCoeffBuf, q->old_floor, q->flcoeffs1, q->flcoeffs2);
722
723    memcpy(q->old_floor, q->flcoeffs1, 32 * sizeof(float));
724
725    counter = 0;
726    for (i=0 ; i<BANDS ; i++) {
727        if (q->levlCoeffBuf[i] == 16) {
728            q->bandWidthT[i] = 0;
729            counter++;
730        } else
731            q->bandWidthT[i] = band_tab[i+1] - band_tab[i];
732    }
733    memset(q->bandFlagsBuf, 0, BANDS * sizeof(int));
734    for(i = 0; i < BANDS-1; i++) {
735        if (q->bandWidthT[i])
736            q->bandFlagsBuf[i] = get_bits1(&q->gb);
737    }
738
739    imc_calculate_coeffs(q, q->flcoeffs1, q->flcoeffs2, q->bandWidthT, q->flcoeffs3, q->flcoeffs5);
740
741    bitscount = 0;
742    /* first 4 bands will be assigned 5 bits per coefficient */
743    if (stream_format_code & 0x2) {
744        bitscount += 15;
745
746        q->bitsBandT[0] = 5;
747        q->CWlengthT[0] = 5;
748        q->CWlengthT[1] = 5;
749        q->CWlengthT[2] = 5;
750        for(i = 1; i < 4; i++){
751            bits = (q->levlCoeffBuf[i] == 16) ? 0 : 5;
752            q->bitsBandT[i] = bits;
753            for(j = band_tab[i]; j < band_tab[i+1]; j++) {
754                q->CWlengthT[j] = bits;
755                bitscount += bits;
756            }
757        }
758    }
759
760    if((ret = bit_allocation (q, stream_format_code,
761                              512 - bitscount - get_bits_count(&q->gb), flag)) < 0) {
762        av_log(avctx, AV_LOG_ERROR, "Bit allocations failed\n");
763        q->decoder_reset = 1;
764        return ret;
765    }
766
767    for(i = 0; i < BANDS; i++) {
768        q->sumLenArr[i] = 0;
769        q->skipFlagRaw[i] = 0;
770        for(j = band_tab[i]; j < band_tab[i+1]; j++)
771            q->sumLenArr[i] += q->CWlengthT[j];
772        if (q->bandFlagsBuf[i])
773            if( (((band_tab[i+1] - band_tab[i]) * 1.5) > q->sumLenArr[i]) && (q->sumLenArr[i] > 0))
774                q->skipFlagRaw[i] = 1;
775    }
776
777    imc_get_skip_coeff(q);
778
779    for(i = 0; i < BANDS; i++) {
780        q->flcoeffs6[i] = q->flcoeffs1[i];
781        /* band has flag set and at least one coded coefficient */
782        if (q->bandFlagsBuf[i] && (band_tab[i+1] - band_tab[i]) != q->skipFlagCount[i]){
783                q->flcoeffs6[i] *= q->sqrt_tab[band_tab[i+1] - band_tab[i]] /
784                                   q->sqrt_tab[(band_tab[i+1] - band_tab[i] - q->skipFlagCount[i])];
785        }
786    }
787
788    /* calculate bits left, bits needed and adjust bit allocation */
789    bits = summer = 0;
790
791    for(i = 0; i < BANDS; i++) {
792        if (q->bandFlagsBuf[i]) {
793            for(j = band_tab[i]; j < band_tab[i+1]; j++) {
794                if(q->skipFlags[j]) {
795                    summer += q->CWlengthT[j];
796                    q->CWlengthT[j] = 0;
797                }
798            }
799            bits += q->skipFlagBits[i];
800            summer -= q->skipFlagBits[i];
801        }
802    }
803    imc_adjust_bit_allocation(q, summer);
804
805    for(i = 0; i < BANDS; i++) {
806        q->sumLenArr[i] = 0;
807
808        for(j = band_tab[i]; j < band_tab[i+1]; j++)
809            if (!q->skipFlags[j])
810                q->sumLenArr[i] += q->CWlengthT[j];
811    }
812
813    memset(q->codewords, 0, sizeof(q->codewords));
814
815    if(imc_get_coeffs(q) < 0) {
816        av_log(avctx, AV_LOG_ERROR, "Read coefficients failed\n");
817        q->decoder_reset = 1;
818        return AVERROR_INVALIDDATA;
819    }
820
821    if(inverse_quant_coeff(q, stream_format_code) < 0) {
822        av_log(avctx, AV_LOG_ERROR, "Inverse quantization of coefficients failed\n");
823        q->decoder_reset = 1;
824        return AVERROR_INVALIDDATA;
825    }
826
827    memset(q->skipFlags, 0, sizeof(q->skipFlags));
828
829    imc_imdct256(q);
830
831    *got_frame_ptr   = 1;
832    *(AVFrame *)data = q->frame;
833
834    return IMC_BLOCK_SIZE;
835}
836
837
838static av_cold int imc_decode_close(AVCodecContext * avctx)
839{
840    IMCContext *q = avctx->priv_data;
841
842    ff_fft_end(&q->fft);
843
844    return 0;
845}
846
847
848AVCodec ff_imc_decoder = {
849    .name = "imc",
850    .type = AVMEDIA_TYPE_AUDIO,
851    .id = CODEC_ID_IMC,
852    .priv_data_size = sizeof(IMCContext),
853    .init = imc_decode_init,
854    .close = imc_decode_close,
855    .decode = imc_decode_frame,
856    .capabilities = CODEC_CAP_DR1,
857    .long_name = NULL_IF_CONFIG_SMALL("IMC (Intel Music Coder)"),
858};
859