Statistics
| Branch: | Revision:

ffmpeg / libavcodec / dca.c @ 1402ee72

History | View | Annotate | Download (43.6 KB)

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
#define DCA_DOLBY 101           /* FIXME */
63

    
64
#define DCA_CHANNEL_BITS 6
65
#define DCA_CHANNEL_MASK 0x3F
66

    
67
#define DCA_LFE 0x80
68

    
69
#define HEADER_SIZE 14
70

    
71
#define DCA_MAX_FRAME_SIZE 16384
72

    
73
/** Bit allocation */
74
typedef struct {
75
    int offset;                 ///< code values offset
76
    int maxbits[8];             ///< max bits in VLC
77
    int wrap;                   ///< wrap for get_vlc2()
78
    VLC vlc[8];                 ///< actual codes
79
} BitAlloc;
80

    
81
static BitAlloc dca_bitalloc_index;    ///< indexes for samples VLC select
82
static BitAlloc dca_tmode;             ///< transition mode VLCs
83
static BitAlloc dca_scalefactor;       ///< scalefactor VLCs
84
static BitAlloc dca_smpl_bitalloc[11]; ///< samples VLCs
85

    
86
static av_always_inline int get_bitalloc(GetBitContext *gb, BitAlloc *ba, int idx)
87
{
88
    return get_vlc2(gb, ba->vlc[idx].table, ba->vlc[idx].bits, ba->wrap) + ba->offset;
89
}
90

    
91
typedef struct {
92
    AVCodecContext *avctx;
93
    /* Frame header */
94
    int frame_type;             ///< type of the current frame
95
    int samples_deficit;        ///< deficit sample count
96
    int crc_present;            ///< crc is present in the bitstream
97
    int sample_blocks;          ///< number of PCM sample blocks
98
    int frame_size;             ///< primary frame byte size
99
    int amode;                  ///< audio channels arrangement
100
    int sample_rate;            ///< audio sampling rate
101
    int bit_rate;               ///< transmission bit rate
102

    
103
    int downmix;                ///< embedded downmix enabled
104
    int dynrange;               ///< embedded dynamic range flag
105
    int timestamp;              ///< embedded time stamp flag
106
    int aux_data;               ///< auxiliary data flag
107
    int hdcd;                   ///< source material is mastered in HDCD
108
    int ext_descr;              ///< extension audio descriptor flag
109
    int ext_coding;             ///< extended coding flag
110
    int aspf;                   ///< audio sync word insertion flag
111
    int lfe;                    ///< low frequency effects flag
112
    int predictor_history;      ///< predictor history flag
113
    int header_crc;             ///< header crc check bytes
114
    int multirate_inter;        ///< multirate interpolator switch
115
    int version;                ///< encoder software revision
116
    int copy_history;           ///< copy history
117
    int source_pcm_res;         ///< source pcm resolution
118
    int front_sum;              ///< front sum/difference flag
119
    int surround_sum;           ///< surround sum/difference flag
120
    int dialog_norm;            ///< dialog normalisation parameter
121

    
122
    /* Primary audio coding header */
123
    int subframes;              ///< number of subframes
124
    int total_channels;         ///< number of channels including extensions
125
    int prim_channels;          ///< number of primary audio channels
126
    int subband_activity[DCA_PRIM_CHANNELS_MAX];    ///< subband activity count
127
    int vq_start_subband[DCA_PRIM_CHANNELS_MAX];    ///< high frequency vq start subband
128
    int joint_intensity[DCA_PRIM_CHANNELS_MAX];     ///< joint intensity coding index
129
    int transient_huffman[DCA_PRIM_CHANNELS_MAX];   ///< transient mode code book
130
    int scalefactor_huffman[DCA_PRIM_CHANNELS_MAX]; ///< scale factor code book
131
    int bitalloc_huffman[DCA_PRIM_CHANNELS_MAX];    ///< bit allocation quantizer select
132
    int quant_index_huffman[DCA_PRIM_CHANNELS_MAX][DCA_ABITS_MAX]; ///< quantization index codebook select
133
    float scalefactor_adj[DCA_PRIM_CHANNELS_MAX][DCA_ABITS_MAX];   ///< scale factor adjustment
134

    
135
    /* Primary audio coding side information */
136
    int subsubframes;           ///< number of subsubframes
137
    int partial_samples;        ///< partial subsubframe samples count
138
    int prediction_mode[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];    ///< prediction mode (ADPCM used or not)
139
    int prediction_vq[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];      ///< prediction VQ coefs
140
    int bitalloc[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];           ///< bit allocation index
141
    int transition_mode[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];    ///< transition mode (transients)
142
    int scale_factor[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][2];    ///< scale factors (2 if transient)
143
    int joint_huff[DCA_PRIM_CHANNELS_MAX];                       ///< joint subband scale factors codebook
144
    int joint_scale_factor[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS]; ///< joint subband scale factors
145
    int downmix_coef[DCA_PRIM_CHANNELS_MAX][2];                  ///< stereo downmix coefficients
146
    int dynrange_coef;                                           ///< dynamic range coefficient
147

    
148
    int high_freq_vq[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];       ///< VQ encoded high frequency subbands
149

    
150
    float lfe_data[2 * DCA_SUBSUBFAMES_MAX * DCA_LFE_MAX *
151
                   2 /*history */ ];    ///< Low frequency effect data
152
    int lfe_scale_factor;
153

    
154
    /* Subband samples history (for ADPCM) */
155
    float subband_samples_hist[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][4];
156
    DECLARE_ALIGNED_16(float, subband_fir_hist[DCA_PRIM_CHANNELS_MAX][512]);
157
    float subband_fir_noidea[DCA_PRIM_CHANNELS_MAX][32];
158
    int hist_index[DCA_PRIM_CHANNELS_MAX];
159

    
160
    int output;                 ///< type of output
161
    float add_bias;             ///< output bias
162
    float scale_bias;           ///< output scale
163

    
164
    DECLARE_ALIGNED_16(float, samples[1536]);  /* 6 * 256 = 1536, might only need 5 */
165
    const float *samples_chanptr[6];
166

    
167
    uint8_t dca_buffer[DCA_MAX_FRAME_SIZE];
168
    int dca_buffer_size;        ///< how much data is in the dca_buffer
169

    
170
    GetBitContext gb;
171
    /* Current position in DCA frame */
172
    int current_subframe;
173
    int current_subsubframe;
174

    
175
    int debug_flag;             ///< used for suppressing repeated error messages output
176
    DSPContext dsp;
177
    MDCTContext imdct;
178
} DCAContext;
179

    
180
static av_cold void dca_init_vlcs(void)
181
{
182
    static int vlcs_initialized = 0;
183
    int i, j;
184

    
185
    if (vlcs_initialized)
186
        return;
187

    
188
    dca_bitalloc_index.offset = 1;
189
    dca_bitalloc_index.wrap = 2;
190
    for (i = 0; i < 5; i++)
191
        init_vlc(&dca_bitalloc_index.vlc[i], bitalloc_12_vlc_bits[i], 12,
192
                 bitalloc_12_bits[i], 1, 1,
193
                 bitalloc_12_codes[i], 2, 2, 1);
194
    dca_scalefactor.offset = -64;
195
    dca_scalefactor.wrap = 2;
196
    for (i = 0; i < 5; i++)
197
        init_vlc(&dca_scalefactor.vlc[i], SCALES_VLC_BITS, 129,
198
                 scales_bits[i], 1, 1,
199
                 scales_codes[i], 2, 2, 1);
200
    dca_tmode.offset = 0;
201
    dca_tmode.wrap = 1;
202
    for (i = 0; i < 4; i++)
203
        init_vlc(&dca_tmode.vlc[i], tmode_vlc_bits[i], 4,
204
                 tmode_bits[i], 1, 1,
205
                 tmode_codes[i], 2, 2, 1);
206

    
207
    for(i = 0; i < 10; i++)
208
        for(j = 0; j < 7; j++){
209
            if(!bitalloc_codes[i][j]) break;
210
            dca_smpl_bitalloc[i+1].offset = bitalloc_offsets[i];
211
            dca_smpl_bitalloc[i+1].wrap = 1 + (j > 4);
212
            init_vlc(&dca_smpl_bitalloc[i+1].vlc[j], bitalloc_maxbits[i][j],
213
                     bitalloc_sizes[i],
214
                     bitalloc_bits[i][j], 1, 1,
215
                     bitalloc_codes[i][j], 2, 2, 1);
216
        }
217
    vlcs_initialized = 1;
218
}
219

    
220
static inline void get_array(GetBitContext *gb, int *dst, int len, int bits)
221
{
222
    while(len--)
223
        *dst++ = get_bits(gb, bits);
224
}
225

    
226
static int dca_parse_frame_header(DCAContext * s)
227
{
228
    int i, j;
229
    static const float adj_table[4] = { 1.0, 1.1250, 1.2500, 1.4375 };
230
    static const int bitlen[11] = { 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3 };
231
    static const int thr[11] = { 0, 1, 3, 3, 3, 3, 7, 7, 7, 7, 7 };
232

    
233
    init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
234

    
235
    /* Sync code */
236
    get_bits(&s->gb, 32);
237

    
238
    /* Frame header */
239
    s->frame_type        = get_bits(&s->gb, 1);
240
    s->samples_deficit   = get_bits(&s->gb, 5) + 1;
241
    s->crc_present       = get_bits(&s->gb, 1);
242
    s->sample_blocks     = get_bits(&s->gb, 7) + 1;
243
    s->frame_size        = get_bits(&s->gb, 14) + 1;
244
    if (s->frame_size < 95)
245
        return -1;
246
    s->amode             = get_bits(&s->gb, 6);
247
    s->sample_rate       = dca_sample_rates[get_bits(&s->gb, 4)];
248
    if (!s->sample_rate)
249
        return -1;
250
    s->bit_rate          = dca_bit_rates[get_bits(&s->gb, 5)];
251
    if (!s->bit_rate)
252
        return -1;
253

    
254
    s->downmix           = get_bits(&s->gb, 1);
255
    s->dynrange          = get_bits(&s->gb, 1);
256
    s->timestamp         = get_bits(&s->gb, 1);
257
    s->aux_data          = get_bits(&s->gb, 1);
258
    s->hdcd              = get_bits(&s->gb, 1);
259
    s->ext_descr         = get_bits(&s->gb, 3);
260
    s->ext_coding        = get_bits(&s->gb, 1);
261
    s->aspf              = get_bits(&s->gb, 1);
262
    s->lfe               = get_bits(&s->gb, 2);
263
    s->predictor_history = get_bits(&s->gb, 1);
264

    
265
    /* TODO: check CRC */
266
    if (s->crc_present)
267
        s->header_crc    = get_bits(&s->gb, 16);
268

    
269
    s->multirate_inter   = get_bits(&s->gb, 1);
270
    s->version           = get_bits(&s->gb, 4);
271
    s->copy_history      = get_bits(&s->gb, 2);
272
    s->source_pcm_res    = get_bits(&s->gb, 3);
273
    s->front_sum         = get_bits(&s->gb, 1);
274
    s->surround_sum      = get_bits(&s->gb, 1);
275
    s->dialog_norm       = get_bits(&s->gb, 4);
276

    
277
    /* FIXME: channels mixing levels */
278
    s->output = s->amode;
279
    if(s->lfe) s->output |= DCA_LFE;
280

    
281
#ifdef TRACE
282
    av_log(s->avctx, AV_LOG_DEBUG, "frame type: %i\n", s->frame_type);
283
    av_log(s->avctx, AV_LOG_DEBUG, "samples deficit: %i\n", s->samples_deficit);
284
    av_log(s->avctx, AV_LOG_DEBUG, "crc present: %i\n", s->crc_present);
285
    av_log(s->avctx, AV_LOG_DEBUG, "sample blocks: %i (%i samples)\n",
286
           s->sample_blocks, s->sample_blocks * 32);
287
    av_log(s->avctx, AV_LOG_DEBUG, "frame size: %i bytes\n", s->frame_size);
288
    av_log(s->avctx, AV_LOG_DEBUG, "amode: %i (%i channels)\n",
289
           s->amode, dca_channels[s->amode]);
290
    av_log(s->avctx, AV_LOG_DEBUG, "sample rate: %i Hz\n",
291
           s->sample_rate);
292
    av_log(s->avctx, AV_LOG_DEBUG, "bit rate: %i bits/s\n",
293
           s->bit_rate);
294
    av_log(s->avctx, AV_LOG_DEBUG, "downmix: %i\n", s->downmix);
295
    av_log(s->avctx, AV_LOG_DEBUG, "dynrange: %i\n", s->dynrange);
296
    av_log(s->avctx, AV_LOG_DEBUG, "timestamp: %i\n", s->timestamp);
297
    av_log(s->avctx, AV_LOG_DEBUG, "aux_data: %i\n", s->aux_data);
298
    av_log(s->avctx, AV_LOG_DEBUG, "hdcd: %i\n", s->hdcd);
299
    av_log(s->avctx, AV_LOG_DEBUG, "ext descr: %i\n", s->ext_descr);
300
    av_log(s->avctx, AV_LOG_DEBUG, "ext coding: %i\n", s->ext_coding);
301
    av_log(s->avctx, AV_LOG_DEBUG, "aspf: %i\n", s->aspf);
302
    av_log(s->avctx, AV_LOG_DEBUG, "lfe: %i\n", s->lfe);
303
    av_log(s->avctx, AV_LOG_DEBUG, "predictor history: %i\n",
304
           s->predictor_history);
305
    av_log(s->avctx, AV_LOG_DEBUG, "header crc: %i\n", s->header_crc);
306
    av_log(s->avctx, AV_LOG_DEBUG, "multirate inter: %i\n",
307
           s->multirate_inter);
308
    av_log(s->avctx, AV_LOG_DEBUG, "version number: %i\n", s->version);
309
    av_log(s->avctx, AV_LOG_DEBUG, "copy history: %i\n", s->copy_history);
310
    av_log(s->avctx, AV_LOG_DEBUG,
311
           "source pcm resolution: %i (%i bits/sample)\n",
312
           s->source_pcm_res, dca_bits_per_sample[s->source_pcm_res]);
313
    av_log(s->avctx, AV_LOG_DEBUG, "front sum: %i\n", s->front_sum);
314
    av_log(s->avctx, AV_LOG_DEBUG, "surround sum: %i\n", s->surround_sum);
315
    av_log(s->avctx, AV_LOG_DEBUG, "dialog norm: %i\n", s->dialog_norm);
316
    av_log(s->avctx, AV_LOG_DEBUG, "\n");
317
#endif
318

    
319
    /* Primary audio coding header */
320
    s->subframes         = get_bits(&s->gb, 4) + 1;
321
    s->total_channels    = get_bits(&s->gb, 3) + 1;
322
    s->prim_channels     = s->total_channels;
323
    if (s->prim_channels > DCA_PRIM_CHANNELS_MAX)
324
        s->prim_channels = DCA_PRIM_CHANNELS_MAX;   /* We only support DTS core */
325

    
326

    
327
    for (i = 0; i < s->prim_channels; i++) {
328
        s->subband_activity[i] = get_bits(&s->gb, 5) + 2;
329
        if (s->subband_activity[i] > DCA_SUBBANDS)
330
            s->subband_activity[i] = DCA_SUBBANDS;
331
    }
332
    for (i = 0; i < s->prim_channels; i++) {
333
        s->vq_start_subband[i] = get_bits(&s->gb, 5) + 1;
334
        if (s->vq_start_subband[i] > DCA_SUBBANDS)
335
            s->vq_start_subband[i] = DCA_SUBBANDS;
336
    }
337
    get_array(&s->gb, s->joint_intensity,     s->prim_channels, 3);
338
    get_array(&s->gb, s->transient_huffman,   s->prim_channels, 2);
339
    get_array(&s->gb, s->scalefactor_huffman, s->prim_channels, 3);
340
    get_array(&s->gb, s->bitalloc_huffman,    s->prim_channels, 3);
341

    
342
    /* Get codebooks quantization indexes */
343
    memset(s->quant_index_huffman, 0, sizeof(s->quant_index_huffman));
344
    for (j = 1; j < 11; j++)
345
        for (i = 0; i < s->prim_channels; i++)
346
            s->quant_index_huffman[i][j] = get_bits(&s->gb, bitlen[j]);
347

    
348
    /* Get scale factor adjustment */
349
    for (j = 0; j < 11; j++)
350
        for (i = 0; i < s->prim_channels; i++)
351
            s->scalefactor_adj[i][j] = 1;
352

    
353
    for (j = 1; j < 11; j++)
354
        for (i = 0; i < s->prim_channels; i++)
355
            if (s->quant_index_huffman[i][j] < thr[j])
356
                s->scalefactor_adj[i][j] = adj_table[get_bits(&s->gb, 2)];
357

    
358
    if (s->crc_present) {
359
        /* Audio header CRC check */
360
        get_bits(&s->gb, 16);
361
    }
362

    
363
    s->current_subframe = 0;
364
    s->current_subsubframe = 0;
365

    
366
#ifdef TRACE
367
    av_log(s->avctx, AV_LOG_DEBUG, "subframes: %i\n", s->subframes);
368
    av_log(s->avctx, AV_LOG_DEBUG, "prim channels: %i\n", s->prim_channels);
369
    for(i = 0; i < s->prim_channels; i++){
370
        av_log(s->avctx, AV_LOG_DEBUG, "subband activity: %i\n", s->subband_activity[i]);
371
        av_log(s->avctx, AV_LOG_DEBUG, "vq start subband: %i\n", s->vq_start_subband[i]);
372
        av_log(s->avctx, AV_LOG_DEBUG, "joint intensity: %i\n", s->joint_intensity[i]);
373
        av_log(s->avctx, AV_LOG_DEBUG, "transient mode codebook: %i\n", s->transient_huffman[i]);
374
        av_log(s->avctx, AV_LOG_DEBUG, "scale factor codebook: %i\n", s->scalefactor_huffman[i]);
375
        av_log(s->avctx, AV_LOG_DEBUG, "bit allocation quantizer: %i\n", s->bitalloc_huffman[i]);
376
        av_log(s->avctx, AV_LOG_DEBUG, "quant index huff:");
377
        for (j = 0; j < 11; j++)
378
            av_log(s->avctx, AV_LOG_DEBUG, " %i",
379
                   s->quant_index_huffman[i][j]);
380
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
381
        av_log(s->avctx, AV_LOG_DEBUG, "scalefac adj:");
382
        for (j = 0; j < 11; j++)
383
            av_log(s->avctx, AV_LOG_DEBUG, " %1.3f", s->scalefactor_adj[i][j]);
384
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
385
    }
386
#endif
387

    
388
    return 0;
389
}
390

    
391

    
392
static inline int get_scale(GetBitContext *gb, int level, int value)
393
{
394
   if (level < 5) {
395
       /* huffman encoded */
396
       value += get_bitalloc(gb, &dca_scalefactor, level);
397
   } else if(level < 8)
398
       value = get_bits(gb, level + 1);
399
   return value;
400
}
401

    
402
static int dca_subframe_header(DCAContext * s)
403
{
404
    /* Primary audio coding side information */
405
    int j, k;
406

    
407
    s->subsubframes = get_bits(&s->gb, 2) + 1;
408
    s->partial_samples = get_bits(&s->gb, 3);
409
    for (j = 0; j < s->prim_channels; j++) {
410
        for (k = 0; k < s->subband_activity[j]; k++)
411
            s->prediction_mode[j][k] = get_bits(&s->gb, 1);
412
    }
413

    
414
    /* Get prediction codebook */
415
    for (j = 0; j < s->prim_channels; j++) {
416
        for (k = 0; k < s->subband_activity[j]; k++) {
417
            if (s->prediction_mode[j][k] > 0) {
418
                /* (Prediction coefficient VQ address) */
419
                s->prediction_vq[j][k] = get_bits(&s->gb, 12);
420
            }
421
        }
422
    }
423

    
424
    /* Bit allocation index */
425
    for (j = 0; j < s->prim_channels; j++) {
426
        for (k = 0; k < s->vq_start_subband[j]; k++) {
427
            if (s->bitalloc_huffman[j] == 6)
428
                s->bitalloc[j][k] = get_bits(&s->gb, 5);
429
            else if (s->bitalloc_huffman[j] == 5)
430
                s->bitalloc[j][k] = get_bits(&s->gb, 4);
431
            else if (s->bitalloc_huffman[j] == 7) {
432
                av_log(s->avctx, AV_LOG_ERROR,
433
                       "Invalid bit allocation index\n");
434
                return -1;
435
            } else {
436
                s->bitalloc[j][k] =
437
                    get_bitalloc(&s->gb, &dca_bitalloc_index, s->bitalloc_huffman[j]);
438
            }
439

    
440
            if (s->bitalloc[j][k] > 26) {
441
//                 av_log(s->avctx,AV_LOG_DEBUG,"bitalloc index [%i][%i] too big (%i)\n",
442
//                          j, k, s->bitalloc[j][k]);
443
                return -1;
444
            }
445
        }
446
    }
447

    
448
    /* Transition mode */
449
    for (j = 0; j < s->prim_channels; j++) {
450
        for (k = 0; k < s->subband_activity[j]; k++) {
451
            s->transition_mode[j][k] = 0;
452
            if (s->subsubframes > 1 &&
453
                k < s->vq_start_subband[j] && s->bitalloc[j][k] > 0) {
454
                s->transition_mode[j][k] =
455
                    get_bitalloc(&s->gb, &dca_tmode, s->transient_huffman[j]);
456
            }
457
        }
458
    }
459

    
460
    for (j = 0; j < s->prim_channels; j++) {
461
        const uint32_t *scale_table;
462
        int scale_sum;
463

    
464
        memset(s->scale_factor[j], 0, s->subband_activity[j] * sizeof(s->scale_factor[0][0][0]) * 2);
465

    
466
        if (s->scalefactor_huffman[j] == 6)
467
            scale_table = scale_factor_quant7;
468
        else
469
            scale_table = scale_factor_quant6;
470

    
471
        /* When huffman coded, only the difference is encoded */
472
        scale_sum = 0;
473

    
474
        for (k = 0; k < s->subband_activity[j]; k++) {
475
            if (k >= s->vq_start_subband[j] || s->bitalloc[j][k] > 0) {
476
                scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum);
477
                s->scale_factor[j][k][0] = scale_table[scale_sum];
478
            }
479

    
480
            if (k < s->vq_start_subband[j] && s->transition_mode[j][k]) {
481
                /* Get second scale factor */
482
                scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum);
483
                s->scale_factor[j][k][1] = scale_table[scale_sum];
484
            }
485
        }
486
    }
487

    
488
    /* Joint subband scale factor codebook select */
489
    for (j = 0; j < s->prim_channels; j++) {
490
        /* Transmitted only if joint subband coding enabled */
491
        if (s->joint_intensity[j] > 0)
492
            s->joint_huff[j] = get_bits(&s->gb, 3);
493
    }
494

    
495
    /* Scale factors for joint subband coding */
496
    for (j = 0; j < s->prim_channels; j++) {
497
        int source_channel;
498

    
499
        /* Transmitted only if joint subband coding enabled */
500
        if (s->joint_intensity[j] > 0) {
501
            int scale = 0;
502
            source_channel = s->joint_intensity[j] - 1;
503

    
504
            /* When huffman coded, only the difference is encoded
505
             * (is this valid as well for joint scales ???) */
506

    
507
            for (k = s->subband_activity[j]; k < s->subband_activity[source_channel]; k++) {
508
                scale = get_scale(&s->gb, s->joint_huff[j], 0);
509
                scale += 64;    /* bias */
510
                s->joint_scale_factor[j][k] = scale;    /*joint_scale_table[scale]; */
511
            }
512

    
513
            if (!s->debug_flag & 0x02) {
514
                av_log(s->avctx, AV_LOG_DEBUG,
515
                       "Joint stereo coding not supported\n");
516
                s->debug_flag |= 0x02;
517
            }
518
        }
519
    }
520

    
521
    /* Stereo downmix coefficients */
522
    if (s->prim_channels > 2) {
523
        if(s->downmix) {
524
            for (j = 0; j < s->prim_channels; j++) {
525
                s->downmix_coef[j][0] = get_bits(&s->gb, 7);
526
                s->downmix_coef[j][1] = get_bits(&s->gb, 7);
527
            }
528
        } else {
529
            int am = s->amode & DCA_CHANNEL_MASK;
530
            for (j = 0; j < s->prim_channels; j++) {
531
                s->downmix_coef[j][0] = dca_default_coeffs[am][j][0];
532
                s->downmix_coef[j][1] = dca_default_coeffs[am][j][1];
533
            }
534
        }
535
    }
536

    
537
    /* Dynamic range coefficient */
538
    if (s->dynrange)
539
        s->dynrange_coef = get_bits(&s->gb, 8);
540

    
541
    /* Side information CRC check word */
542
    if (s->crc_present) {
543
        get_bits(&s->gb, 16);
544
    }
545

    
546
    /*
547
     * Primary audio data arrays
548
     */
549

    
550
    /* VQ encoded high frequency subbands */
551
    for (j = 0; j < s->prim_channels; j++)
552
        for (k = s->vq_start_subband[j]; k < s->subband_activity[j]; k++)
553
            /* 1 vector -> 32 samples */
554
            s->high_freq_vq[j][k] = get_bits(&s->gb, 10);
555

    
556
    /* Low frequency effect data */
557
    if (s->lfe) {
558
        /* LFE samples */
559
        int lfe_samples = 2 * s->lfe * s->subsubframes;
560
        float lfe_scale;
561

    
562
        for (j = lfe_samples; j < lfe_samples * 2; j++) {
563
            /* Signed 8 bits int */
564
            s->lfe_data[j] = get_sbits(&s->gb, 8);
565
        }
566

    
567
        /* Scale factor index */
568
        s->lfe_scale_factor = scale_factor_quant7[get_bits(&s->gb, 8)];
569

    
570
        /* Quantization step size * scale factor */
571
        lfe_scale = 0.035 * s->lfe_scale_factor;
572

    
573
        for (j = lfe_samples; j < lfe_samples * 2; j++)
574
            s->lfe_data[j] *= lfe_scale;
575
    }
576

    
577
#ifdef TRACE
578
    av_log(s->avctx, AV_LOG_DEBUG, "subsubframes: %i\n", s->subsubframes);
579
    av_log(s->avctx, AV_LOG_DEBUG, "partial samples: %i\n",
580
           s->partial_samples);
581
    for (j = 0; j < s->prim_channels; j++) {
582
        av_log(s->avctx, AV_LOG_DEBUG, "prediction mode:");
583
        for (k = 0; k < s->subband_activity[j]; k++)
584
            av_log(s->avctx, AV_LOG_DEBUG, " %i", s->prediction_mode[j][k]);
585
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
586
    }
587
    for (j = 0; j < s->prim_channels; j++) {
588
        for (k = 0; k < s->subband_activity[j]; k++)
589
                av_log(s->avctx, AV_LOG_DEBUG,
590
                       "prediction coefs: %f, %f, %f, %f\n",
591
                       (float) adpcm_vb[s->prediction_vq[j][k]][0] / 8192,
592
                       (float) adpcm_vb[s->prediction_vq[j][k]][1] / 8192,
593
                       (float) adpcm_vb[s->prediction_vq[j][k]][2] / 8192,
594
                       (float) adpcm_vb[s->prediction_vq[j][k]][3] / 8192);
595
    }
596
    for (j = 0; j < s->prim_channels; j++) {
597
        av_log(s->avctx, AV_LOG_DEBUG, "bitalloc index: ");
598
        for (k = 0; k < s->vq_start_subband[j]; k++)
599
            av_log(s->avctx, AV_LOG_DEBUG, "%2.2i ", s->bitalloc[j][k]);
600
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
601
    }
602
    for (j = 0; j < s->prim_channels; j++) {
603
        av_log(s->avctx, AV_LOG_DEBUG, "Transition mode:");
604
        for (k = 0; k < s->subband_activity[j]; k++)
605
            av_log(s->avctx, AV_LOG_DEBUG, " %i", s->transition_mode[j][k]);
606
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
607
    }
608
    for (j = 0; j < s->prim_channels; j++) {
609
        av_log(s->avctx, AV_LOG_DEBUG, "Scale factor:");
610
        for (k = 0; k < s->subband_activity[j]; k++) {
611
            if (k >= s->vq_start_subband[j] || s->bitalloc[j][k] > 0)
612
                av_log(s->avctx, AV_LOG_DEBUG, " %i", s->scale_factor[j][k][0]);
613
            if (k < s->vq_start_subband[j] && s->transition_mode[j][k])
614
                av_log(s->avctx, AV_LOG_DEBUG, " %i(t)", s->scale_factor[j][k][1]);
615
        }
616
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
617
    }
618
    for (j = 0; j < s->prim_channels; j++) {
619
        if (s->joint_intensity[j] > 0) {
620
            int source_channel = s->joint_intensity[j] - 1;
621
            av_log(s->avctx, AV_LOG_DEBUG, "Joint scale factor index:\n");
622
            for (k = s->subband_activity[j]; k < s->subband_activity[source_channel]; k++)
623
                av_log(s->avctx, AV_LOG_DEBUG, " %i", s->joint_scale_factor[j][k]);
624
            av_log(s->avctx, AV_LOG_DEBUG, "\n");
625
        }
626
    }
627
    if (s->prim_channels > 2 && s->downmix) {
628
        av_log(s->avctx, AV_LOG_DEBUG, "Downmix coeffs:\n");
629
        for (j = 0; j < s->prim_channels; j++) {
630
            av_log(s->avctx, AV_LOG_DEBUG, "Channel 0,%d = %f\n", j, dca_downmix_coeffs[s->downmix_coef[j][0]]);
631
            av_log(s->avctx, AV_LOG_DEBUG, "Channel 1,%d = %f\n", j, dca_downmix_coeffs[s->downmix_coef[j][1]]);
632
        }
633
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
634
    }
635
    for (j = 0; j < s->prim_channels; j++)
636
        for (k = s->vq_start_subband[j]; k < s->subband_activity[j]; k++)
637
            av_log(s->avctx, AV_LOG_DEBUG, "VQ index: %i\n", s->high_freq_vq[j][k]);
638
    if(s->lfe){
639
        int lfe_samples = 2 * s->lfe * s->subsubframes;
640
        av_log(s->avctx, AV_LOG_DEBUG, "LFE samples:\n");
641
        for (j = lfe_samples; j < lfe_samples * 2; j++)
642
            av_log(s->avctx, AV_LOG_DEBUG, " %f", s->lfe_data[j]);
643
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
644
    }
645
#endif
646

    
647
    return 0;
648
}
649

    
650
static void qmf_32_subbands(DCAContext * s, int chans,
651
                            float samples_in[32][8], float *samples_out,
652
                            float scale, float bias)
653
{
654
    const float *prCoeff;
655
    int i, j;
656
    DECLARE_ALIGNED_16(float, raXin[32]);
657

    
658
    int hist_index= s->hist_index[chans];
659
    float *subband_fir_hist2 = s->subband_fir_noidea[chans];
660

    
661
    int subindex;
662

    
663
    scale *= sqrt(1/8.0);
664

    
665
    /* Select filter */
666
    if (!s->multirate_inter)    /* Non-perfect reconstruction */
667
        prCoeff = fir_32bands_nonperfect;
668
    else                        /* Perfect reconstruction */
669
        prCoeff = fir_32bands_perfect;
670

    
671
    /* Reconstructed channel sample index */
672
    for (subindex = 0; subindex < 8; subindex++) {
673
        float *subband_fir_hist = s->subband_fir_hist[chans] + hist_index;
674
        /* Load in one sample from each subband and clear inactive subbands */
675
        for (i = 0; i < s->subband_activity[chans]; i++){
676
            if((i-1)&2) raXin[i] = -samples_in[i][subindex];
677
            else        raXin[i] =  samples_in[i][subindex];
678
        }
679
        for (; i < 32; i++)
680
            raXin[i] = 0.0;
681

    
682
        ff_imdct_half(&s->imdct, subband_fir_hist, raXin);
683

    
684
        /* Multiply by filter coefficients */
685
        for (i = 0; i < 16; i++){
686
            float a= subband_fir_hist2[i   ];
687
            float b= subband_fir_hist2[i+16];
688
            float c= 0;
689
            float d= 0;
690
            for (j = 0; j < 512-hist_index; j += 64){
691
                a += prCoeff[i+j   ]*(-subband_fir_hist[15-i+j]);
692
                b += prCoeff[i+j+16]*( subband_fir_hist[   i+j]);
693
                c += prCoeff[i+j+32]*( subband_fir_hist[16+i+j]);
694
                d += prCoeff[i+j+48]*( subband_fir_hist[31-i+j]);
695
            }
696
            for (     ; j < 512; j += 64){
697
                a += prCoeff[i+j   ]*(-subband_fir_hist[15-i+j-512]);
698
                b += prCoeff[i+j+16]*( subband_fir_hist[   i+j-512]);
699
                c += prCoeff[i+j+32]*( subband_fir_hist[16+i+j-512]);
700
                d += prCoeff[i+j+48]*( subband_fir_hist[31-i+j-512]);
701
            }
702
            samples_out[i   ] = a * scale + bias;
703
            samples_out[i+16] = b * scale + bias;
704
            subband_fir_hist2[i   ] = c;
705
            subband_fir_hist2[i+16] = d;
706
        }
707
        samples_out+= 32;
708

    
709
        hist_index = (hist_index-32)&511;
710
    }
711
    s->hist_index[chans]= hist_index;
712
}
713

    
714
static void lfe_interpolation_fir(int decimation_select,
715
                                  int num_deci_sample, float *samples_in,
716
                                  float *samples_out, float scale,
717
                                  float bias)
718
{
719
    /* samples_in: An array holding decimated samples.
720
     *   Samples in current subframe starts from samples_in[0],
721
     *   while samples_in[-1], samples_in[-2], ..., stores samples
722
     *   from last subframe as history.
723
     *
724
     * samples_out: An array holding interpolated samples
725
     */
726

    
727
    int decifactor, k, j;
728
    const float *prCoeff;
729

    
730
    int interp_index = 0;       /* Index to the interpolated samples */
731
    int deciindex;
732

    
733
    /* Select decimation filter */
734
    if (decimation_select == 1) {
735
        decifactor = 128;
736
        prCoeff = lfe_fir_128;
737
    } else {
738
        decifactor = 64;
739
        prCoeff = lfe_fir_64;
740
    }
741
    /* Interpolation */
742
    for (deciindex = 0; deciindex < num_deci_sample; deciindex++) {
743
        /* One decimated sample generates decifactor interpolated ones */
744
        for (k = 0; k < decifactor; k++) {
745
            float rTmp = 0.0;
746
            //FIXME the coeffs are symetric, fix that
747
            for (j = 0; j < 512 / decifactor; j++)
748
                rTmp += samples_in[deciindex - j] * prCoeff[k + j * decifactor];
749
            samples_out[interp_index++] = (rTmp * scale) + bias;
750
        }
751
    }
752
}
753

    
754
/* downmixing routines */
755
#define MIX_REAR1(samples, si1, rs, coef) \
756
     samples[i]     += samples[si1] * coef[rs][0]; \
757
     samples[i+256] += samples[si1] * coef[rs][1];
758

    
759
#define MIX_REAR2(samples, si1, si2, rs, coef) \
760
     samples[i]     += samples[si1] * coef[rs][0] + samples[si2] * coef[rs+1][0]; \
761
     samples[i+256] += samples[si1] * coef[rs][1] + samples[si2] * coef[rs+1][1];
762

    
763
#define MIX_FRONT3(samples, coef) \
764
    t = samples[i]; \
765
    samples[i]     = t * coef[0][0] + samples[i+256] * coef[1][0] + samples[i+512] * coef[2][0]; \
766
    samples[i+256] = t * coef[0][1] + samples[i+256] * coef[1][1] + samples[i+512] * coef[2][1];
767

    
768
#define DOWNMIX_TO_STEREO(op1, op2) \
769
    for(i = 0; i < 256; i++){ \
770
        op1 \
771
        op2 \
772
    }
773

    
774
static void dca_downmix(float *samples, int srcfmt,
775
                        int downmix_coef[DCA_PRIM_CHANNELS_MAX][2])
776
{
777
    int i;
778
    float t;
779
    float coef[DCA_PRIM_CHANNELS_MAX][2];
780

    
781
    for(i=0; i<DCA_PRIM_CHANNELS_MAX; i++) {
782
        coef[i][0] = dca_downmix_coeffs[downmix_coef[i][0]];
783
        coef[i][1] = dca_downmix_coeffs[downmix_coef[i][1]];
784
    }
785

    
786
    switch (srcfmt) {
787
    case DCA_MONO:
788
    case DCA_CHANNEL:
789
    case DCA_STEREO_TOTAL:
790
    case DCA_STEREO_SUMDIFF:
791
    case DCA_4F2R:
792
        av_log(NULL, 0, "Not implemented!\n");
793
        break;
794
    case DCA_STEREO:
795
        break;
796
    case DCA_3F:
797
        DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),);
798
        break;
799
    case DCA_2F1R:
800
        DOWNMIX_TO_STEREO(MIX_REAR1(samples, i + 512, 2, coef),);
801
        break;
802
    case DCA_3F1R:
803
        DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
804
                          MIX_REAR1(samples, i + 768, 3, coef));
805
        break;
806
    case DCA_2F2R:
807
        DOWNMIX_TO_STEREO(MIX_REAR2(samples, i + 512, i + 768, 2, coef),);
808
        break;
809
    case DCA_3F2R:
810
        DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
811
                          MIX_REAR2(samples, i + 768, i + 1024, 3, coef));
812
        break;
813
    }
814
}
815

    
816

    
817
/* Very compact version of the block code decoder that does not use table
818
 * look-up but is slightly slower */
819
static int decode_blockcode(int code, int levels, int *values)
820
{
821
    int i;
822
    int offset = (levels - 1) >> 1;
823

    
824
    for (i = 0; i < 4; i++) {
825
        values[i] = (code % levels) - offset;
826
        code /= levels;
827
    }
828

    
829
    if (code == 0)
830
        return 0;
831
    else {
832
        av_log(NULL, AV_LOG_ERROR, "ERROR: block code look-up failed\n");
833
        return -1;
834
    }
835
}
836

    
837
static const uint8_t abits_sizes[7] = { 7, 10, 12, 13, 15, 17, 19 };
838
static const uint8_t abits_levels[7] = { 3, 5, 7, 9, 13, 17, 25 };
839

    
840
static int dca_subsubframe(DCAContext * s)
841
{
842
    int k, l;
843
    int subsubframe = s->current_subsubframe;
844

    
845
    const float *quant_step_table;
846

    
847
    /* FIXME */
848
    float subband_samples[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][8];
849

    
850
    /*
851
     * Audio data
852
     */
853

    
854
    /* Select quantization step size table */
855
    if (s->bit_rate == 0x1f)
856
        quant_step_table = lossless_quant_d;
857
    else
858
        quant_step_table = lossy_quant_d;
859

    
860
    for (k = 0; k < s->prim_channels; k++) {
861
        for (l = 0; l < s->vq_start_subband[k]; l++) {
862
            int m;
863

    
864
            /* Select the mid-tread linear quantizer */
865
            int abits = s->bitalloc[k][l];
866

    
867
            float quant_step_size = quant_step_table[abits];
868
            float rscale;
869

    
870
            /*
871
             * Determine quantization index code book and its type
872
             */
873

    
874
            /* Select quantization index code book */
875
            int sel = s->quant_index_huffman[k][abits];
876

    
877
            /*
878
             * Extract bits from the bit stream
879
             */
880
            if(!abits){
881
                memset(subband_samples[k][l], 0, 8 * sizeof(subband_samples[0][0][0]));
882
            }else if(abits >= 11 || !dca_smpl_bitalloc[abits].vlc[sel].table){
883
                if(abits <= 7){
884
                    /* Block code */
885
                    int block_code1, block_code2, size, levels;
886
                    int block[8];
887

    
888
                    size = abits_sizes[abits-1];
889
                    levels = abits_levels[abits-1];
890

    
891
                    block_code1 = get_bits(&s->gb, size);
892
                    /* FIXME Should test return value */
893
                    decode_blockcode(block_code1, levels, block);
894
                    block_code2 = get_bits(&s->gb, size);
895
                    decode_blockcode(block_code2, levels, &block[4]);
896
                    for (m = 0; m < 8; m++)
897
                        subband_samples[k][l][m] = block[m];
898
                }else{
899
                    /* no coding */
900
                    for (m = 0; m < 8; m++)
901
                        subband_samples[k][l][m] = get_sbits(&s->gb, abits - 3);
902
                }
903
            }else{
904
                /* Huffman coded */
905
                for (m = 0; m < 8; m++)
906
                    subband_samples[k][l][m] = get_bitalloc(&s->gb, &dca_smpl_bitalloc[abits], sel);
907
            }
908

    
909
            /* Deal with transients */
910
            if (s->transition_mode[k][l] &&
911
                subsubframe >= s->transition_mode[k][l])
912
                rscale = quant_step_size * s->scale_factor[k][l][1];
913
            else
914
                rscale = quant_step_size * s->scale_factor[k][l][0];
915

    
916
            rscale *= s->scalefactor_adj[k][sel];
917

    
918
            for (m = 0; m < 8; m++)
919
                subband_samples[k][l][m] *= rscale;
920

    
921
            /*
922
             * Inverse ADPCM if in prediction mode
923
             */
924
            if (s->prediction_mode[k][l]) {
925
                int n;
926
                for (m = 0; m < 8; m++) {
927
                    for (n = 1; n <= 4; n++)
928
                        if (m >= n)
929
                            subband_samples[k][l][m] +=
930
                                (adpcm_vb[s->prediction_vq[k][l]][n - 1] *
931
                                 subband_samples[k][l][m - n] / 8192);
932
                        else if (s->predictor_history)
933
                            subband_samples[k][l][m] +=
934
                                (adpcm_vb[s->prediction_vq[k][l]][n - 1] *
935
                                 s->subband_samples_hist[k][l][m - n +
936
                                                               4] / 8192);
937
                }
938
            }
939
        }
940

    
941
        /*
942
         * Decode VQ encoded high frequencies
943
         */
944
        for (l = s->vq_start_subband[k]; l < s->subband_activity[k]; l++) {
945
            /* 1 vector -> 32 samples but we only need the 8 samples
946
             * for this subsubframe. */
947
            int m;
948

    
949
            if (!s->debug_flag & 0x01) {
950
                av_log(s->avctx, AV_LOG_DEBUG, "Stream with high frequencies VQ coding\n");
951
                s->debug_flag |= 0x01;
952
            }
953

    
954
            for (m = 0; m < 8; m++) {
955
                subband_samples[k][l][m] =
956
                    high_freq_vq[s->high_freq_vq[k][l]][subsubframe * 8 +
957
                                                        m]
958
                    * (float) s->scale_factor[k][l][0] / 16.0;
959
            }
960
        }
961
    }
962

    
963
    /* Check for DSYNC after subsubframe */
964
    if (s->aspf || subsubframe == s->subsubframes - 1) {
965
        if (0xFFFF == get_bits(&s->gb, 16)) {   /* 0xFFFF */
966
#ifdef TRACE
967
            av_log(s->avctx, AV_LOG_DEBUG, "Got subframe DSYNC\n");
968
#endif
969
        } else {
970
            av_log(s->avctx, AV_LOG_ERROR, "Didn't get subframe DSYNC\n");
971
        }
972
    }
973

    
974
    /* Backup predictor history for adpcm */
975
    for (k = 0; k < s->prim_channels; k++)
976
        for (l = 0; l < s->vq_start_subband[k]; l++)
977
            memcpy(s->subband_samples_hist[k][l], &subband_samples[k][l][4],
978
                        4 * sizeof(subband_samples[0][0][0]));
979

    
980
    /* 32 subbands QMF */
981
    for (k = 0; k < s->prim_channels; k++) {
982
/*        static float pcm_to_double[8] =
983
            {32768.0, 32768.0, 524288.0, 524288.0, 0, 8388608.0, 8388608.0};*/
984
         qmf_32_subbands(s, k, subband_samples[k], &s->samples[256 * k],
985
                            M_SQRT1_2*s->scale_bias /*pcm_to_double[s->source_pcm_res] */ ,
986
                            s->add_bias );
987
    }
988

    
989
    /* Down mixing */
990

    
991
    if (s->prim_channels > dca_channels[s->output & DCA_CHANNEL_MASK]) {
992
        dca_downmix(s->samples, s->amode, s->downmix_coef);
993
    }
994

    
995
    /* Generate LFE samples for this subsubframe FIXME!!! */
996
    if (s->output & DCA_LFE) {
997
        int lfe_samples = 2 * s->lfe * s->subsubframes;
998
        int i_channels = dca_channels[s->output & DCA_CHANNEL_MASK];
999

    
1000
        lfe_interpolation_fir(s->lfe, 2 * s->lfe,
1001
                              s->lfe_data + lfe_samples +
1002
                              2 * s->lfe * subsubframe,
1003
                              &s->samples[256 * i_channels],
1004
                              (1.0/256.0)*s->scale_bias,  s->add_bias);
1005
        /* Outputs 20bits pcm samples */
1006
    }
1007

    
1008
    return 0;
1009
}
1010

    
1011

    
1012
static int dca_subframe_footer(DCAContext * s)
1013
{
1014
    int aux_data_count = 0, i;
1015
    int lfe_samples;
1016

    
1017
    /*
1018
     * Unpack optional information
1019
     */
1020

    
1021
    if (s->timestamp)
1022
        get_bits(&s->gb, 32);
1023

    
1024
    if (s->aux_data)
1025
        aux_data_count = get_bits(&s->gb, 6);
1026

    
1027
    for (i = 0; i < aux_data_count; i++)
1028
        get_bits(&s->gb, 8);
1029

    
1030
    if (s->crc_present && (s->downmix || s->dynrange))
1031
        get_bits(&s->gb, 16);
1032

    
1033
    lfe_samples = 2 * s->lfe * s->subsubframes;
1034
    for (i = 0; i < lfe_samples; i++) {
1035
        s->lfe_data[i] = s->lfe_data[i + lfe_samples];
1036
    }
1037

    
1038
    return 0;
1039
}
1040

    
1041
/**
1042
 * Decode a dca frame block
1043
 *
1044
 * @param s     pointer to the DCAContext
1045
 */
1046

    
1047
static int dca_decode_block(DCAContext * s)
1048
{
1049

    
1050
    /* Sanity check */
1051
    if (s->current_subframe >= s->subframes) {
1052
        av_log(s->avctx, AV_LOG_DEBUG, "check failed: %i>%i",
1053
               s->current_subframe, s->subframes);
1054
        return -1;
1055
    }
1056

    
1057
    if (!s->current_subsubframe) {
1058
#ifdef TRACE
1059
        av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subframe_header\n");
1060
#endif
1061
        /* Read subframe header */
1062
        if (dca_subframe_header(s))
1063
            return -1;
1064
    }
1065

    
1066
    /* Read subsubframe */
1067
#ifdef TRACE
1068
    av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subsubframe\n");
1069
#endif
1070
    if (dca_subsubframe(s))
1071
        return -1;
1072

    
1073
    /* Update state */
1074
    s->current_subsubframe++;
1075
    if (s->current_subsubframe >= s->subsubframes) {
1076
        s->current_subsubframe = 0;
1077
        s->current_subframe++;
1078
    }
1079
    if (s->current_subframe >= s->subframes) {
1080
#ifdef TRACE
1081
        av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subframe_footer\n");
1082
#endif
1083
        /* Read subframe footer */
1084
        if (dca_subframe_footer(s))
1085
            return -1;
1086
    }
1087

    
1088
    return 0;
1089
}
1090

    
1091
/**
1092
 * Convert bitstream to one representation based on sync marker
1093
 */
1094
static int dca_convert_bitstream(const uint8_t * src, int src_size, uint8_t * dst,
1095
                          int max_size)
1096
{
1097
    uint32_t mrk;
1098
    int i, tmp;
1099
    const uint16_t *ssrc = (const uint16_t *) src;
1100
    uint16_t *sdst = (uint16_t *) dst;
1101
    PutBitContext pb;
1102

    
1103
    if((unsigned)src_size > (unsigned)max_size) {
1104
        av_log(NULL, AV_LOG_ERROR, "Input frame size larger then DCA_MAX_FRAME_SIZE!\n");
1105
        return -1;
1106
    }
1107

    
1108
    mrk = AV_RB32(src);
1109
    switch (mrk) {
1110
    case DCA_MARKER_RAW_BE:
1111
        memcpy(dst, src, src_size);
1112
        return src_size;
1113
    case DCA_MARKER_RAW_LE:
1114
        for (i = 0; i < (src_size + 1) >> 1; i++)
1115
            *sdst++ = bswap_16(*ssrc++);
1116
        return src_size;
1117
    case DCA_MARKER_14B_BE:
1118
    case DCA_MARKER_14B_LE:
1119
        init_put_bits(&pb, dst, max_size);
1120
        for (i = 0; i < (src_size + 1) >> 1; i++, src += 2) {
1121
            tmp = ((mrk == DCA_MARKER_14B_BE) ? AV_RB16(src) : AV_RL16(src)) & 0x3FFF;
1122
            put_bits(&pb, 14, tmp);
1123
        }
1124
        flush_put_bits(&pb);
1125
        return (put_bits_count(&pb) + 7) >> 3;
1126
    default:
1127
        return -1;
1128
    }
1129
}
1130

    
1131
/**
1132
 * Main frame decoding function
1133
 * FIXME add arguments
1134
 */
1135
static int dca_decode_frame(AVCodecContext * avctx,
1136
                            void *data, int *data_size,
1137
                            const uint8_t * buf, int buf_size)
1138
{
1139

    
1140
    int i;
1141
    int16_t *samples = data;
1142
    DCAContext *s = avctx->priv_data;
1143
    int channels;
1144

    
1145

    
1146
    s->dca_buffer_size = dca_convert_bitstream(buf, buf_size, s->dca_buffer, DCA_MAX_FRAME_SIZE);
1147
    if (s->dca_buffer_size == -1) {
1148
        av_log(avctx, AV_LOG_ERROR, "Not a valid DCA frame\n");
1149
        return -1;
1150
    }
1151

    
1152
    init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
1153
    if (dca_parse_frame_header(s) < 0) {
1154
        //seems like the frame is corrupt, try with the next one
1155
        *data_size=0;
1156
        return buf_size;
1157
    }
1158
    //set AVCodec values with parsed data
1159
    avctx->sample_rate = s->sample_rate;
1160
    avctx->bit_rate = s->bit_rate;
1161

    
1162
    channels = s->prim_channels + !!s->lfe;
1163
    if(avctx->request_channels == 2 && s->prim_channels > 2) {
1164
        channels = 2;
1165
        s->output = DCA_STEREO;
1166
    }
1167

    
1168
    /* There is nothing that prevents a dts frame to change channel configuration
1169
       but FFmpeg doesn't support that so only set the channels if it is previously
1170
       unset. Ideally during the first probe for channels the crc should be checked
1171
       and only set avctx->channels when the crc is ok. Right now the decoder could
1172
       set the channels based on a broken first frame.*/
1173
    if (!avctx->channels)
1174
        avctx->channels = channels;
1175

    
1176
    if(*data_size < (s->sample_blocks / 8) * 256 * sizeof(int16_t) * channels)
1177
        return -1;
1178
    *data_size = 256 / 8 * s->sample_blocks * sizeof(int16_t) * channels;
1179
    for (i = 0; i < (s->sample_blocks / 8); i++) {
1180
        dca_decode_block(s);
1181
        s->dsp.float_to_int16_interleave(samples, s->samples_chanptr, 256, channels);
1182
        samples += 256 * channels;
1183
    }
1184

    
1185
    return buf_size;
1186
}
1187

    
1188

    
1189

    
1190
/**
1191
 * DCA initialization
1192
 *
1193
 * @param avctx     pointer to the AVCodecContext
1194
 */
1195

    
1196
static av_cold int dca_decode_init(AVCodecContext * avctx)
1197
{
1198
    DCAContext *s = avctx->priv_data;
1199
    int i;
1200

    
1201
    s->avctx = avctx;
1202
    dca_init_vlcs();
1203

    
1204
    dsputil_init(&s->dsp, avctx);
1205
    ff_mdct_init(&s->imdct, 6, 1);
1206

    
1207
    /* allow downmixing to stereo */
1208
    if (avctx->channels > 0 && avctx->request_channels < avctx->channels &&
1209
            avctx->request_channels == 2) {
1210
        avctx->channels = avctx->request_channels;
1211
    }
1212
    for(i = 0; i < 6; i++)
1213
        s->samples_chanptr[i] = s->samples + i * 256;
1214
    avctx->sample_fmt = SAMPLE_FMT_S16;
1215

    
1216
    if(s->dsp.float_to_int16 == ff_float_to_int16_c) {
1217
        s->add_bias = 385.0f;
1218
        s->scale_bias = 1.0 / 32768.0;
1219
    } else {
1220
        s->add_bias = 0.0f;
1221
        s->scale_bias = 1.0;
1222
    }
1223

    
1224

    
1225
    return 0;
1226
}
1227

    
1228
static av_cold int dca_decode_end(AVCodecContext * avctx)
1229
{
1230
    DCAContext *s = avctx->priv_data;
1231
    ff_mdct_end(&s->imdct);
1232
    return 0;
1233
}
1234

    
1235
AVCodec dca_decoder = {
1236
    .name = "dca",
1237
    .type = CODEC_TYPE_AUDIO,
1238
    .id = CODEC_ID_DTS,
1239
    .priv_data_size = sizeof(DCAContext),
1240
    .init = dca_decode_init,
1241
    .decode = dca_decode_frame,
1242
    .close = dca_decode_end,
1243
    .long_name = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
1244
};