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