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