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