]> git.sesse.net Git - ffmpeg/blob - libavcodec/dca.c
6d0b966aab43a7fc8e9fe6ddb82ef7e0cf3a139f
[ffmpeg] / libavcodec / dca.c
1 /*
2  * DCA compatible decoder
3  * Copyright (C) 2004 Gildas Bazin
4  * Copyright (C) 2004 Benjamin Zores
5  * Copyright (C) 2006 Benjamin Larsson
6  * Copyright (C) 2007 Konstantin Shishkov
7  *
8  * This file is part of FFmpeg.
9  *
10  * FFmpeg is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * FFmpeg is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with FFmpeg; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23  */
24
25 /**
26  * @file libavcodec/dca.c
27  */
28
29 #include <math.h>
30 #include <stddef.h>
31 #include <stdio.h>
32
33 #include "libavutil/intmath.h"
34 #include "libavutil/intreadwrite.h"
35 #include "avcodec.h"
36 #include "dsputil.h"
37 #include "fft.h"
38 #include "get_bits.h"
39 #include "put_bits.h"
40 #include "dcadata.h"
41 #include "dcahuff.h"
42 #include "dca.h"
43 #include "synth_filter.h"
44 #include "dcadsp.h"
45
46 //#define TRACE
47
48 #define DCA_PRIM_CHANNELS_MAX (5)
49 #define DCA_SUBBANDS (32)
50 #define DCA_ABITS_MAX (32)      /* Should be 28 */
51 #define DCA_SUBSUBFAMES_MAX (4)
52 #define DCA_LFE_MAX (3)
53
54 enum DCAMode {
55     DCA_MONO = 0,
56     DCA_CHANNEL,
57     DCA_STEREO,
58     DCA_STEREO_SUMDIFF,
59     DCA_STEREO_TOTAL,
60     DCA_3F,
61     DCA_2F1R,
62     DCA_3F1R,
63     DCA_2F2R,
64     DCA_3F2R,
65     DCA_4F2R
66 };
67
68 /* Tables for mapping dts channel configurations to libavcodec multichannel api.
69  * Some compromises have been made for special configurations. Most configurations
70  * are never used so complete accuracy is not needed.
71  *
72  * L = left, R = right, C = center, S = surround, F = front, R = rear, T = total, OV = overhead.
73  * S  -> side, when both rear and back are configured move one of them to the side channel
74  * OV -> center back
75  * All 2 channel configurations -> CH_LAYOUT_STEREO
76  */
77
78 static const int64_t dca_core_channel_layout[] = {
79     CH_FRONT_CENTER,                                               ///< 1, A
80     CH_LAYOUT_STEREO,                                              ///< 2, A + B (dual mono)
81     CH_LAYOUT_STEREO,                                              ///< 2, L + R (stereo)
82     CH_LAYOUT_STEREO,                                              ///< 2, (L+R) + (L-R) (sum-difference)
83     CH_LAYOUT_STEREO,                                              ///< 2, LT +RT (left and right total)
84     CH_LAYOUT_STEREO|CH_FRONT_CENTER,                              ///< 3, C+L+R
85     CH_LAYOUT_STEREO|CH_BACK_CENTER,                               ///< 3, L+R+S
86     CH_LAYOUT_STEREO|CH_FRONT_CENTER|CH_BACK_CENTER,               ///< 4, C + L + R+ S
87     CH_LAYOUT_STEREO|CH_SIDE_LEFT|CH_SIDE_RIGHT,                   ///< 4, L + R +SL+ SR
88     CH_LAYOUT_STEREO|CH_FRONT_CENTER|CH_SIDE_LEFT|CH_SIDE_RIGHT,   ///< 5, C + L + R+ SL+SR
89     CH_LAYOUT_STEREO|CH_SIDE_LEFT|CH_SIDE_RIGHT|CH_FRONT_LEFT_OF_CENTER|CH_FRONT_RIGHT_OF_CENTER,                 ///< 6, CL + CR + L + R + SL + SR
90     CH_LAYOUT_STEREO|CH_BACK_LEFT|CH_BACK_RIGHT|CH_FRONT_CENTER|CH_BACK_CENTER,                                   ///< 6, C + L + R+ LR + RR + OV
91     CH_FRONT_CENTER|CH_FRONT_RIGHT_OF_CENTER|CH_FRONT_LEFT_OF_CENTER|CH_BACK_CENTER|CH_BACK_LEFT|CH_BACK_RIGHT,   ///< 6, CF+ CR+LF+ RF+LR + RR
92     CH_FRONT_LEFT_OF_CENTER|CH_FRONT_CENTER|CH_FRONT_RIGHT_OF_CENTER|CH_LAYOUT_STEREO|CH_SIDE_LEFT|CH_SIDE_RIGHT, ///< 7, CL + C + CR + L + R + SL + SR
93     CH_FRONT_LEFT_OF_CENTER|CH_FRONT_RIGHT_OF_CENTER|CH_LAYOUT_STEREO|CH_SIDE_LEFT|CH_SIDE_RIGHT|CH_BACK_LEFT|CH_BACK_RIGHT, ///< 8, CL + CR + L + R + SL1 + SL2+ SR1 + SR2
94     CH_FRONT_LEFT_OF_CENTER|CH_FRONT_CENTER|CH_FRONT_RIGHT_OF_CENTER|CH_LAYOUT_STEREO|CH_SIDE_LEFT|CH_BACK_CENTER|CH_SIDE_RIGHT, ///< 8, CL + C+ CR + L + R + SL + S+ SR
95 };
96
97 static const int8_t dca_lfe_index[] = {
98     1,2,2,2,2,3,2,3,2,3,2,3,1,3,2,3
99 };
100
101 static const int8_t dca_channel_reorder_lfe[][8] = {
102     { 0, -1, -1, -1, -1, -1, -1, -1},
103     { 0,  1, -1, -1, -1, -1, -1, -1},
104     { 0,  1, -1, -1, -1, -1, -1, -1},
105     { 0,  1, -1, -1, -1, -1, -1, -1},
106     { 0,  1, -1, -1, -1, -1, -1, -1},
107     { 2,  0,  1, -1, -1, -1, -1, -1},
108     { 0,  1,  3, -1, -1, -1, -1, -1},
109     { 2,  0,  1,  4, -1, -1, -1, -1},
110     { 0,  1,  3,  4, -1, -1, -1, -1},
111     { 2,  0,  1,  4,  5, -1, -1, -1},
112     { 3,  4,  0,  1,  5,  6, -1, -1},
113     { 2,  0,  1,  4,  5,  6, -1, -1},
114     { 0,  6,  4,  5,  2,  3, -1, -1},
115     { 4,  2,  5,  0,  1,  6,  7, -1},
116     { 5,  6,  0,  1,  7,  3,  8,  4},
117     { 4,  2,  5,  0,  1,  6,  8,  7},
118 };
119
120 static const int8_t dca_channel_reorder_nolfe[][8] = {
121     { 0, -1, -1, -1, -1, -1, -1, -1},
122     { 0,  1, -1, -1, -1, -1, -1, -1},
123     { 0,  1, -1, -1, -1, -1, -1, -1},
124     { 0,  1, -1, -1, -1, -1, -1, -1},
125     { 0,  1, -1, -1, -1, -1, -1, -1},
126     { 2,  0,  1, -1, -1, -1, -1, -1},
127     { 0,  1,  2, -1, -1, -1, -1, -1},
128     { 2,  0,  1,  3, -1, -1, -1, -1},
129     { 0,  1,  2,  3, -1, -1, -1, -1},
130     { 2,  0,  1,  3,  4, -1, -1, -1},
131     { 2,  3,  0,  1,  4,  5, -1, -1},
132     { 2,  0,  1,  3,  4,  5, -1, -1},
133     { 0,  5,  3,  4,  1,  2, -1, -1},
134     { 3,  2,  4,  0,  1,  5,  6, -1},
135     { 4,  5,  0,  1,  6,  2,  7,  3},
136     { 3,  2,  4,  0,  1,  5,  7,  6},
137 };
138
139
140 #define DCA_DOLBY 101           /* FIXME */
141
142 #define DCA_CHANNEL_BITS 6
143 #define DCA_CHANNEL_MASK 0x3F
144
145 #define DCA_LFE 0x80
146
147 #define HEADER_SIZE 14
148
149 #define DCA_MAX_FRAME_SIZE 16384
150
151 /** Bit allocation */
152 typedef struct {
153     int offset;                 ///< code values offset
154     int maxbits[8];             ///< max bits in VLC
155     int wrap;                   ///< wrap for get_vlc2()
156     VLC vlc[8];                 ///< actual codes
157 } BitAlloc;
158
159 static BitAlloc dca_bitalloc_index;    ///< indexes for samples VLC select
160 static BitAlloc dca_tmode;             ///< transition mode VLCs
161 static BitAlloc dca_scalefactor;       ///< scalefactor VLCs
162 static BitAlloc dca_smpl_bitalloc[11]; ///< samples VLCs
163
164 static av_always_inline int get_bitalloc(GetBitContext *gb, BitAlloc *ba, int idx)
165 {
166     return get_vlc2(gb, ba->vlc[idx].table, ba->vlc[idx].bits, ba->wrap) + ba->offset;
167 }
168
169 typedef struct {
170     AVCodecContext *avctx;
171     /* Frame header */
172     int frame_type;             ///< type of the current frame
173     int samples_deficit;        ///< deficit sample count
174     int crc_present;            ///< crc is present in the bitstream
175     int sample_blocks;          ///< number of PCM sample blocks
176     int frame_size;             ///< primary frame byte size
177     int amode;                  ///< audio channels arrangement
178     int sample_rate;            ///< audio sampling rate
179     int bit_rate;               ///< transmission bit rate
180     int bit_rate_index;         ///< transmission bit rate index
181
182     int downmix;                ///< embedded downmix enabled
183     int dynrange;               ///< embedded dynamic range flag
184     int timestamp;              ///< embedded time stamp flag
185     int aux_data;               ///< auxiliary data flag
186     int hdcd;                   ///< source material is mastered in HDCD
187     int ext_descr;              ///< extension audio descriptor flag
188     int ext_coding;             ///< extended coding flag
189     int aspf;                   ///< audio sync word insertion flag
190     int lfe;                    ///< low frequency effects flag
191     int predictor_history;      ///< predictor history flag
192     int header_crc;             ///< header crc check bytes
193     int multirate_inter;        ///< multirate interpolator switch
194     int version;                ///< encoder software revision
195     int copy_history;           ///< copy history
196     int source_pcm_res;         ///< source pcm resolution
197     int front_sum;              ///< front sum/difference flag
198     int surround_sum;           ///< surround sum/difference flag
199     int dialog_norm;            ///< dialog normalisation parameter
200
201     /* Primary audio coding header */
202     int subframes;              ///< number of subframes
203     int total_channels;         ///< number of channels including extensions
204     int prim_channels;          ///< number of primary audio channels
205     int subband_activity[DCA_PRIM_CHANNELS_MAX];    ///< subband activity count
206     int vq_start_subband[DCA_PRIM_CHANNELS_MAX];    ///< high frequency vq start subband
207     int joint_intensity[DCA_PRIM_CHANNELS_MAX];     ///< joint intensity coding index
208     int transient_huffman[DCA_PRIM_CHANNELS_MAX];   ///< transient mode code book
209     int scalefactor_huffman[DCA_PRIM_CHANNELS_MAX]; ///< scale factor code book
210     int bitalloc_huffman[DCA_PRIM_CHANNELS_MAX];    ///< bit allocation quantizer select
211     int quant_index_huffman[DCA_PRIM_CHANNELS_MAX][DCA_ABITS_MAX]; ///< quantization index codebook select
212     float scalefactor_adj[DCA_PRIM_CHANNELS_MAX][DCA_ABITS_MAX];   ///< scale factor adjustment
213
214     /* Primary audio coding side information */
215     int subsubframes;           ///< number of subsubframes
216     int partial_samples;        ///< partial subsubframe samples count
217     int prediction_mode[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];    ///< prediction mode (ADPCM used or not)
218     int prediction_vq[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];      ///< prediction VQ coefs
219     int bitalloc[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];           ///< bit allocation index
220     int transition_mode[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];    ///< transition mode (transients)
221     int scale_factor[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][2];    ///< scale factors (2 if transient)
222     int joint_huff[DCA_PRIM_CHANNELS_MAX];                       ///< joint subband scale factors codebook
223     int joint_scale_factor[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS]; ///< joint subband scale factors
224     int downmix_coef[DCA_PRIM_CHANNELS_MAX][2];                  ///< stereo downmix coefficients
225     int dynrange_coef;                                           ///< dynamic range coefficient
226
227     int high_freq_vq[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];       ///< VQ encoded high frequency subbands
228
229     float lfe_data[2 * DCA_SUBSUBFAMES_MAX * DCA_LFE_MAX *
230                    2 /*history */ ];    ///< Low frequency effect data
231     int lfe_scale_factor;
232
233     /* Subband samples history (for ADPCM) */
234     float subband_samples_hist[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][4];
235     DECLARE_ALIGNED(16, float, subband_fir_hist)[DCA_PRIM_CHANNELS_MAX][512];
236     DECLARE_ALIGNED(16, float, subband_fir_noidea)[DCA_PRIM_CHANNELS_MAX][32];
237     int hist_index[DCA_PRIM_CHANNELS_MAX];
238     DECLARE_ALIGNED(16, float, raXin)[32];
239
240     int output;                 ///< type of output
241     float add_bias;             ///< output bias
242     float scale_bias;           ///< output scale
243
244     DECLARE_ALIGNED(16, float, samples)[1536];  /* 6 * 256 = 1536, might only need 5 */
245     const float *samples_chanptr[6];
246
247     uint8_t dca_buffer[DCA_MAX_FRAME_SIZE];
248     int dca_buffer_size;        ///< how much data is in the dca_buffer
249
250     const int8_t* channel_order_tab;                             ///< channel reordering table, lfe and non lfe
251     GetBitContext gb;
252     /* Current position in DCA frame */
253     int current_subframe;
254     int current_subsubframe;
255
256     int debug_flag;             ///< used for suppressing repeated error messages output
257     DSPContext dsp;
258     FFTContext imdct;
259     SynthFilterContext synth;
260     DCADSPContext dcadsp;
261 } DCAContext;
262
263 static const uint16_t dca_vlc_offs[] = {
264         0,   512,   640,   768,  1282,  1794,  2436,  3080,  3770,  4454,  5364,
265      5372,  5380,  5388,  5392,  5396,  5412,  5420,  5428,  5460,  5492,  5508,
266      5572,  5604,  5668,  5796,  5860,  5892,  6412,  6668,  6796,  7308,  7564,
267      7820,  8076,  8620,  9132,  9388,  9910, 10166, 10680, 11196, 11726, 12240,
268     12752, 13298, 13810, 14326, 14840, 15500, 16022, 16540, 17158, 17678, 18264,
269     18796, 19352, 19926, 20468, 21472, 22398, 23014, 23622,
270 };
271
272 static av_cold void dca_init_vlcs(void)
273 {
274     static int vlcs_initialized = 0;
275     int i, j, c = 14;
276     static VLC_TYPE dca_table[23622][2];
277
278     if (vlcs_initialized)
279         return;
280
281     dca_bitalloc_index.offset = 1;
282     dca_bitalloc_index.wrap = 2;
283     for (i = 0; i < 5; i++) {
284         dca_bitalloc_index.vlc[i].table = &dca_table[dca_vlc_offs[i]];
285         dca_bitalloc_index.vlc[i].table_allocated = dca_vlc_offs[i + 1] - dca_vlc_offs[i];
286         init_vlc(&dca_bitalloc_index.vlc[i], bitalloc_12_vlc_bits[i], 12,
287                  bitalloc_12_bits[i], 1, 1,
288                  bitalloc_12_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
289     }
290     dca_scalefactor.offset = -64;
291     dca_scalefactor.wrap = 2;
292     for (i = 0; i < 5; i++) {
293         dca_scalefactor.vlc[i].table = &dca_table[dca_vlc_offs[i + 5]];
294         dca_scalefactor.vlc[i].table_allocated = dca_vlc_offs[i + 6] - dca_vlc_offs[i + 5];
295         init_vlc(&dca_scalefactor.vlc[i], SCALES_VLC_BITS, 129,
296                  scales_bits[i], 1, 1,
297                  scales_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
298     }
299     dca_tmode.offset = 0;
300     dca_tmode.wrap = 1;
301     for (i = 0; i < 4; i++) {
302         dca_tmode.vlc[i].table = &dca_table[dca_vlc_offs[i + 10]];
303         dca_tmode.vlc[i].table_allocated = dca_vlc_offs[i + 11] - dca_vlc_offs[i + 10];
304         init_vlc(&dca_tmode.vlc[i], tmode_vlc_bits[i], 4,
305                  tmode_bits[i], 1, 1,
306                  tmode_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
307     }
308
309     for(i = 0; i < 10; i++)
310         for(j = 0; j < 7; j++){
311             if(!bitalloc_codes[i][j]) break;
312             dca_smpl_bitalloc[i+1].offset = bitalloc_offsets[i];
313             dca_smpl_bitalloc[i+1].wrap = 1 + (j > 4);
314             dca_smpl_bitalloc[i+1].vlc[j].table = &dca_table[dca_vlc_offs[c]];
315             dca_smpl_bitalloc[i+1].vlc[j].table_allocated = dca_vlc_offs[c + 1] - dca_vlc_offs[c];
316             init_vlc(&dca_smpl_bitalloc[i+1].vlc[j], bitalloc_maxbits[i][j],
317                      bitalloc_sizes[i],
318                      bitalloc_bits[i][j], 1, 1,
319                      bitalloc_codes[i][j], 2, 2, INIT_VLC_USE_NEW_STATIC);
320             c++;
321         }
322     vlcs_initialized = 1;
323 }
324
325 static inline void get_array(GetBitContext *gb, int *dst, int len, int bits)
326 {
327     while(len--)
328         *dst++ = get_bits(gb, bits);
329 }
330
331 static int dca_parse_frame_header(DCAContext * s)
332 {
333     int i, j;
334     static const float adj_table[4] = { 1.0, 1.1250, 1.2500, 1.4375 };
335     static const int bitlen[11] = { 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3 };
336     static const int thr[11] = { 0, 1, 3, 3, 3, 3, 7, 7, 7, 7, 7 };
337
338     init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
339
340     /* Sync code */
341     get_bits(&s->gb, 32);
342
343     /* Frame header */
344     s->frame_type        = get_bits(&s->gb, 1);
345     s->samples_deficit   = get_bits(&s->gb, 5) + 1;
346     s->crc_present       = get_bits(&s->gb, 1);
347     s->sample_blocks     = get_bits(&s->gb, 7) + 1;
348     s->frame_size        = get_bits(&s->gb, 14) + 1;
349     if (s->frame_size < 95)
350         return -1;
351     s->amode             = get_bits(&s->gb, 6);
352     s->sample_rate       = dca_sample_rates[get_bits(&s->gb, 4)];
353     if (!s->sample_rate)
354         return -1;
355     s->bit_rate_index    = get_bits(&s->gb, 5);
356     s->bit_rate          = dca_bit_rates[s->bit_rate_index];
357     if (!s->bit_rate)
358         return -1;
359
360     s->downmix           = get_bits(&s->gb, 1);
361     s->dynrange          = get_bits(&s->gb, 1);
362     s->timestamp         = get_bits(&s->gb, 1);
363     s->aux_data          = get_bits(&s->gb, 1);
364     s->hdcd              = get_bits(&s->gb, 1);
365     s->ext_descr         = get_bits(&s->gb, 3);
366     s->ext_coding        = get_bits(&s->gb, 1);
367     s->aspf              = get_bits(&s->gb, 1);
368     s->lfe               = get_bits(&s->gb, 2);
369     s->predictor_history = get_bits(&s->gb, 1);
370
371     /* TODO: check CRC */
372     if (s->crc_present)
373         s->header_crc    = get_bits(&s->gb, 16);
374
375     s->multirate_inter   = get_bits(&s->gb, 1);
376     s->version           = get_bits(&s->gb, 4);
377     s->copy_history      = get_bits(&s->gb, 2);
378     s->source_pcm_res    = get_bits(&s->gb, 3);
379     s->front_sum         = get_bits(&s->gb, 1);
380     s->surround_sum      = get_bits(&s->gb, 1);
381     s->dialog_norm       = get_bits(&s->gb, 4);
382
383     /* FIXME: channels mixing levels */
384     s->output = s->amode;
385     if(s->lfe) s->output |= DCA_LFE;
386
387 #ifdef TRACE
388     av_log(s->avctx, AV_LOG_DEBUG, "frame type: %i\n", s->frame_type);
389     av_log(s->avctx, AV_LOG_DEBUG, "samples deficit: %i\n", s->samples_deficit);
390     av_log(s->avctx, AV_LOG_DEBUG, "crc present: %i\n", s->crc_present);
391     av_log(s->avctx, AV_LOG_DEBUG, "sample blocks: %i (%i samples)\n",
392            s->sample_blocks, s->sample_blocks * 32);
393     av_log(s->avctx, AV_LOG_DEBUG, "frame size: %i bytes\n", s->frame_size);
394     av_log(s->avctx, AV_LOG_DEBUG, "amode: %i (%i channels)\n",
395            s->amode, dca_channels[s->amode]);
396     av_log(s->avctx, AV_LOG_DEBUG, "sample rate: %i Hz\n",
397            s->sample_rate);
398     av_log(s->avctx, AV_LOG_DEBUG, "bit rate: %i bits/s\n",
399            s->bit_rate);
400     av_log(s->avctx, AV_LOG_DEBUG, "downmix: %i\n", s->downmix);
401     av_log(s->avctx, AV_LOG_DEBUG, "dynrange: %i\n", s->dynrange);
402     av_log(s->avctx, AV_LOG_DEBUG, "timestamp: %i\n", s->timestamp);
403     av_log(s->avctx, AV_LOG_DEBUG, "aux_data: %i\n", s->aux_data);
404     av_log(s->avctx, AV_LOG_DEBUG, "hdcd: %i\n", s->hdcd);
405     av_log(s->avctx, AV_LOG_DEBUG, "ext descr: %i\n", s->ext_descr);
406     av_log(s->avctx, AV_LOG_DEBUG, "ext coding: %i\n", s->ext_coding);
407     av_log(s->avctx, AV_LOG_DEBUG, "aspf: %i\n", s->aspf);
408     av_log(s->avctx, AV_LOG_DEBUG, "lfe: %i\n", s->lfe);
409     av_log(s->avctx, AV_LOG_DEBUG, "predictor history: %i\n",
410            s->predictor_history);
411     av_log(s->avctx, AV_LOG_DEBUG, "header crc: %i\n", s->header_crc);
412     av_log(s->avctx, AV_LOG_DEBUG, "multirate inter: %i\n",
413            s->multirate_inter);
414     av_log(s->avctx, AV_LOG_DEBUG, "version number: %i\n", s->version);
415     av_log(s->avctx, AV_LOG_DEBUG, "copy history: %i\n", s->copy_history);
416     av_log(s->avctx, AV_LOG_DEBUG,
417            "source pcm resolution: %i (%i bits/sample)\n",
418            s->source_pcm_res, dca_bits_per_sample[s->source_pcm_res]);
419     av_log(s->avctx, AV_LOG_DEBUG, "front sum: %i\n", s->front_sum);
420     av_log(s->avctx, AV_LOG_DEBUG, "surround sum: %i\n", s->surround_sum);
421     av_log(s->avctx, AV_LOG_DEBUG, "dialog norm: %i\n", s->dialog_norm);
422     av_log(s->avctx, AV_LOG_DEBUG, "\n");
423 #endif
424
425     /* Primary audio coding header */
426     s->subframes         = get_bits(&s->gb, 4) + 1;
427     s->total_channels    = get_bits(&s->gb, 3) + 1;
428     s->prim_channels     = s->total_channels;
429     if (s->prim_channels > DCA_PRIM_CHANNELS_MAX)
430         s->prim_channels = DCA_PRIM_CHANNELS_MAX;   /* We only support DTS core */
431
432
433     for (i = 0; i < s->prim_channels; i++) {
434         s->subband_activity[i] = get_bits(&s->gb, 5) + 2;
435         if (s->subband_activity[i] > DCA_SUBBANDS)
436             s->subband_activity[i] = DCA_SUBBANDS;
437     }
438     for (i = 0; i < s->prim_channels; i++) {
439         s->vq_start_subband[i] = get_bits(&s->gb, 5) + 1;
440         if (s->vq_start_subband[i] > DCA_SUBBANDS)
441             s->vq_start_subband[i] = DCA_SUBBANDS;
442     }
443     get_array(&s->gb, s->joint_intensity,     s->prim_channels, 3);
444     get_array(&s->gb, s->transient_huffman,   s->prim_channels, 2);
445     get_array(&s->gb, s->scalefactor_huffman, s->prim_channels, 3);
446     get_array(&s->gb, s->bitalloc_huffman,    s->prim_channels, 3);
447
448     /* Get codebooks quantization indexes */
449     memset(s->quant_index_huffman, 0, sizeof(s->quant_index_huffman));
450     for (j = 1; j < 11; j++)
451         for (i = 0; i < s->prim_channels; i++)
452             s->quant_index_huffman[i][j] = get_bits(&s->gb, bitlen[j]);
453
454     /* Get scale factor adjustment */
455     for (j = 0; j < 11; j++)
456         for (i = 0; i < s->prim_channels; i++)
457             s->scalefactor_adj[i][j] = 1;
458
459     for (j = 1; j < 11; j++)
460         for (i = 0; i < s->prim_channels; i++)
461             if (s->quant_index_huffman[i][j] < thr[j])
462                 s->scalefactor_adj[i][j] = adj_table[get_bits(&s->gb, 2)];
463
464     if (s->crc_present) {
465         /* Audio header CRC check */
466         get_bits(&s->gb, 16);
467     }
468
469     s->current_subframe = 0;
470     s->current_subsubframe = 0;
471
472 #ifdef TRACE
473     av_log(s->avctx, AV_LOG_DEBUG, "subframes: %i\n", s->subframes);
474     av_log(s->avctx, AV_LOG_DEBUG, "prim channels: %i\n", s->prim_channels);
475     for(i = 0; i < s->prim_channels; i++){
476         av_log(s->avctx, AV_LOG_DEBUG, "subband activity: %i\n", s->subband_activity[i]);
477         av_log(s->avctx, AV_LOG_DEBUG, "vq start subband: %i\n", s->vq_start_subband[i]);
478         av_log(s->avctx, AV_LOG_DEBUG, "joint intensity: %i\n", s->joint_intensity[i]);
479         av_log(s->avctx, AV_LOG_DEBUG, "transient mode codebook: %i\n", s->transient_huffman[i]);
480         av_log(s->avctx, AV_LOG_DEBUG, "scale factor codebook: %i\n", s->scalefactor_huffman[i]);
481         av_log(s->avctx, AV_LOG_DEBUG, "bit allocation quantizer: %i\n", s->bitalloc_huffman[i]);
482         av_log(s->avctx, AV_LOG_DEBUG, "quant index huff:");
483         for (j = 0; j < 11; j++)
484             av_log(s->avctx, AV_LOG_DEBUG, " %i",
485                    s->quant_index_huffman[i][j]);
486         av_log(s->avctx, AV_LOG_DEBUG, "\n");
487         av_log(s->avctx, AV_LOG_DEBUG, "scalefac adj:");
488         for (j = 0; j < 11; j++)
489             av_log(s->avctx, AV_LOG_DEBUG, " %1.3f", s->scalefactor_adj[i][j]);
490         av_log(s->avctx, AV_LOG_DEBUG, "\n");
491     }
492 #endif
493
494     return 0;
495 }
496
497
498 static inline int get_scale(GetBitContext *gb, int level, int value)
499 {
500    if (level < 5) {
501        /* huffman encoded */
502        value += get_bitalloc(gb, &dca_scalefactor, level);
503    } else if(level < 8)
504        value = get_bits(gb, level + 1);
505    return value;
506 }
507
508 static int dca_subframe_header(DCAContext * s)
509 {
510     /* Primary audio coding side information */
511     int j, k;
512
513     s->subsubframes = get_bits(&s->gb, 2) + 1;
514     s->partial_samples = get_bits(&s->gb, 3);
515     for (j = 0; j < s->prim_channels; j++) {
516         for (k = 0; k < s->subband_activity[j]; k++)
517             s->prediction_mode[j][k] = get_bits(&s->gb, 1);
518     }
519
520     /* Get prediction codebook */
521     for (j = 0; j < s->prim_channels; j++) {
522         for (k = 0; k < s->subband_activity[j]; k++) {
523             if (s->prediction_mode[j][k] > 0) {
524                 /* (Prediction coefficient VQ address) */
525                 s->prediction_vq[j][k] = get_bits(&s->gb, 12);
526             }
527         }
528     }
529
530     /* Bit allocation index */
531     for (j = 0; j < s->prim_channels; j++) {
532         for (k = 0; k < s->vq_start_subband[j]; k++) {
533             if (s->bitalloc_huffman[j] == 6)
534                 s->bitalloc[j][k] = get_bits(&s->gb, 5);
535             else if (s->bitalloc_huffman[j] == 5)
536                 s->bitalloc[j][k] = get_bits(&s->gb, 4);
537             else if (s->bitalloc_huffman[j] == 7) {
538                 av_log(s->avctx, AV_LOG_ERROR,
539                        "Invalid bit allocation index\n");
540                 return -1;
541             } else {
542                 s->bitalloc[j][k] =
543                     get_bitalloc(&s->gb, &dca_bitalloc_index, s->bitalloc_huffman[j]);
544             }
545
546             if (s->bitalloc[j][k] > 26) {
547 //                 av_log(s->avctx,AV_LOG_DEBUG,"bitalloc index [%i][%i] too big (%i)\n",
548 //                          j, k, s->bitalloc[j][k]);
549                 return -1;
550             }
551         }
552     }
553
554     /* Transition mode */
555     for (j = 0; j < s->prim_channels; j++) {
556         for (k = 0; k < s->subband_activity[j]; k++) {
557             s->transition_mode[j][k] = 0;
558             if (s->subsubframes > 1 &&
559                 k < s->vq_start_subband[j] && s->bitalloc[j][k] > 0) {
560                 s->transition_mode[j][k] =
561                     get_bitalloc(&s->gb, &dca_tmode, s->transient_huffman[j]);
562             }
563         }
564     }
565
566     for (j = 0; j < s->prim_channels; j++) {
567         const uint32_t *scale_table;
568         int scale_sum;
569
570         memset(s->scale_factor[j], 0, s->subband_activity[j] * sizeof(s->scale_factor[0][0][0]) * 2);
571
572         if (s->scalefactor_huffman[j] == 6)
573             scale_table = scale_factor_quant7;
574         else
575             scale_table = scale_factor_quant6;
576
577         /* When huffman coded, only the difference is encoded */
578         scale_sum = 0;
579
580         for (k = 0; k < s->subband_activity[j]; k++) {
581             if (k >= s->vq_start_subband[j] || s->bitalloc[j][k] > 0) {
582                 scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum);
583                 s->scale_factor[j][k][0] = scale_table[scale_sum];
584             }
585
586             if (k < s->vq_start_subband[j] && s->transition_mode[j][k]) {
587                 /* Get second scale factor */
588                 scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum);
589                 s->scale_factor[j][k][1] = scale_table[scale_sum];
590             }
591         }
592     }
593
594     /* Joint subband scale factor codebook select */
595     for (j = 0; j < s->prim_channels; j++) {
596         /* Transmitted only if joint subband coding enabled */
597         if (s->joint_intensity[j] > 0)
598             s->joint_huff[j] = get_bits(&s->gb, 3);
599     }
600
601     /* Scale factors for joint subband coding */
602     for (j = 0; j < s->prim_channels; j++) {
603         int source_channel;
604
605         /* Transmitted only if joint subband coding enabled */
606         if (s->joint_intensity[j] > 0) {
607             int scale = 0;
608             source_channel = s->joint_intensity[j] - 1;
609
610             /* When huffman coded, only the difference is encoded
611              * (is this valid as well for joint scales ???) */
612
613             for (k = s->subband_activity[j]; k < s->subband_activity[source_channel]; k++) {
614                 scale = get_scale(&s->gb, s->joint_huff[j], 0);
615                 scale += 64;    /* bias */
616                 s->joint_scale_factor[j][k] = scale;    /*joint_scale_table[scale]; */
617             }
618
619             if (!(s->debug_flag & 0x02)) {
620                 av_log(s->avctx, AV_LOG_DEBUG,
621                        "Joint stereo coding not supported\n");
622                 s->debug_flag |= 0x02;
623             }
624         }
625     }
626
627     /* Stereo downmix coefficients */
628     if (s->prim_channels > 2) {
629         if(s->downmix) {
630             for (j = 0; j < s->prim_channels; j++) {
631                 s->downmix_coef[j][0] = get_bits(&s->gb, 7);
632                 s->downmix_coef[j][1] = get_bits(&s->gb, 7);
633             }
634         } else {
635             int am = s->amode & DCA_CHANNEL_MASK;
636             for (j = 0; j < s->prim_channels; j++) {
637                 s->downmix_coef[j][0] = dca_default_coeffs[am][j][0];
638                 s->downmix_coef[j][1] = dca_default_coeffs[am][j][1];
639             }
640         }
641     }
642
643     /* Dynamic range coefficient */
644     if (s->dynrange)
645         s->dynrange_coef = get_bits(&s->gb, 8);
646
647     /* Side information CRC check word */
648     if (s->crc_present) {
649         get_bits(&s->gb, 16);
650     }
651
652     /*
653      * Primary audio data arrays
654      */
655
656     /* VQ encoded high frequency subbands */
657     for (j = 0; j < s->prim_channels; j++)
658         for (k = s->vq_start_subband[j]; k < s->subband_activity[j]; k++)
659             /* 1 vector -> 32 samples */
660             s->high_freq_vq[j][k] = get_bits(&s->gb, 10);
661
662     /* Low frequency effect data */
663     if (s->lfe) {
664         /* LFE samples */
665         int lfe_samples = 2 * s->lfe * s->subsubframes;
666         float lfe_scale;
667
668         for (j = lfe_samples; j < lfe_samples * 2; j++) {
669             /* Signed 8 bits int */
670             s->lfe_data[j] = get_sbits(&s->gb, 8);
671         }
672
673         /* Scale factor index */
674         s->lfe_scale_factor = scale_factor_quant7[get_bits(&s->gb, 8)];
675
676         /* Quantization step size * scale factor */
677         lfe_scale = 0.035 * s->lfe_scale_factor;
678
679         for (j = lfe_samples; j < lfe_samples * 2; j++)
680             s->lfe_data[j] *= lfe_scale;
681     }
682
683 #ifdef TRACE
684     av_log(s->avctx, AV_LOG_DEBUG, "subsubframes: %i\n", s->subsubframes);
685     av_log(s->avctx, AV_LOG_DEBUG, "partial samples: %i\n",
686            s->partial_samples);
687     for (j = 0; j < s->prim_channels; j++) {
688         av_log(s->avctx, AV_LOG_DEBUG, "prediction mode:");
689         for (k = 0; k < s->subband_activity[j]; k++)
690             av_log(s->avctx, AV_LOG_DEBUG, " %i", s->prediction_mode[j][k]);
691         av_log(s->avctx, AV_LOG_DEBUG, "\n");
692     }
693     for (j = 0; j < s->prim_channels; j++) {
694         for (k = 0; k < s->subband_activity[j]; k++)
695                 av_log(s->avctx, AV_LOG_DEBUG,
696                        "prediction coefs: %f, %f, %f, %f\n",
697                        (float) adpcm_vb[s->prediction_vq[j][k]][0] / 8192,
698                        (float) adpcm_vb[s->prediction_vq[j][k]][1] / 8192,
699                        (float) adpcm_vb[s->prediction_vq[j][k]][2] / 8192,
700                        (float) adpcm_vb[s->prediction_vq[j][k]][3] / 8192);
701     }
702     for (j = 0; j < s->prim_channels; j++) {
703         av_log(s->avctx, AV_LOG_DEBUG, "bitalloc index: ");
704         for (k = 0; k < s->vq_start_subband[j]; k++)
705             av_log(s->avctx, AV_LOG_DEBUG, "%2.2i ", s->bitalloc[j][k]);
706         av_log(s->avctx, AV_LOG_DEBUG, "\n");
707     }
708     for (j = 0; j < s->prim_channels; j++) {
709         av_log(s->avctx, AV_LOG_DEBUG, "Transition mode:");
710         for (k = 0; k < s->subband_activity[j]; k++)
711             av_log(s->avctx, AV_LOG_DEBUG, " %i", s->transition_mode[j][k]);
712         av_log(s->avctx, AV_LOG_DEBUG, "\n");
713     }
714     for (j = 0; j < s->prim_channels; j++) {
715         av_log(s->avctx, AV_LOG_DEBUG, "Scale factor:");
716         for (k = 0; k < s->subband_activity[j]; k++) {
717             if (k >= s->vq_start_subband[j] || s->bitalloc[j][k] > 0)
718                 av_log(s->avctx, AV_LOG_DEBUG, " %i", s->scale_factor[j][k][0]);
719             if (k < s->vq_start_subband[j] && s->transition_mode[j][k])
720                 av_log(s->avctx, AV_LOG_DEBUG, " %i(t)", s->scale_factor[j][k][1]);
721         }
722         av_log(s->avctx, AV_LOG_DEBUG, "\n");
723     }
724     for (j = 0; j < s->prim_channels; j++) {
725         if (s->joint_intensity[j] > 0) {
726             int source_channel = s->joint_intensity[j] - 1;
727             av_log(s->avctx, AV_LOG_DEBUG, "Joint scale factor index:\n");
728             for (k = s->subband_activity[j]; k < s->subband_activity[source_channel]; k++)
729                 av_log(s->avctx, AV_LOG_DEBUG, " %i", s->joint_scale_factor[j][k]);
730             av_log(s->avctx, AV_LOG_DEBUG, "\n");
731         }
732     }
733     if (s->prim_channels > 2 && s->downmix) {
734         av_log(s->avctx, AV_LOG_DEBUG, "Downmix coeffs:\n");
735         for (j = 0; j < s->prim_channels; j++) {
736             av_log(s->avctx, AV_LOG_DEBUG, "Channel 0,%d = %f\n", j, dca_downmix_coeffs[s->downmix_coef[j][0]]);
737             av_log(s->avctx, AV_LOG_DEBUG, "Channel 1,%d = %f\n", j, dca_downmix_coeffs[s->downmix_coef[j][1]]);
738         }
739         av_log(s->avctx, AV_LOG_DEBUG, "\n");
740     }
741     for (j = 0; j < s->prim_channels; j++)
742         for (k = s->vq_start_subband[j]; k < s->subband_activity[j]; k++)
743             av_log(s->avctx, AV_LOG_DEBUG, "VQ index: %i\n", s->high_freq_vq[j][k]);
744     if(s->lfe){
745         int lfe_samples = 2 * s->lfe * s->subsubframes;
746         av_log(s->avctx, AV_LOG_DEBUG, "LFE samples:\n");
747         for (j = lfe_samples; j < lfe_samples * 2; j++)
748             av_log(s->avctx, AV_LOG_DEBUG, " %f", s->lfe_data[j]);
749         av_log(s->avctx, AV_LOG_DEBUG, "\n");
750     }
751 #endif
752
753     return 0;
754 }
755
756 static void qmf_32_subbands(DCAContext * s, int chans,
757                             float samples_in[32][8], float *samples_out,
758                             float scale, float bias)
759 {
760     const float *prCoeff;
761     int i;
762
763     int sb_act = s->subband_activity[chans];
764     int subindex;
765
766     scale *= sqrt(1/8.0);
767
768     /* Select filter */
769     if (!s->multirate_inter)    /* Non-perfect reconstruction */
770         prCoeff = fir_32bands_nonperfect;
771     else                        /* Perfect reconstruction */
772         prCoeff = fir_32bands_perfect;
773
774     /* Reconstructed channel sample index */
775     for (subindex = 0; subindex < 8; subindex++) {
776         /* Load in one sample from each subband and clear inactive subbands */
777         for (i = 0; i < sb_act; i++){
778             uint32_t v = AV_RN32A(&samples_in[i][subindex]) ^ ((i-1)&2)<<30;
779             AV_WN32A(&s->raXin[i], v);
780         }
781         for (; i < 32; i++)
782             s->raXin[i] = 0.0;
783
784         s->synth.synth_filter_float(&s->imdct,
785                               s->subband_fir_hist[chans], &s->hist_index[chans],
786                               s->subband_fir_noidea[chans], prCoeff,
787                               samples_out, s->raXin, scale, bias);
788         samples_out+= 32;
789
790     }
791 }
792
793 static void lfe_interpolation_fir(DCAContext *s, int decimation_select,
794                                   int num_deci_sample, float *samples_in,
795                                   float *samples_out, float scale,
796                                   float bias)
797 {
798     /* samples_in: An array holding decimated samples.
799      *   Samples in current subframe starts from samples_in[0],
800      *   while samples_in[-1], samples_in[-2], ..., stores samples
801      *   from last subframe as history.
802      *
803      * samples_out: An array holding interpolated samples
804      */
805
806     int decifactor;
807     const float *prCoeff;
808     int deciindex;
809
810     /* Select decimation filter */
811     if (decimation_select == 1) {
812         decifactor = 64;
813         prCoeff = lfe_fir_128;
814     } else {
815         decifactor = 32;
816         prCoeff = lfe_fir_64;
817     }
818     /* Interpolation */
819     for (deciindex = 0; deciindex < num_deci_sample; deciindex++) {
820         s->dcadsp.lfe_fir(samples_out, samples_in, prCoeff, decifactor,
821                           scale, bias);
822         samples_in++;
823         samples_out += 2 * decifactor;
824     }
825 }
826
827 /* downmixing routines */
828 #define MIX_REAR1(samples, si1, rs, coef) \
829      samples[i]     += samples[si1] * coef[rs][0]; \
830      samples[i+256] += samples[si1] * coef[rs][1];
831
832 #define MIX_REAR2(samples, si1, si2, rs, coef) \
833      samples[i]     += samples[si1] * coef[rs][0] + samples[si2] * coef[rs+1][0]; \
834      samples[i+256] += samples[si1] * coef[rs][1] + samples[si2] * coef[rs+1][1];
835
836 #define MIX_FRONT3(samples, coef) \
837     t = samples[i]; \
838     samples[i]     = t * coef[0][0] + samples[i+256] * coef[1][0] + samples[i+512] * coef[2][0]; \
839     samples[i+256] = t * coef[0][1] + samples[i+256] * coef[1][1] + samples[i+512] * coef[2][1];
840
841 #define DOWNMIX_TO_STEREO(op1, op2) \
842     for(i = 0; i < 256; i++){ \
843         op1 \
844         op2 \
845     }
846
847 static void dca_downmix(float *samples, int srcfmt,
848                         int downmix_coef[DCA_PRIM_CHANNELS_MAX][2])
849 {
850     int i;
851     float t;
852     float coef[DCA_PRIM_CHANNELS_MAX][2];
853
854     for(i=0; i<DCA_PRIM_CHANNELS_MAX; i++) {
855         coef[i][0] = dca_downmix_coeffs[downmix_coef[i][0]];
856         coef[i][1] = dca_downmix_coeffs[downmix_coef[i][1]];
857     }
858
859     switch (srcfmt) {
860     case DCA_MONO:
861     case DCA_CHANNEL:
862     case DCA_STEREO_TOTAL:
863     case DCA_STEREO_SUMDIFF:
864     case DCA_4F2R:
865         av_log(NULL, 0, "Not implemented!\n");
866         break;
867     case DCA_STEREO:
868         break;
869     case DCA_3F:
870         DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),);
871         break;
872     case DCA_2F1R:
873         DOWNMIX_TO_STEREO(MIX_REAR1(samples, i + 512, 2, coef),);
874         break;
875     case DCA_3F1R:
876         DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
877                           MIX_REAR1(samples, i + 768, 3, coef));
878         break;
879     case DCA_2F2R:
880         DOWNMIX_TO_STEREO(MIX_REAR2(samples, i + 512, i + 768, 2, coef),);
881         break;
882     case DCA_3F2R:
883         DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
884                           MIX_REAR2(samples, i + 768, i + 1024, 3, coef));
885         break;
886     }
887 }
888
889
890 /* Very compact version of the block code decoder that does not use table
891  * look-up but is slightly slower */
892 static int decode_blockcode(int code, int levels, int *values)
893 {
894     int i;
895     int offset = (levels - 1) >> 1;
896
897     for (i = 0; i < 4; i++) {
898         int div = FASTDIV(code, levels);
899         values[i] = code - offset - div*levels;
900         code = div;
901     }
902
903     if (code == 0)
904         return 0;
905     else {
906         av_log(NULL, AV_LOG_ERROR, "ERROR: block code look-up failed\n");
907         return -1;
908     }
909 }
910
911 static const uint8_t abits_sizes[7] = { 7, 10, 12, 13, 15, 17, 19 };
912 static const uint8_t abits_levels[7] = { 3, 5, 7, 9, 13, 17, 25 };
913
914 static int dca_subsubframe(DCAContext * s)
915 {
916     int k, l;
917     int subsubframe = s->current_subsubframe;
918
919     const float *quant_step_table;
920
921     /* FIXME */
922     LOCAL_ALIGNED_16(float, subband_samples, [DCA_PRIM_CHANNELS_MAX], [DCA_SUBBANDS][8]);
923     LOCAL_ALIGNED_16(int, block, [8]);
924
925     /*
926      * Audio data
927      */
928
929     /* Select quantization step size table */
930     if (s->bit_rate_index == 0x1f)
931         quant_step_table = lossless_quant_d;
932     else
933         quant_step_table = lossy_quant_d;
934
935     for (k = 0; k < s->prim_channels; k++) {
936         for (l = 0; l < s->vq_start_subband[k]; l++) {
937             int m;
938
939             /* Select the mid-tread linear quantizer */
940             int abits = s->bitalloc[k][l];
941
942             float quant_step_size = quant_step_table[abits];
943
944             /*
945              * Determine quantization index code book and its type
946              */
947
948             /* Select quantization index code book */
949             int sel = s->quant_index_huffman[k][abits];
950
951             /*
952              * Extract bits from the bit stream
953              */
954             if(!abits){
955                 memset(subband_samples[k][l], 0, 8 * sizeof(subband_samples[0][0][0]));
956             } else {
957                 /* Deal with transients */
958                 int sfi = s->transition_mode[k][l] && subsubframe >= s->transition_mode[k][l];
959                 float rscale = quant_step_size * s->scale_factor[k][l][sfi] * s->scalefactor_adj[k][sel];
960
961                 if(abits >= 11 || !dca_smpl_bitalloc[abits].vlc[sel].table){
962                     if(abits <= 7){
963                         /* Block code */
964                         int block_code1, block_code2, size, levels;
965
966                         size = abits_sizes[abits-1];
967                         levels = abits_levels[abits-1];
968
969                         block_code1 = get_bits(&s->gb, size);
970                         /* FIXME Should test return value */
971                         decode_blockcode(block_code1, levels, block);
972                         block_code2 = get_bits(&s->gb, size);
973                         decode_blockcode(block_code2, levels, &block[4]);
974                     }else{
975                         /* no coding */
976                         for (m = 0; m < 8; m++)
977                             block[m] = get_sbits(&s->gb, abits - 3);
978                     }
979                 }else{
980                     /* Huffman coded */
981                     for (m = 0; m < 8; m++)
982                         block[m] = get_bitalloc(&s->gb, &dca_smpl_bitalloc[abits], sel);
983                 }
984
985                 s->dsp.int32_to_float_fmul_scalar(subband_samples[k][l],
986                                                   block, rscale, 8);
987             }
988
989             /*
990              * Inverse ADPCM if in prediction mode
991              */
992             if (s->prediction_mode[k][l]) {
993                 int n;
994                 for (m = 0; m < 8; m++) {
995                     for (n = 1; n <= 4; n++)
996                         if (m >= n)
997                             subband_samples[k][l][m] +=
998                                 (adpcm_vb[s->prediction_vq[k][l]][n - 1] *
999                                  subband_samples[k][l][m - n] / 8192);
1000                         else if (s->predictor_history)
1001                             subband_samples[k][l][m] +=
1002                                 (adpcm_vb[s->prediction_vq[k][l]][n - 1] *
1003                                  s->subband_samples_hist[k][l][m - n +
1004                                                                4] / 8192);
1005                 }
1006             }
1007         }
1008
1009         /*
1010          * Decode VQ encoded high frequencies
1011          */
1012         for (l = s->vq_start_subband[k]; l < s->subband_activity[k]; l++) {
1013             /* 1 vector -> 32 samples but we only need the 8 samples
1014              * for this subsubframe. */
1015             int m;
1016
1017             if (!s->debug_flag & 0x01) {
1018                 av_log(s->avctx, AV_LOG_DEBUG, "Stream with high frequencies VQ coding\n");
1019                 s->debug_flag |= 0x01;
1020             }
1021
1022             for (m = 0; m < 8; m++) {
1023                 subband_samples[k][l][m] =
1024                     high_freq_vq[s->high_freq_vq[k][l]][subsubframe * 8 +
1025                                                         m]
1026                     * (float) s->scale_factor[k][l][0] / 16.0;
1027             }
1028         }
1029     }
1030
1031     /* Check for DSYNC after subsubframe */
1032     if (s->aspf || subsubframe == s->subsubframes - 1) {
1033         if (0xFFFF == get_bits(&s->gb, 16)) {   /* 0xFFFF */
1034 #ifdef TRACE
1035             av_log(s->avctx, AV_LOG_DEBUG, "Got subframe DSYNC\n");
1036 #endif
1037         } else {
1038             av_log(s->avctx, AV_LOG_ERROR, "Didn't get subframe DSYNC\n");
1039         }
1040     }
1041
1042     /* Backup predictor history for adpcm */
1043     for (k = 0; k < s->prim_channels; k++)
1044         for (l = 0; l < s->vq_start_subband[k]; l++)
1045             memcpy(s->subband_samples_hist[k][l], &subband_samples[k][l][4],
1046                         4 * sizeof(subband_samples[0][0][0]));
1047
1048     /* 32 subbands QMF */
1049     for (k = 0; k < s->prim_channels; k++) {
1050 /*        static float pcm_to_double[8] =
1051             {32768.0, 32768.0, 524288.0, 524288.0, 0, 8388608.0, 8388608.0};*/
1052          qmf_32_subbands(s, k, subband_samples[k], &s->samples[256 * s->channel_order_tab[k]],
1053                             M_SQRT1_2*s->scale_bias /*pcm_to_double[s->source_pcm_res] */ ,
1054                             s->add_bias );
1055     }
1056
1057     /* Down mixing */
1058
1059     if (s->prim_channels > dca_channels[s->output & DCA_CHANNEL_MASK]) {
1060         dca_downmix(s->samples, s->amode, s->downmix_coef);
1061     }
1062
1063     /* Generate LFE samples for this subsubframe FIXME!!! */
1064     if (s->output & DCA_LFE) {
1065         int lfe_samples = 2 * s->lfe * s->subsubframes;
1066
1067         lfe_interpolation_fir(s, s->lfe, 2 * s->lfe,
1068                               s->lfe_data + lfe_samples +
1069                               2 * s->lfe * subsubframe,
1070                               &s->samples[256 * dca_lfe_index[s->amode]],
1071                               (1.0/256.0)*s->scale_bias,  s->add_bias);
1072         /* Outputs 20bits pcm samples */
1073     }
1074
1075     return 0;
1076 }
1077
1078
1079 static int dca_subframe_footer(DCAContext * s)
1080 {
1081     int aux_data_count = 0, i;
1082     int lfe_samples;
1083
1084     /*
1085      * Unpack optional information
1086      */
1087
1088     if (s->timestamp)
1089         get_bits(&s->gb, 32);
1090
1091     if (s->aux_data)
1092         aux_data_count = get_bits(&s->gb, 6);
1093
1094     for (i = 0; i < aux_data_count; i++)
1095         get_bits(&s->gb, 8);
1096
1097     if (s->crc_present && (s->downmix || s->dynrange))
1098         get_bits(&s->gb, 16);
1099
1100     lfe_samples = 2 * s->lfe * s->subsubframes;
1101     for (i = 0; i < lfe_samples; i++) {
1102         s->lfe_data[i] = s->lfe_data[i + lfe_samples];
1103     }
1104
1105     return 0;
1106 }
1107
1108 /**
1109  * Decode a dca frame block
1110  *
1111  * @param s     pointer to the DCAContext
1112  */
1113
1114 static int dca_decode_block(DCAContext * s)
1115 {
1116
1117     /* Sanity check */
1118     if (s->current_subframe >= s->subframes) {
1119         av_log(s->avctx, AV_LOG_DEBUG, "check failed: %i>%i",
1120                s->current_subframe, s->subframes);
1121         return -1;
1122     }
1123
1124     if (!s->current_subsubframe) {
1125 #ifdef TRACE
1126         av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subframe_header\n");
1127 #endif
1128         /* Read subframe header */
1129         if (dca_subframe_header(s))
1130             return -1;
1131     }
1132
1133     /* Read subsubframe */
1134 #ifdef TRACE
1135     av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subsubframe\n");
1136 #endif
1137     if (dca_subsubframe(s))
1138         return -1;
1139
1140     /* Update state */
1141     s->current_subsubframe++;
1142     if (s->current_subsubframe >= s->subsubframes) {
1143         s->current_subsubframe = 0;
1144         s->current_subframe++;
1145     }
1146     if (s->current_subframe >= s->subframes) {
1147 #ifdef TRACE
1148         av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subframe_footer\n");
1149 #endif
1150         /* Read subframe footer */
1151         if (dca_subframe_footer(s))
1152             return -1;
1153     }
1154
1155     return 0;
1156 }
1157
1158 /**
1159  * Convert bitstream to one representation based on sync marker
1160  */
1161 static int dca_convert_bitstream(const uint8_t * src, int src_size, uint8_t * dst,
1162                           int max_size)
1163 {
1164     uint32_t mrk;
1165     int i, tmp;
1166     const uint16_t *ssrc = (const uint16_t *) src;
1167     uint16_t *sdst = (uint16_t *) dst;
1168     PutBitContext pb;
1169
1170     if((unsigned)src_size > (unsigned)max_size) {
1171 //        av_log(NULL, AV_LOG_ERROR, "Input frame size larger then DCA_MAX_FRAME_SIZE!\n");
1172 //        return -1;
1173         src_size = max_size;
1174     }
1175
1176     mrk = AV_RB32(src);
1177     switch (mrk) {
1178     case DCA_MARKER_RAW_BE:
1179         memcpy(dst, src, src_size);
1180         return src_size;
1181     case DCA_MARKER_RAW_LE:
1182         for (i = 0; i < (src_size + 1) >> 1; i++)
1183             *sdst++ = bswap_16(*ssrc++);
1184         return src_size;
1185     case DCA_MARKER_14B_BE:
1186     case DCA_MARKER_14B_LE:
1187         init_put_bits(&pb, dst, max_size);
1188         for (i = 0; i < (src_size + 1) >> 1; i++, src += 2) {
1189             tmp = ((mrk == DCA_MARKER_14B_BE) ? AV_RB16(src) : AV_RL16(src)) & 0x3FFF;
1190             put_bits(&pb, 14, tmp);
1191         }
1192         flush_put_bits(&pb);
1193         return (put_bits_count(&pb) + 7) >> 3;
1194     default:
1195         return -1;
1196     }
1197 }
1198
1199 /**
1200  * Main frame decoding function
1201  * FIXME add arguments
1202  */
1203 static int dca_decode_frame(AVCodecContext * avctx,
1204                             void *data, int *data_size,
1205                             AVPacket *avpkt)
1206 {
1207     const uint8_t *buf = avpkt->data;
1208     int buf_size = avpkt->size;
1209
1210     int i;
1211     int16_t *samples = data;
1212     DCAContext *s = avctx->priv_data;
1213     int channels;
1214
1215
1216     s->dca_buffer_size = dca_convert_bitstream(buf, buf_size, s->dca_buffer, DCA_MAX_FRAME_SIZE);
1217     if (s->dca_buffer_size == -1) {
1218         av_log(avctx, AV_LOG_ERROR, "Not a valid DCA frame\n");
1219         return -1;
1220     }
1221
1222     init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
1223     if (dca_parse_frame_header(s) < 0) {
1224         //seems like the frame is corrupt, try with the next one
1225         *data_size=0;
1226         return buf_size;
1227     }
1228     //set AVCodec values with parsed data
1229     avctx->sample_rate = s->sample_rate;
1230     avctx->bit_rate = s->bit_rate;
1231
1232     channels = s->prim_channels + !!s->lfe;
1233
1234     if (s->amode<16) {
1235         avctx->channel_layout = dca_core_channel_layout[s->amode];
1236
1237         if (s->lfe) {
1238             avctx->channel_layout |= CH_LOW_FREQUENCY;
1239             s->channel_order_tab = dca_channel_reorder_lfe[s->amode];
1240         } else
1241             s->channel_order_tab = dca_channel_reorder_nolfe[s->amode];
1242
1243         if (s->prim_channels > 0 &&
1244             s->channel_order_tab[s->prim_channels - 1] < 0)
1245             return -1;
1246
1247         if(avctx->request_channels == 2 && s->prim_channels > 2) {
1248             channels = 2;
1249             s->output = DCA_STEREO;
1250             avctx->channel_layout = CH_LAYOUT_STEREO;
1251         }
1252     } else {
1253         av_log(avctx, AV_LOG_ERROR, "Non standard configuration %d !\n",s->amode);
1254         return -1;
1255     }
1256
1257
1258     /* There is nothing that prevents a dts frame to change channel configuration
1259        but FFmpeg doesn't support that so only set the channels if it is previously
1260        unset. Ideally during the first probe for channels the crc should be checked
1261        and only set avctx->channels when the crc is ok. Right now the decoder could
1262        set the channels based on a broken first frame.*/
1263     if (!avctx->channels)
1264         avctx->channels = channels;
1265
1266     if(*data_size < (s->sample_blocks / 8) * 256 * sizeof(int16_t) * channels)
1267         return -1;
1268     *data_size = 256 / 8 * s->sample_blocks * sizeof(int16_t) * channels;
1269     for (i = 0; i < (s->sample_blocks / 8); i++) {
1270         dca_decode_block(s);
1271         s->dsp.float_to_int16_interleave(samples, s->samples_chanptr, 256, channels);
1272         samples += 256 * channels;
1273     }
1274
1275     return buf_size;
1276 }
1277
1278
1279
1280 /**
1281  * DCA initialization
1282  *
1283  * @param avctx     pointer to the AVCodecContext
1284  */
1285
1286 static av_cold int dca_decode_init(AVCodecContext * avctx)
1287 {
1288     DCAContext *s = avctx->priv_data;
1289     int i;
1290
1291     s->avctx = avctx;
1292     dca_init_vlcs();
1293
1294     dsputil_init(&s->dsp, avctx);
1295     ff_mdct_init(&s->imdct, 6, 1, 1.0);
1296     ff_synth_filter_init(&s->synth);
1297     ff_dcadsp_init(&s->dcadsp);
1298
1299     for(i = 0; i < 6; i++)
1300         s->samples_chanptr[i] = s->samples + i * 256;
1301     avctx->sample_fmt = SAMPLE_FMT_S16;
1302
1303     if(s->dsp.float_to_int16_interleave == ff_float_to_int16_interleave_c) {
1304         s->add_bias = 385.0f;
1305         s->scale_bias = 1.0 / 32768.0;
1306     } else {
1307         s->add_bias = 0.0f;
1308         s->scale_bias = 1.0;
1309
1310         /* allow downmixing to stereo */
1311         if (avctx->channels > 0 && avctx->request_channels < avctx->channels &&
1312                 avctx->request_channels == 2) {
1313             avctx->channels = avctx->request_channels;
1314         }
1315     }
1316
1317
1318     return 0;
1319 }
1320
1321 static av_cold int dca_decode_end(AVCodecContext * avctx)
1322 {
1323     DCAContext *s = avctx->priv_data;
1324     ff_mdct_end(&s->imdct);
1325     return 0;
1326 }
1327
1328 AVCodec dca_decoder = {
1329     .name = "dca",
1330     .type = AVMEDIA_TYPE_AUDIO,
1331     .id = CODEC_ID_DTS,
1332     .priv_data_size = sizeof(DCAContext),
1333     .init = dca_decode_init,
1334     .decode = dca_decode_frame,
1335     .close = dca_decode_end,
1336     .long_name = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
1337 };