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