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