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