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