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