Statistics
| Branch: | Revision:

ffmpeg / libavcodec / dca.c @ 84dc2d8a

History | View | Annotate | Download (48.5 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 libavcodec/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 "get_bits.h"
36
#include "put_bits.h"
37
#include "dcadata.h"
38
#include "dcahuff.h"
39
#include "dca.h"
40
#include "synth_filter.h"
41

    
42
//#define TRACE
43

    
44
#define DCA_PRIM_CHANNELS_MAX (5)
45
#define DCA_SUBBANDS (32)
46
#define DCA_ABITS_MAX (32)      /* Should be 28 */
47
#define DCA_SUBSUBFAMES_MAX (4)
48
#define DCA_LFE_MAX (3)
49

    
50
enum DCAMode {
51
    DCA_MONO = 0,
52
    DCA_CHANNEL,
53
    DCA_STEREO,
54
    DCA_STEREO_SUMDIFF,
55
    DCA_STEREO_TOTAL,
56
    DCA_3F,
57
    DCA_2F1R,
58
    DCA_3F1R,
59
    DCA_2F2R,
60
    DCA_3F2R,
61
    DCA_4F2R
62
};
63

    
64
/* Tables for mapping dts channel configurations to libavcodec multichannel api.
65
 * Some compromises have been made for special configurations. Most configurations
66
 * are never used so complete accuracy is not needed.
67
 *
68
 * L = left, R = right, C = center, S = surround, F = front, R = rear, T = total, OV = overhead.
69
 * S  -> side, when both rear and back are configured move one of them to the side channel
70
 * OV -> center back
71
 * All 2 channel configurations -> CH_LAYOUT_STEREO
72
 */
73

    
74
static const int64_t dca_core_channel_layout[] = {
75
    CH_FRONT_CENTER,                                               ///< 1, A
76
    CH_LAYOUT_STEREO,                                              ///< 2, A + B (dual mono)
77
    CH_LAYOUT_STEREO,                                              ///< 2, L + R (stereo)
78
    CH_LAYOUT_STEREO,                                              ///< 2, (L+R) + (L-R) (sum-difference)
79
    CH_LAYOUT_STEREO,                                              ///< 2, LT +RT (left and right total)
80
    CH_LAYOUT_STEREO|CH_FRONT_CENTER,                              ///< 3, C+L+R
81
    CH_LAYOUT_STEREO|CH_BACK_CENTER,                               ///< 3, L+R+S
82
    CH_LAYOUT_STEREO|CH_FRONT_CENTER|CH_BACK_CENTER,               ///< 4, C + L + R+ S
83
    CH_LAYOUT_STEREO|CH_SIDE_LEFT|CH_SIDE_RIGHT,                   ///< 4, L + R +SL+ SR
84
    CH_LAYOUT_STEREO|CH_FRONT_CENTER|CH_SIDE_LEFT|CH_SIDE_RIGHT,   ///< 5, C + L + R+ SL+SR
85
    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
86
    CH_LAYOUT_STEREO|CH_BACK_LEFT|CH_BACK_RIGHT|CH_FRONT_CENTER|CH_BACK_CENTER,                                   ///< 6, C + L + R+ LR + RR + OV
87
    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
88
    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
89
    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
90
    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
91
};
92

    
93
static const int8_t dca_lfe_index[] = {
94
    1,2,2,2,2,3,2,3,2,3,2,3,1,3,2,3
95
};
96

    
97
static const int8_t dca_channel_reorder_lfe[][8] = {
98
    { 0, -1, -1, -1, -1, -1, -1, -1},
99
    { 0,  1, -1, -1, -1, -1, -1, -1},
100
    { 0,  1, -1, -1, -1, -1, -1, -1},
101
    { 0,  1, -1, -1, -1, -1, -1, -1},
102
    { 0,  1, -1, -1, -1, -1, -1, -1},
103
    { 2,  0,  1, -1, -1, -1, -1, -1},
104
    { 0,  1,  3, -1, -1, -1, -1, -1},
105
    { 2,  0,  1,  4, -1, -1, -1, -1},
106
    { 0,  1,  3,  4, -1, -1, -1, -1},
107
    { 2,  0,  1,  4,  5, -1, -1, -1},
108
    { 3,  4,  0,  1,  5,  6, -1, -1},
109
    { 2,  0,  1,  4,  5,  6, -1, -1},
110
    { 0,  6,  4,  5,  2,  3, -1, -1},
111
    { 4,  2,  5,  0,  1,  6,  7, -1},
112
    { 5,  6,  0,  1,  7,  3,  8,  4},
113
    { 4,  2,  5,  0,  1,  6,  8,  7},
114
};
115

    
116
static const int8_t dca_channel_reorder_nolfe[][8] = {
117
    { 0, -1, -1, -1, -1, -1, -1, -1},
118
    { 0,  1, -1, -1, -1, -1, -1, -1},
119
    { 0,  1, -1, -1, -1, -1, -1, -1},
120
    { 0,  1, -1, -1, -1, -1, -1, -1},
121
    { 0,  1, -1, -1, -1, -1, -1, -1},
122
    { 2,  0,  1, -1, -1, -1, -1, -1},
123
    { 0,  1,  2, -1, -1, -1, -1, -1},
124
    { 2,  0,  1,  3, -1, -1, -1, -1},
125
    { 0,  1,  2,  3, -1, -1, -1, -1},
126
    { 2,  0,  1,  3,  4, -1, -1, -1},
127
    { 2,  3,  0,  1,  4,  5, -1, -1},
128
    { 2,  0,  1,  3,  4,  5, -1, -1},
129
    { 0,  5,  3,  4,  1,  2, -1, -1},
130
    { 3,  2,  4,  0,  1,  5,  6, -1},
131
    { 4,  5,  0,  1,  6,  2,  7,  3},
132
    { 3,  2,  4,  0,  1,  5,  7,  6},
133
};
134

    
135

    
136
#define DCA_DOLBY 101           /* FIXME */
137

    
138
#define DCA_CHANNEL_BITS 6
139
#define DCA_CHANNEL_MASK 0x3F
140

    
141
#define DCA_LFE 0x80
142

    
143
#define HEADER_SIZE 14
144

    
145
#define DCA_MAX_FRAME_SIZE 16384
146

    
147
/** Bit allocation */
148
typedef struct {
149
    int offset;                 ///< code values offset
150
    int maxbits[8];             ///< max bits in VLC
151
    int wrap;                   ///< wrap for get_vlc2()
152
    VLC vlc[8];                 ///< actual codes
153
} BitAlloc;
154

    
155
static BitAlloc dca_bitalloc_index;    ///< indexes for samples VLC select
156
static BitAlloc dca_tmode;             ///< transition mode VLCs
157
static BitAlloc dca_scalefactor;       ///< scalefactor VLCs
158
static BitAlloc dca_smpl_bitalloc[11]; ///< samples VLCs
159

    
160
static av_always_inline int get_bitalloc(GetBitContext *gb, BitAlloc *ba, int idx)
161
{
162
    return get_vlc2(gb, ba->vlc[idx].table, ba->vlc[idx].bits, ba->wrap) + ba->offset;
163
}
164

    
165
typedef struct {
166
    AVCodecContext *avctx;
167
    /* Frame header */
168
    int frame_type;             ///< type of the current frame
169
    int samples_deficit;        ///< deficit sample count
170
    int crc_present;            ///< crc is present in the bitstream
171
    int sample_blocks;          ///< number of PCM sample blocks
172
    int frame_size;             ///< primary frame byte size
173
    int amode;                  ///< audio channels arrangement
174
    int sample_rate;            ///< audio sampling rate
175
    int bit_rate;               ///< transmission bit rate
176
    int bit_rate_index;         ///< transmission bit rate index
177

    
178
    int downmix;                ///< embedded downmix enabled
179
    int dynrange;               ///< embedded dynamic range flag
180
    int timestamp;              ///< embedded time stamp flag
181
    int aux_data;               ///< auxiliary data flag
182
    int hdcd;                   ///< source material is mastered in HDCD
183
    int ext_descr;              ///< extension audio descriptor flag
184
    int ext_coding;             ///< extended coding flag
185
    int aspf;                   ///< audio sync word insertion flag
186
    int lfe;                    ///< low frequency effects flag
187
    int predictor_history;      ///< predictor history flag
188
    int header_crc;             ///< header crc check bytes
189
    int multirate_inter;        ///< multirate interpolator switch
190
    int version;                ///< encoder software revision
191
    int copy_history;           ///< copy history
192
    int source_pcm_res;         ///< source pcm resolution
193
    int front_sum;              ///< front sum/difference flag
194
    int surround_sum;           ///< surround sum/difference flag
195
    int dialog_norm;            ///< dialog normalisation parameter
196

    
197
    /* Primary audio coding header */
198
    int subframes;              ///< number of subframes
199
    int total_channels;         ///< number of channels including extensions
200
    int prim_channels;          ///< number of primary audio channels
201
    int subband_activity[DCA_PRIM_CHANNELS_MAX];    ///< subband activity count
202
    int vq_start_subband[DCA_PRIM_CHANNELS_MAX];    ///< high frequency vq start subband
203
    int joint_intensity[DCA_PRIM_CHANNELS_MAX];     ///< joint intensity coding index
204
    int transient_huffman[DCA_PRIM_CHANNELS_MAX];   ///< transient mode code book
205
    int scalefactor_huffman[DCA_PRIM_CHANNELS_MAX]; ///< scale factor code book
206
    int bitalloc_huffman[DCA_PRIM_CHANNELS_MAX];    ///< bit allocation quantizer select
207
    int quant_index_huffman[DCA_PRIM_CHANNELS_MAX][DCA_ABITS_MAX]; ///< quantization index codebook select
208
    float scalefactor_adj[DCA_PRIM_CHANNELS_MAX][DCA_ABITS_MAX];   ///< scale factor adjustment
209

    
210
    /* Primary audio coding side information */
211
    int subsubframes;           ///< number of subsubframes
212
    int partial_samples;        ///< partial subsubframe samples count
213
    int prediction_mode[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];    ///< prediction mode (ADPCM used or not)
214
    int prediction_vq[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];      ///< prediction VQ coefs
215
    int bitalloc[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];           ///< bit allocation index
216
    int transition_mode[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];    ///< transition mode (transients)
217
    int scale_factor[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][2];    ///< scale factors (2 if transient)
218
    int joint_huff[DCA_PRIM_CHANNELS_MAX];                       ///< joint subband scale factors codebook
219
    int joint_scale_factor[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS]; ///< joint subband scale factors
220
    int downmix_coef[DCA_PRIM_CHANNELS_MAX][2];                  ///< stereo downmix coefficients
221
    int dynrange_coef;                                           ///< dynamic range coefficient
222

    
223
    int high_freq_vq[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];       ///< VQ encoded high frequency subbands
224

    
225
    float lfe_data[2 * DCA_SUBSUBFAMES_MAX * DCA_LFE_MAX *
226
                   2 /*history */ ];    ///< Low frequency effect data
227
    int lfe_scale_factor;
228

    
229
    /* Subband samples history (for ADPCM) */
230
    float subband_samples_hist[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][4];
231
    DECLARE_ALIGNED(16, float, subband_fir_hist)[DCA_PRIM_CHANNELS_MAX][512];
232
    float subband_fir_noidea[DCA_PRIM_CHANNELS_MAX][32];
233
    int hist_index[DCA_PRIM_CHANNELS_MAX];
234
    DECLARE_ALIGNED(16, float, raXin)[32];
235

    
236
    int output;                 ///< type of output
237
    float add_bias;             ///< output bias
238
    float scale_bias;           ///< output scale
239

    
240
    DECLARE_ALIGNED(16, float, samples)[1536];  /* 6 * 256 = 1536, might only need 5 */
241
    const float *samples_chanptr[6];
242

    
243
    uint8_t dca_buffer[DCA_MAX_FRAME_SIZE];
244
    int dca_buffer_size;        ///< how much data is in the dca_buffer
245

    
246
    const int8_t* channel_order_tab;                             ///< channel reordering table, lfe and non lfe
247
    GetBitContext gb;
248
    /* Current position in DCA frame */
249
    int current_subframe;
250
    int current_subsubframe;
251

    
252
    int debug_flag;             ///< used for suppressing repeated error messages output
253
    DSPContext dsp;
254
    FFTContext imdct;
255
} DCAContext;
256

    
257
static const uint16_t dca_vlc_offs[] = {
258
        0,   512,   640,   768,  1282,  1794,  2436,  3080,  3770,  4454,  5364,
259
     5372,  5380,  5388,  5392,  5396,  5412,  5420,  5428,  5460,  5492,  5508,
260
     5572,  5604,  5668,  5796,  5860,  5892,  6412,  6668,  6796,  7308,  7564,
261
     7820,  8076,  8620,  9132,  9388,  9910, 10166, 10680, 11196, 11726, 12240,
262
    12752, 13298, 13810, 14326, 14840, 15500, 16022, 16540, 17158, 17678, 18264,
263
    18796, 19352, 19926, 20468, 21472, 22398, 23014, 23622,
264
};
265

    
266
static av_cold void dca_init_vlcs(void)
267
{
268
    static int vlcs_initialized = 0;
269
    int i, j, c = 14;
270
    static VLC_TYPE dca_table[23622][2];
271

    
272
    if (vlcs_initialized)
273
        return;
274

    
275
    dca_bitalloc_index.offset = 1;
276
    dca_bitalloc_index.wrap = 2;
277
    for (i = 0; i < 5; i++) {
278
        dca_bitalloc_index.vlc[i].table = &dca_table[dca_vlc_offs[i]];
279
        dca_bitalloc_index.vlc[i].table_allocated = dca_vlc_offs[i + 1] - dca_vlc_offs[i];
280
        init_vlc(&dca_bitalloc_index.vlc[i], bitalloc_12_vlc_bits[i], 12,
281
                 bitalloc_12_bits[i], 1, 1,
282
                 bitalloc_12_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
283
    }
284
    dca_scalefactor.offset = -64;
285
    dca_scalefactor.wrap = 2;
286
    for (i = 0; i < 5; i++) {
287
        dca_scalefactor.vlc[i].table = &dca_table[dca_vlc_offs[i + 5]];
288
        dca_scalefactor.vlc[i].table_allocated = dca_vlc_offs[i + 6] - dca_vlc_offs[i + 5];
289
        init_vlc(&dca_scalefactor.vlc[i], SCALES_VLC_BITS, 129,
290
                 scales_bits[i], 1, 1,
291
                 scales_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
292
    }
293
    dca_tmode.offset = 0;
294
    dca_tmode.wrap = 1;
295
    for (i = 0; i < 4; i++) {
296
        dca_tmode.vlc[i].table = &dca_table[dca_vlc_offs[i + 10]];
297
        dca_tmode.vlc[i].table_allocated = dca_vlc_offs[i + 11] - dca_vlc_offs[i + 10];
298
        init_vlc(&dca_tmode.vlc[i], tmode_vlc_bits[i], 4,
299
                 tmode_bits[i], 1, 1,
300
                 tmode_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
301
    }
302

    
303
    for(i = 0; i < 10; i++)
304
        for(j = 0; j < 7; j++){
305
            if(!bitalloc_codes[i][j]) break;
306
            dca_smpl_bitalloc[i+1].offset = bitalloc_offsets[i];
307
            dca_smpl_bitalloc[i+1].wrap = 1 + (j > 4);
308
            dca_smpl_bitalloc[i+1].vlc[j].table = &dca_table[dca_vlc_offs[c]];
309
            dca_smpl_bitalloc[i+1].vlc[j].table_allocated = dca_vlc_offs[c + 1] - dca_vlc_offs[c];
310
            init_vlc(&dca_smpl_bitalloc[i+1].vlc[j], bitalloc_maxbits[i][j],
311
                     bitalloc_sizes[i],
312
                     bitalloc_bits[i][j], 1, 1,
313
                     bitalloc_codes[i][j], 2, 2, INIT_VLC_USE_NEW_STATIC);
314
            c++;
315
        }
316
    vlcs_initialized = 1;
317
}
318

    
319
static inline void get_array(GetBitContext *gb, int *dst, int len, int bits)
320
{
321
    while(len--)
322
        *dst++ = get_bits(gb, bits);
323
}
324

    
325
static int dca_parse_frame_header(DCAContext * s)
326
{
327
    int i, j;
328
    static const float adj_table[4] = { 1.0, 1.1250, 1.2500, 1.4375 };
329
    static const int bitlen[11] = { 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3 };
330
    static const int thr[11] = { 0, 1, 3, 3, 3, 3, 7, 7, 7, 7, 7 };
331

    
332
    init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
333

    
334
    /* Sync code */
335
    get_bits(&s->gb, 32);
336

    
337
    /* Frame header */
338
    s->frame_type        = get_bits(&s->gb, 1);
339
    s->samples_deficit   = get_bits(&s->gb, 5) + 1;
340
    s->crc_present       = get_bits(&s->gb, 1);
341
    s->sample_blocks     = get_bits(&s->gb, 7) + 1;
342
    s->frame_size        = get_bits(&s->gb, 14) + 1;
343
    if (s->frame_size < 95)
344
        return -1;
345
    s->amode             = get_bits(&s->gb, 6);
346
    s->sample_rate       = dca_sample_rates[get_bits(&s->gb, 4)];
347
    if (!s->sample_rate)
348
        return -1;
349
    s->bit_rate_index    = get_bits(&s->gb, 5);
350
    s->bit_rate          = dca_bit_rates[s->bit_rate_index];
351
    if (!s->bit_rate)
352
        return -1;
353

    
354
    s->downmix           = get_bits(&s->gb, 1);
355
    s->dynrange          = get_bits(&s->gb, 1);
356
    s->timestamp         = get_bits(&s->gb, 1);
357
    s->aux_data          = get_bits(&s->gb, 1);
358
    s->hdcd              = get_bits(&s->gb, 1);
359
    s->ext_descr         = get_bits(&s->gb, 3);
360
    s->ext_coding        = get_bits(&s->gb, 1);
361
    s->aspf              = get_bits(&s->gb, 1);
362
    s->lfe               = get_bits(&s->gb, 2);
363
    s->predictor_history = get_bits(&s->gb, 1);
364

    
365
    /* TODO: check CRC */
366
    if (s->crc_present)
367
        s->header_crc    = get_bits(&s->gb, 16);
368

    
369
    s->multirate_inter   = get_bits(&s->gb, 1);
370
    s->version           = get_bits(&s->gb, 4);
371
    s->copy_history      = get_bits(&s->gb, 2);
372
    s->source_pcm_res    = get_bits(&s->gb, 3);
373
    s->front_sum         = get_bits(&s->gb, 1);
374
    s->surround_sum      = get_bits(&s->gb, 1);
375
    s->dialog_norm       = get_bits(&s->gb, 4);
376

    
377
    /* FIXME: channels mixing levels */
378
    s->output = s->amode;
379
    if(s->lfe) s->output |= DCA_LFE;
380

    
381
#ifdef TRACE
382
    av_log(s->avctx, AV_LOG_DEBUG, "frame type: %i\n", s->frame_type);
383
    av_log(s->avctx, AV_LOG_DEBUG, "samples deficit: %i\n", s->samples_deficit);
384
    av_log(s->avctx, AV_LOG_DEBUG, "crc present: %i\n", s->crc_present);
385
    av_log(s->avctx, AV_LOG_DEBUG, "sample blocks: %i (%i samples)\n",
386
           s->sample_blocks, s->sample_blocks * 32);
387
    av_log(s->avctx, AV_LOG_DEBUG, "frame size: %i bytes\n", s->frame_size);
388
    av_log(s->avctx, AV_LOG_DEBUG, "amode: %i (%i channels)\n",
389
           s->amode, dca_channels[s->amode]);
390
    av_log(s->avctx, AV_LOG_DEBUG, "sample rate: %i Hz\n",
391
           s->sample_rate);
392
    av_log(s->avctx, AV_LOG_DEBUG, "bit rate: %i bits/s\n",
393
           s->bit_rate);
394
    av_log(s->avctx, AV_LOG_DEBUG, "downmix: %i\n", s->downmix);
395
    av_log(s->avctx, AV_LOG_DEBUG, "dynrange: %i\n", s->dynrange);
396
    av_log(s->avctx, AV_LOG_DEBUG, "timestamp: %i\n", s->timestamp);
397
    av_log(s->avctx, AV_LOG_DEBUG, "aux_data: %i\n", s->aux_data);
398
    av_log(s->avctx, AV_LOG_DEBUG, "hdcd: %i\n", s->hdcd);
399
    av_log(s->avctx, AV_LOG_DEBUG, "ext descr: %i\n", s->ext_descr);
400
    av_log(s->avctx, AV_LOG_DEBUG, "ext coding: %i\n", s->ext_coding);
401
    av_log(s->avctx, AV_LOG_DEBUG, "aspf: %i\n", s->aspf);
402
    av_log(s->avctx, AV_LOG_DEBUG, "lfe: %i\n", s->lfe);
403
    av_log(s->avctx, AV_LOG_DEBUG, "predictor history: %i\n",
404
           s->predictor_history);
405
    av_log(s->avctx, AV_LOG_DEBUG, "header crc: %i\n", s->header_crc);
406
    av_log(s->avctx, AV_LOG_DEBUG, "multirate inter: %i\n",
407
           s->multirate_inter);
408
    av_log(s->avctx, AV_LOG_DEBUG, "version number: %i\n", s->version);
409
    av_log(s->avctx, AV_LOG_DEBUG, "copy history: %i\n", s->copy_history);
410
    av_log(s->avctx, AV_LOG_DEBUG,
411
           "source pcm resolution: %i (%i bits/sample)\n",
412
           s->source_pcm_res, dca_bits_per_sample[s->source_pcm_res]);
413
    av_log(s->avctx, AV_LOG_DEBUG, "front sum: %i\n", s->front_sum);
414
    av_log(s->avctx, AV_LOG_DEBUG, "surround sum: %i\n", s->surround_sum);
415
    av_log(s->avctx, AV_LOG_DEBUG, "dialog norm: %i\n", s->dialog_norm);
416
    av_log(s->avctx, AV_LOG_DEBUG, "\n");
417
#endif
418

    
419
    /* Primary audio coding header */
420
    s->subframes         = get_bits(&s->gb, 4) + 1;
421
    s->total_channels    = get_bits(&s->gb, 3) + 1;
422
    s->prim_channels     = s->total_channels;
423
    if (s->prim_channels > DCA_PRIM_CHANNELS_MAX)
424
        s->prim_channels = DCA_PRIM_CHANNELS_MAX;   /* We only support DTS core */
425

    
426

    
427
    for (i = 0; i < s->prim_channels; i++) {
428
        s->subband_activity[i] = get_bits(&s->gb, 5) + 2;
429
        if (s->subband_activity[i] > DCA_SUBBANDS)
430
            s->subband_activity[i] = DCA_SUBBANDS;
431
    }
432
    for (i = 0; i < s->prim_channels; i++) {
433
        s->vq_start_subband[i] = get_bits(&s->gb, 5) + 1;
434
        if (s->vq_start_subband[i] > DCA_SUBBANDS)
435
            s->vq_start_subband[i] = DCA_SUBBANDS;
436
    }
437
    get_array(&s->gb, s->joint_intensity,     s->prim_channels, 3);
438
    get_array(&s->gb, s->transient_huffman,   s->prim_channels, 2);
439
    get_array(&s->gb, s->scalefactor_huffman, s->prim_channels, 3);
440
    get_array(&s->gb, s->bitalloc_huffman,    s->prim_channels, 3);
441

    
442
    /* Get codebooks quantization indexes */
443
    memset(s->quant_index_huffman, 0, sizeof(s->quant_index_huffman));
444
    for (j = 1; j < 11; j++)
445
        for (i = 0; i < s->prim_channels; i++)
446
            s->quant_index_huffman[i][j] = get_bits(&s->gb, bitlen[j]);
447

    
448
    /* Get scale factor adjustment */
449
    for (j = 0; j < 11; j++)
450
        for (i = 0; i < s->prim_channels; i++)
451
            s->scalefactor_adj[i][j] = 1;
452

    
453
    for (j = 1; j < 11; j++)
454
        for (i = 0; i < s->prim_channels; i++)
455
            if (s->quant_index_huffman[i][j] < thr[j])
456
                s->scalefactor_adj[i][j] = adj_table[get_bits(&s->gb, 2)];
457

    
458
    if (s->crc_present) {
459
        /* Audio header CRC check */
460
        get_bits(&s->gb, 16);
461
    }
462

    
463
    s->current_subframe = 0;
464
    s->current_subsubframe = 0;
465

    
466
#ifdef TRACE
467
    av_log(s->avctx, AV_LOG_DEBUG, "subframes: %i\n", s->subframes);
468
    av_log(s->avctx, AV_LOG_DEBUG, "prim channels: %i\n", s->prim_channels);
469
    for(i = 0; i < s->prim_channels; i++){
470
        av_log(s->avctx, AV_LOG_DEBUG, "subband activity: %i\n", s->subband_activity[i]);
471
        av_log(s->avctx, AV_LOG_DEBUG, "vq start subband: %i\n", s->vq_start_subband[i]);
472
        av_log(s->avctx, AV_LOG_DEBUG, "joint intensity: %i\n", s->joint_intensity[i]);
473
        av_log(s->avctx, AV_LOG_DEBUG, "transient mode codebook: %i\n", s->transient_huffman[i]);
474
        av_log(s->avctx, AV_LOG_DEBUG, "scale factor codebook: %i\n", s->scalefactor_huffman[i]);
475
        av_log(s->avctx, AV_LOG_DEBUG, "bit allocation quantizer: %i\n", s->bitalloc_huffman[i]);
476
        av_log(s->avctx, AV_LOG_DEBUG, "quant index huff:");
477
        for (j = 0; j < 11; j++)
478
            av_log(s->avctx, AV_LOG_DEBUG, " %i",
479
                   s->quant_index_huffman[i][j]);
480
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
481
        av_log(s->avctx, AV_LOG_DEBUG, "scalefac adj:");
482
        for (j = 0; j < 11; j++)
483
            av_log(s->avctx, AV_LOG_DEBUG, " %1.3f", s->scalefactor_adj[i][j]);
484
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
485
    }
486
#endif
487

    
488
    return 0;
489
}
490

    
491

    
492
static inline int get_scale(GetBitContext *gb, int level, int value)
493
{
494
   if (level < 5) {
495
       /* huffman encoded */
496
       value += get_bitalloc(gb, &dca_scalefactor, level);
497
   } else if(level < 8)
498
       value = get_bits(gb, level + 1);
499
   return value;
500
}
501

    
502
static int dca_subframe_header(DCAContext * s)
503
{
504
    /* Primary audio coding side information */
505
    int j, k;
506

    
507
    s->subsubframes = get_bits(&s->gb, 2) + 1;
508
    s->partial_samples = get_bits(&s->gb, 3);
509
    for (j = 0; j < s->prim_channels; j++) {
510
        for (k = 0; k < s->subband_activity[j]; k++)
511
            s->prediction_mode[j][k] = get_bits(&s->gb, 1);
512
    }
513

    
514
    /* Get prediction codebook */
515
    for (j = 0; j < s->prim_channels; j++) {
516
        for (k = 0; k < s->subband_activity[j]; k++) {
517
            if (s->prediction_mode[j][k] > 0) {
518
                /* (Prediction coefficient VQ address) */
519
                s->prediction_vq[j][k] = get_bits(&s->gb, 12);
520
            }
521
        }
522
    }
523

    
524
    /* Bit allocation index */
525
    for (j = 0; j < s->prim_channels; j++) {
526
        for (k = 0; k < s->vq_start_subband[j]; k++) {
527
            if (s->bitalloc_huffman[j] == 6)
528
                s->bitalloc[j][k] = get_bits(&s->gb, 5);
529
            else if (s->bitalloc_huffman[j] == 5)
530
                s->bitalloc[j][k] = get_bits(&s->gb, 4);
531
            else if (s->bitalloc_huffman[j] == 7) {
532
                av_log(s->avctx, AV_LOG_ERROR,
533
                       "Invalid bit allocation index\n");
534
                return -1;
535
            } else {
536
                s->bitalloc[j][k] =
537
                    get_bitalloc(&s->gb, &dca_bitalloc_index, s->bitalloc_huffman[j]);
538
            }
539

    
540
            if (s->bitalloc[j][k] > 26) {
541
//                 av_log(s->avctx,AV_LOG_DEBUG,"bitalloc index [%i][%i] too big (%i)\n",
542
//                          j, k, s->bitalloc[j][k]);
543
                return -1;
544
            }
545
        }
546
    }
547

    
548
    /* Transition mode */
549
    for (j = 0; j < s->prim_channels; j++) {
550
        for (k = 0; k < s->subband_activity[j]; k++) {
551
            s->transition_mode[j][k] = 0;
552
            if (s->subsubframes > 1 &&
553
                k < s->vq_start_subband[j] && s->bitalloc[j][k] > 0) {
554
                s->transition_mode[j][k] =
555
                    get_bitalloc(&s->gb, &dca_tmode, s->transient_huffman[j]);
556
            }
557
        }
558
    }
559

    
560
    for (j = 0; j < s->prim_channels; j++) {
561
        const uint32_t *scale_table;
562
        int scale_sum;
563

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

    
566
        if (s->scalefactor_huffman[j] == 6)
567
            scale_table = scale_factor_quant7;
568
        else
569
            scale_table = scale_factor_quant6;
570

    
571
        /* When huffman coded, only the difference is encoded */
572
        scale_sum = 0;
573

    
574
        for (k = 0; k < s->subband_activity[j]; k++) {
575
            if (k >= s->vq_start_subband[j] || s->bitalloc[j][k] > 0) {
576
                scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum);
577
                s->scale_factor[j][k][0] = scale_table[scale_sum];
578
            }
579

    
580
            if (k < s->vq_start_subband[j] && s->transition_mode[j][k]) {
581
                /* Get second scale factor */
582
                scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum);
583
                s->scale_factor[j][k][1] = scale_table[scale_sum];
584
            }
585
        }
586
    }
587

    
588
    /* Joint subband scale factor codebook select */
589
    for (j = 0; j < s->prim_channels; j++) {
590
        /* Transmitted only if joint subband coding enabled */
591
        if (s->joint_intensity[j] > 0)
592
            s->joint_huff[j] = get_bits(&s->gb, 3);
593
    }
594

    
595
    /* Scale factors for joint subband coding */
596
    for (j = 0; j < s->prim_channels; j++) {
597
        int source_channel;
598

    
599
        /* Transmitted only if joint subband coding enabled */
600
        if (s->joint_intensity[j] > 0) {
601
            int scale = 0;
602
            source_channel = s->joint_intensity[j] - 1;
603

    
604
            /* When huffman coded, only the difference is encoded
605
             * (is this valid as well for joint scales ???) */
606

    
607
            for (k = s->subband_activity[j]; k < s->subband_activity[source_channel]; k++) {
608
                scale = get_scale(&s->gb, s->joint_huff[j], 0);
609
                scale += 64;    /* bias */
610
                s->joint_scale_factor[j][k] = scale;    /*joint_scale_table[scale]; */
611
            }
612

    
613
            if (!(s->debug_flag & 0x02)) {
614
                av_log(s->avctx, AV_LOG_DEBUG,
615
                       "Joint stereo coding not supported\n");
616
                s->debug_flag |= 0x02;
617
            }
618
        }
619
    }
620

    
621
    /* Stereo downmix coefficients */
622
    if (s->prim_channels > 2) {
623
        if(s->downmix) {
624
            for (j = 0; j < s->prim_channels; j++) {
625
                s->downmix_coef[j][0] = get_bits(&s->gb, 7);
626
                s->downmix_coef[j][1] = get_bits(&s->gb, 7);
627
            }
628
        } else {
629
            int am = s->amode & DCA_CHANNEL_MASK;
630
            for (j = 0; j < s->prim_channels; j++) {
631
                s->downmix_coef[j][0] = dca_default_coeffs[am][j][0];
632
                s->downmix_coef[j][1] = dca_default_coeffs[am][j][1];
633
            }
634
        }
635
    }
636

    
637
    /* Dynamic range coefficient */
638
    if (s->dynrange)
639
        s->dynrange_coef = get_bits(&s->gb, 8);
640

    
641
    /* Side information CRC check word */
642
    if (s->crc_present) {
643
        get_bits(&s->gb, 16);
644
    }
645

    
646
    /*
647
     * Primary audio data arrays
648
     */
649

    
650
    /* VQ encoded high frequency subbands */
651
    for (j = 0; j < s->prim_channels; j++)
652
        for (k = s->vq_start_subband[j]; k < s->subband_activity[j]; k++)
653
            /* 1 vector -> 32 samples */
654
            s->high_freq_vq[j][k] = get_bits(&s->gb, 10);
655

    
656
    /* Low frequency effect data */
657
    if (s->lfe) {
658
        /* LFE samples */
659
        int lfe_samples = 2 * s->lfe * s->subsubframes;
660
        float lfe_scale;
661

    
662
        for (j = lfe_samples; j < lfe_samples * 2; j++) {
663
            /* Signed 8 bits int */
664
            s->lfe_data[j] = get_sbits(&s->gb, 8);
665
        }
666

    
667
        /* Scale factor index */
668
        s->lfe_scale_factor = scale_factor_quant7[get_bits(&s->gb, 8)];
669

    
670
        /* Quantization step size * scale factor */
671
        lfe_scale = 0.035 * s->lfe_scale_factor;
672

    
673
        for (j = lfe_samples; j < lfe_samples * 2; j++)
674
            s->lfe_data[j] *= lfe_scale;
675
    }
676

    
677
#ifdef TRACE
678
    av_log(s->avctx, AV_LOG_DEBUG, "subsubframes: %i\n", s->subsubframes);
679
    av_log(s->avctx, AV_LOG_DEBUG, "partial samples: %i\n",
680
           s->partial_samples);
681
    for (j = 0; j < s->prim_channels; j++) {
682
        av_log(s->avctx, AV_LOG_DEBUG, "prediction mode:");
683
        for (k = 0; k < s->subband_activity[j]; k++)
684
            av_log(s->avctx, AV_LOG_DEBUG, " %i", s->prediction_mode[j][k]);
685
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
686
    }
687
    for (j = 0; j < s->prim_channels; j++) {
688
        for (k = 0; k < s->subband_activity[j]; k++)
689
                av_log(s->avctx, AV_LOG_DEBUG,
690
                       "prediction coefs: %f, %f, %f, %f\n",
691
                       (float) adpcm_vb[s->prediction_vq[j][k]][0] / 8192,
692
                       (float) adpcm_vb[s->prediction_vq[j][k]][1] / 8192,
693
                       (float) adpcm_vb[s->prediction_vq[j][k]][2] / 8192,
694
                       (float) adpcm_vb[s->prediction_vq[j][k]][3] / 8192);
695
    }
696
    for (j = 0; j < s->prim_channels; j++) {
697
        av_log(s->avctx, AV_LOG_DEBUG, "bitalloc index: ");
698
        for (k = 0; k < s->vq_start_subband[j]; k++)
699
            av_log(s->avctx, AV_LOG_DEBUG, "%2.2i ", s->bitalloc[j][k]);
700
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
701
    }
702
    for (j = 0; j < s->prim_channels; j++) {
703
        av_log(s->avctx, AV_LOG_DEBUG, "Transition mode:");
704
        for (k = 0; k < s->subband_activity[j]; k++)
705
            av_log(s->avctx, AV_LOG_DEBUG, " %i", s->transition_mode[j][k]);
706
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
707
    }
708
    for (j = 0; j < s->prim_channels; j++) {
709
        av_log(s->avctx, AV_LOG_DEBUG, "Scale factor:");
710
        for (k = 0; k < s->subband_activity[j]; k++) {
711
            if (k >= s->vq_start_subband[j] || s->bitalloc[j][k] > 0)
712
                av_log(s->avctx, AV_LOG_DEBUG, " %i", s->scale_factor[j][k][0]);
713
            if (k < s->vq_start_subband[j] && s->transition_mode[j][k])
714
                av_log(s->avctx, AV_LOG_DEBUG, " %i(t)", s->scale_factor[j][k][1]);
715
        }
716
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
717
    }
718
    for (j = 0; j < s->prim_channels; j++) {
719
        if (s->joint_intensity[j] > 0) {
720
            int source_channel = s->joint_intensity[j] - 1;
721
            av_log(s->avctx, AV_LOG_DEBUG, "Joint scale factor index:\n");
722
            for (k = s->subband_activity[j]; k < s->subband_activity[source_channel]; k++)
723
                av_log(s->avctx, AV_LOG_DEBUG, " %i", s->joint_scale_factor[j][k]);
724
            av_log(s->avctx, AV_LOG_DEBUG, "\n");
725
        }
726
    }
727
    if (s->prim_channels > 2 && s->downmix) {
728
        av_log(s->avctx, AV_LOG_DEBUG, "Downmix coeffs:\n");
729
        for (j = 0; j < s->prim_channels; j++) {
730
            av_log(s->avctx, AV_LOG_DEBUG, "Channel 0,%d = %f\n", j, dca_downmix_coeffs[s->downmix_coef[j][0]]);
731
            av_log(s->avctx, AV_LOG_DEBUG, "Channel 1,%d = %f\n", j, dca_downmix_coeffs[s->downmix_coef[j][1]]);
732
        }
733
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
734
    }
735
    for (j = 0; j < s->prim_channels; j++)
736
        for (k = s->vq_start_subband[j]; k < s->subband_activity[j]; k++)
737
            av_log(s->avctx, AV_LOG_DEBUG, "VQ index: %i\n", s->high_freq_vq[j][k]);
738
    if(s->lfe){
739
        int lfe_samples = 2 * s->lfe * s->subsubframes;
740
        av_log(s->avctx, AV_LOG_DEBUG, "LFE samples:\n");
741
        for (j = lfe_samples; j < lfe_samples * 2; j++)
742
            av_log(s->avctx, AV_LOG_DEBUG, " %f", s->lfe_data[j]);
743
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
744
    }
745
#endif
746

    
747
    return 0;
748
}
749

    
750
static void qmf_32_subbands(DCAContext * s, int chans,
751
                            float samples_in[32][8], float *samples_out,
752
                            float scale, float bias)
753
{
754
    const float *prCoeff;
755
    int i;
756

    
757
    int subindex;
758

    
759
    scale *= sqrt(1/8.0);
760

    
761
    /* Select filter */
762
    if (!s->multirate_inter)    /* Non-perfect reconstruction */
763
        prCoeff = fir_32bands_nonperfect;
764
    else                        /* Perfect reconstruction */
765
        prCoeff = fir_32bands_perfect;
766

    
767
    /* Reconstructed channel sample index */
768
    for (subindex = 0; subindex < 8; subindex++) {
769
        /* Load in one sample from each subband and clear inactive subbands */
770
        for (i = 0; i < s->subband_activity[chans]; i++){
771
            if((i-1)&2) s->raXin[i] = -samples_in[i][subindex];
772
            else        s->raXin[i] =  samples_in[i][subindex];
773
        }
774
        for (; i < 32; i++)
775
            s->raXin[i] = 0.0;
776

    
777
        ff_synth_filter_float(&s->imdct,
778
                              s->subband_fir_hist[chans], &s->hist_index[chans],
779
                              s->subband_fir_noidea[chans], prCoeff,
780
                              samples_out, s->raXin, scale, bias);
781
        samples_out+= 32;
782

    
783
    }
784
}
785

    
786
static void lfe_interpolation_fir(int decimation_select,
787
                                  int num_deci_sample, float *samples_in,
788
                                  float *samples_out, float scale,
789
                                  float bias)
790
{
791
    /* samples_in: An array holding decimated samples.
792
     *   Samples in current subframe starts from samples_in[0],
793
     *   while samples_in[-1], samples_in[-2], ..., stores samples
794
     *   from last subframe as history.
795
     *
796
     * samples_out: An array holding interpolated samples
797
     */
798

    
799
    int decifactor, k, j;
800
    const float *prCoeff;
801

    
802
    int interp_index = 0;       /* Index to the interpolated samples */
803
    int deciindex;
804

    
805
    /* Select decimation filter */
806
    if (decimation_select == 1) {
807
        decifactor = 128;
808
        prCoeff = lfe_fir_128;
809
    } else {
810
        decifactor = 64;
811
        prCoeff = lfe_fir_64;
812
    }
813
    /* Interpolation */
814
    for (deciindex = 0; deciindex < num_deci_sample; deciindex++) {
815
        /* One decimated sample generates decifactor interpolated ones */
816
        for (k = 0; k < decifactor; k++) {
817
            float rTmp = 0.0;
818
            //FIXME the coeffs are symetric, fix that
819
            for (j = 0; j < 512 / decifactor; j++)
820
                rTmp += samples_in[deciindex - j] * prCoeff[k + j * decifactor];
821
            samples_out[interp_index++] = (rTmp * scale) + bias;
822
        }
823
    }
824
}
825

    
826
/* downmixing routines */
827
#define MIX_REAR1(samples, si1, rs, coef) \
828
     samples[i]     += samples[si1] * coef[rs][0]; \
829
     samples[i+256] += samples[si1] * coef[rs][1];
830

    
831
#define MIX_REAR2(samples, si1, si2, rs, coef) \
832
     samples[i]     += samples[si1] * coef[rs][0] + samples[si2] * coef[rs+1][0]; \
833
     samples[i+256] += samples[si1] * coef[rs][1] + samples[si2] * coef[rs+1][1];
834

    
835
#define MIX_FRONT3(samples, coef) \
836
    t = samples[i]; \
837
    samples[i]     = t * coef[0][0] + samples[i+256] * coef[1][0] + samples[i+512] * coef[2][0]; \
838
    samples[i+256] = t * coef[0][1] + samples[i+256] * coef[1][1] + samples[i+512] * coef[2][1];
839

    
840
#define DOWNMIX_TO_STEREO(op1, op2) \
841
    for(i = 0; i < 256; i++){ \
842
        op1 \
843
        op2 \
844
    }
845

    
846
static void dca_downmix(float *samples, int srcfmt,
847
                        int downmix_coef[DCA_PRIM_CHANNELS_MAX][2])
848
{
849
    int i;
850
    float t;
851
    float coef[DCA_PRIM_CHANNELS_MAX][2];
852

    
853
    for(i=0; i<DCA_PRIM_CHANNELS_MAX; i++) {
854
        coef[i][0] = dca_downmix_coeffs[downmix_coef[i][0]];
855
        coef[i][1] = dca_downmix_coeffs[downmix_coef[i][1]];
856
    }
857

    
858
    switch (srcfmt) {
859
    case DCA_MONO:
860
    case DCA_CHANNEL:
861
    case DCA_STEREO_TOTAL:
862
    case DCA_STEREO_SUMDIFF:
863
    case DCA_4F2R:
864
        av_log(NULL, 0, "Not implemented!\n");
865
        break;
866
    case DCA_STEREO:
867
        break;
868
    case DCA_3F:
869
        DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),);
870
        break;
871
    case DCA_2F1R:
872
        DOWNMIX_TO_STEREO(MIX_REAR1(samples, i + 512, 2, coef),);
873
        break;
874
    case DCA_3F1R:
875
        DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
876
                          MIX_REAR1(samples, i + 768, 3, coef));
877
        break;
878
    case DCA_2F2R:
879
        DOWNMIX_TO_STEREO(MIX_REAR2(samples, i + 512, i + 768, 2, coef),);
880
        break;
881
    case DCA_3F2R:
882
        DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
883
                          MIX_REAR2(samples, i + 768, i + 1024, 3, coef));
884
        break;
885
    }
886
}
887

    
888

    
889
/* Very compact version of the block code decoder that does not use table
890
 * look-up but is slightly slower */
891
static int decode_blockcode(int code, int levels, int *values)
892
{
893
    int i;
894
    int offset = (levels - 1) >> 1;
895

    
896
    for (i = 0; i < 4; i++) {
897
        values[i] = (code % levels) - offset;
898
        code /= levels;
899
    }
900

    
901
    if (code == 0)
902
        return 0;
903
    else {
904
        av_log(NULL, AV_LOG_ERROR, "ERROR: block code look-up failed\n");
905
        return -1;
906
    }
907
}
908

    
909
static const uint8_t abits_sizes[7] = { 7, 10, 12, 13, 15, 17, 19 };
910
static const uint8_t abits_levels[7] = { 3, 5, 7, 9, 13, 17, 25 };
911

    
912
static int dca_subsubframe(DCAContext * s)
913
{
914
    int k, l;
915
    int subsubframe = s->current_subsubframe;
916

    
917
    const float *quant_step_table;
918

    
919
    /* FIXME */
920
    float subband_samples[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][8];
921

    
922
    /*
923
     * Audio data
924
     */
925

    
926
    /* Select quantization step size table */
927
    if (s->bit_rate_index == 0x1f)
928
        quant_step_table = lossless_quant_d;
929
    else
930
        quant_step_table = lossy_quant_d;
931

    
932
    for (k = 0; k < s->prim_channels; k++) {
933
        for (l = 0; l < s->vq_start_subband[k]; l++) {
934
            int m;
935

    
936
            /* Select the mid-tread linear quantizer */
937
            int abits = s->bitalloc[k][l];
938

    
939
            float quant_step_size = quant_step_table[abits];
940
            float rscale;
941

    
942
            /*
943
             * Determine quantization index code book and its type
944
             */
945

    
946
            /* Select quantization index code book */
947
            int sel = s->quant_index_huffman[k][abits];
948

    
949
            /*
950
             * Extract bits from the bit stream
951
             */
952
            if(!abits){
953
                memset(subband_samples[k][l], 0, 8 * sizeof(subband_samples[0][0][0]));
954
            }else if(abits >= 11 || !dca_smpl_bitalloc[abits].vlc[sel].table){
955
                if(abits <= 7){
956
                    /* Block code */
957
                    int block_code1, block_code2, size, levels;
958
                    int block[8];
959

    
960
                    size = abits_sizes[abits-1];
961
                    levels = abits_levels[abits-1];
962

    
963
                    block_code1 = get_bits(&s->gb, size);
964
                    /* FIXME Should test return value */
965
                    decode_blockcode(block_code1, levels, block);
966
                    block_code2 = get_bits(&s->gb, size);
967
                    decode_blockcode(block_code2, levels, &block[4]);
968
                    for (m = 0; m < 8; m++)
969
                        subband_samples[k][l][m] = block[m];
970
                }else{
971
                    /* no coding */
972
                    for (m = 0; m < 8; m++)
973
                        subband_samples[k][l][m] = get_sbits(&s->gb, abits - 3);
974
                }
975
            }else{
976
                /* Huffman coded */
977
                for (m = 0; m < 8; m++)
978
                    subband_samples[k][l][m] = get_bitalloc(&s->gb, &dca_smpl_bitalloc[abits], sel);
979
            }
980

    
981
            /* Deal with transients */
982
            if (s->transition_mode[k][l] &&
983
                subsubframe >= s->transition_mode[k][l])
984
                rscale = quant_step_size * s->scale_factor[k][l][1];
985
            else
986
                rscale = quant_step_size * s->scale_factor[k][l][0];
987

    
988
            rscale *= s->scalefactor_adj[k][sel];
989

    
990
            for (m = 0; m < 8; m++)
991
                subband_samples[k][l][m] *= rscale;
992

    
993
            /*
994
             * Inverse ADPCM if in prediction mode
995
             */
996
            if (s->prediction_mode[k][l]) {
997
                int n;
998
                for (m = 0; m < 8; m++) {
999
                    for (n = 1; n <= 4; n++)
1000
                        if (m >= n)
1001
                            subband_samples[k][l][m] +=
1002
                                (adpcm_vb[s->prediction_vq[k][l]][n - 1] *
1003
                                 subband_samples[k][l][m - n] / 8192);
1004
                        else if (s->predictor_history)
1005
                            subband_samples[k][l][m] +=
1006
                                (adpcm_vb[s->prediction_vq[k][l]][n - 1] *
1007
                                 s->subband_samples_hist[k][l][m - n +
1008
                                                               4] / 8192);
1009
                }
1010
            }
1011
        }
1012

    
1013
        /*
1014
         * Decode VQ encoded high frequencies
1015
         */
1016
        for (l = s->vq_start_subband[k]; l < s->subband_activity[k]; l++) {
1017
            /* 1 vector -> 32 samples but we only need the 8 samples
1018
             * for this subsubframe. */
1019
            int m;
1020

    
1021
            if (!s->debug_flag & 0x01) {
1022
                av_log(s->avctx, AV_LOG_DEBUG, "Stream with high frequencies VQ coding\n");
1023
                s->debug_flag |= 0x01;
1024
            }
1025

    
1026
            for (m = 0; m < 8; m++) {
1027
                subband_samples[k][l][m] =
1028
                    high_freq_vq[s->high_freq_vq[k][l]][subsubframe * 8 +
1029
                                                        m]
1030
                    * (float) s->scale_factor[k][l][0] / 16.0;
1031
            }
1032
        }
1033
    }
1034

    
1035
    /* Check for DSYNC after subsubframe */
1036
    if (s->aspf || subsubframe == s->subsubframes - 1) {
1037
        if (0xFFFF == get_bits(&s->gb, 16)) {   /* 0xFFFF */
1038
#ifdef TRACE
1039
            av_log(s->avctx, AV_LOG_DEBUG, "Got subframe DSYNC\n");
1040
#endif
1041
        } else {
1042
            av_log(s->avctx, AV_LOG_ERROR, "Didn't get subframe DSYNC\n");
1043
        }
1044
    }
1045

    
1046
    /* Backup predictor history for adpcm */
1047
    for (k = 0; k < s->prim_channels; k++)
1048
        for (l = 0; l < s->vq_start_subband[k]; l++)
1049
            memcpy(s->subband_samples_hist[k][l], &subband_samples[k][l][4],
1050
                        4 * sizeof(subband_samples[0][0][0]));
1051

    
1052
    /* 32 subbands QMF */
1053
    for (k = 0; k < s->prim_channels; k++) {
1054
/*        static float pcm_to_double[8] =
1055
            {32768.0, 32768.0, 524288.0, 524288.0, 0, 8388608.0, 8388608.0};*/
1056
         qmf_32_subbands(s, k, subband_samples[k], &s->samples[256 * s->channel_order_tab[k]],
1057
                            M_SQRT1_2*s->scale_bias /*pcm_to_double[s->source_pcm_res] */ ,
1058
                            s->add_bias );
1059
    }
1060

    
1061
    /* Down mixing */
1062

    
1063
    if (s->prim_channels > dca_channels[s->output & DCA_CHANNEL_MASK]) {
1064
        dca_downmix(s->samples, s->amode, s->downmix_coef);
1065
    }
1066

    
1067
    /* Generate LFE samples for this subsubframe FIXME!!! */
1068
    if (s->output & DCA_LFE) {
1069
        int lfe_samples = 2 * s->lfe * s->subsubframes;
1070

    
1071
        lfe_interpolation_fir(s->lfe, 2 * s->lfe,
1072
                              s->lfe_data + lfe_samples +
1073
                              2 * s->lfe * subsubframe,
1074
                              &s->samples[256 * dca_lfe_index[s->amode]],
1075
                              (1.0/256.0)*s->scale_bias,  s->add_bias);
1076
        /* Outputs 20bits pcm samples */
1077
    }
1078

    
1079
    return 0;
1080
}
1081

    
1082

    
1083
static int dca_subframe_footer(DCAContext * s)
1084
{
1085
    int aux_data_count = 0, i;
1086
    int lfe_samples;
1087

    
1088
    /*
1089
     * Unpack optional information
1090
     */
1091

    
1092
    if (s->timestamp)
1093
        get_bits(&s->gb, 32);
1094

    
1095
    if (s->aux_data)
1096
        aux_data_count = get_bits(&s->gb, 6);
1097

    
1098
    for (i = 0; i < aux_data_count; i++)
1099
        get_bits(&s->gb, 8);
1100

    
1101
    if (s->crc_present && (s->downmix || s->dynrange))
1102
        get_bits(&s->gb, 16);
1103

    
1104
    lfe_samples = 2 * s->lfe * s->subsubframes;
1105
    for (i = 0; i < lfe_samples; i++) {
1106
        s->lfe_data[i] = s->lfe_data[i + lfe_samples];
1107
    }
1108

    
1109
    return 0;
1110
}
1111

    
1112
/**
1113
 * Decode a dca frame block
1114
 *
1115
 * @param s     pointer to the DCAContext
1116
 */
1117

    
1118
static int dca_decode_block(DCAContext * s)
1119
{
1120

    
1121
    /* Sanity check */
1122
    if (s->current_subframe >= s->subframes) {
1123
        av_log(s->avctx, AV_LOG_DEBUG, "check failed: %i>%i",
1124
               s->current_subframe, s->subframes);
1125
        return -1;
1126
    }
1127

    
1128
    if (!s->current_subsubframe) {
1129
#ifdef TRACE
1130
        av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subframe_header\n");
1131
#endif
1132
        /* Read subframe header */
1133
        if (dca_subframe_header(s))
1134
            return -1;
1135
    }
1136

    
1137
    /* Read subsubframe */
1138
#ifdef TRACE
1139
    av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subsubframe\n");
1140
#endif
1141
    if (dca_subsubframe(s))
1142
        return -1;
1143

    
1144
    /* Update state */
1145
    s->current_subsubframe++;
1146
    if (s->current_subsubframe >= s->subsubframes) {
1147
        s->current_subsubframe = 0;
1148
        s->current_subframe++;
1149
    }
1150
    if (s->current_subframe >= s->subframes) {
1151
#ifdef TRACE
1152
        av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subframe_footer\n");
1153
#endif
1154
        /* Read subframe footer */
1155
        if (dca_subframe_footer(s))
1156
            return -1;
1157
    }
1158

    
1159
    return 0;
1160
}
1161

    
1162
/**
1163
 * Convert bitstream to one representation based on sync marker
1164
 */
1165
static int dca_convert_bitstream(const uint8_t * src, int src_size, uint8_t * dst,
1166
                          int max_size)
1167
{
1168
    uint32_t mrk;
1169
    int i, tmp;
1170
    const uint16_t *ssrc = (const uint16_t *) src;
1171
    uint16_t *sdst = (uint16_t *) dst;
1172
    PutBitContext pb;
1173

    
1174
    if((unsigned)src_size > (unsigned)max_size) {
1175
//        av_log(NULL, AV_LOG_ERROR, "Input frame size larger then DCA_MAX_FRAME_SIZE!\n");
1176
//        return -1;
1177
        src_size = max_size;
1178
    }
1179

    
1180
    mrk = AV_RB32(src);
1181
    switch (mrk) {
1182
    case DCA_MARKER_RAW_BE:
1183
        memcpy(dst, src, src_size);
1184
        return src_size;
1185
    case DCA_MARKER_RAW_LE:
1186
        for (i = 0; i < (src_size + 1) >> 1; i++)
1187
            *sdst++ = bswap_16(*ssrc++);
1188
        return src_size;
1189
    case DCA_MARKER_14B_BE:
1190
    case DCA_MARKER_14B_LE:
1191
        init_put_bits(&pb, dst, max_size);
1192
        for (i = 0; i < (src_size + 1) >> 1; i++, src += 2) {
1193
            tmp = ((mrk == DCA_MARKER_14B_BE) ? AV_RB16(src) : AV_RL16(src)) & 0x3FFF;
1194
            put_bits(&pb, 14, tmp);
1195
        }
1196
        flush_put_bits(&pb);
1197
        return (put_bits_count(&pb) + 7) >> 3;
1198
    default:
1199
        return -1;
1200
    }
1201
}
1202

    
1203
/**
1204
 * Main frame decoding function
1205
 * FIXME add arguments
1206
 */
1207
static int dca_decode_frame(AVCodecContext * avctx,
1208
                            void *data, int *data_size,
1209
                            AVPacket *avpkt)
1210
{
1211
    const uint8_t *buf = avpkt->data;
1212
    int buf_size = avpkt->size;
1213

    
1214
    int i;
1215
    int16_t *samples = data;
1216
    DCAContext *s = avctx->priv_data;
1217
    int channels;
1218

    
1219

    
1220
    s->dca_buffer_size = dca_convert_bitstream(buf, buf_size, s->dca_buffer, DCA_MAX_FRAME_SIZE);
1221
    if (s->dca_buffer_size == -1) {
1222
        av_log(avctx, AV_LOG_ERROR, "Not a valid DCA frame\n");
1223
        return -1;
1224
    }
1225

    
1226
    init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
1227
    if (dca_parse_frame_header(s) < 0) {
1228
        //seems like the frame is corrupt, try with the next one
1229
        *data_size=0;
1230
        return buf_size;
1231
    }
1232
    //set AVCodec values with parsed data
1233
    avctx->sample_rate = s->sample_rate;
1234
    avctx->bit_rate = s->bit_rate;
1235

    
1236
    channels = s->prim_channels + !!s->lfe;
1237

    
1238
    if (s->amode<16) {
1239
        avctx->channel_layout = dca_core_channel_layout[s->amode];
1240

    
1241
        if (s->lfe) {
1242
            avctx->channel_layout |= CH_LOW_FREQUENCY;
1243
            s->channel_order_tab = dca_channel_reorder_lfe[s->amode];
1244
        } else
1245
            s->channel_order_tab = dca_channel_reorder_nolfe[s->amode];
1246

    
1247
        if (s->prim_channels > 0 &&
1248
            s->channel_order_tab[s->prim_channels - 1] < 0)
1249
            return -1;
1250

    
1251
        if(avctx->request_channels == 2 && s->prim_channels > 2) {
1252
            channels = 2;
1253
            s->output = DCA_STEREO;
1254
            avctx->channel_layout = CH_LAYOUT_STEREO;
1255
        }
1256
    } else {
1257
        av_log(avctx, AV_LOG_ERROR, "Non standard configuration %d !\n",s->amode);
1258
        return -1;
1259
    }
1260

    
1261

    
1262
    /* There is nothing that prevents a dts frame to change channel configuration
1263
       but FFmpeg doesn't support that so only set the channels if it is previously
1264
       unset. Ideally during the first probe for channels the crc should be checked
1265
       and only set avctx->channels when the crc is ok. Right now the decoder could
1266
       set the channels based on a broken first frame.*/
1267
    if (!avctx->channels)
1268
        avctx->channels = channels;
1269

    
1270
    if(*data_size < (s->sample_blocks / 8) * 256 * sizeof(int16_t) * channels)
1271
        return -1;
1272
    *data_size = 256 / 8 * s->sample_blocks * sizeof(int16_t) * channels;
1273
    for (i = 0; i < (s->sample_blocks / 8); i++) {
1274
        dca_decode_block(s);
1275
        s->dsp.float_to_int16_interleave(samples, s->samples_chanptr, 256, channels);
1276
        samples += 256 * channels;
1277
    }
1278

    
1279
    return buf_size;
1280
}
1281

    
1282

    
1283

    
1284
/**
1285
 * DCA initialization
1286
 *
1287
 * @param avctx     pointer to the AVCodecContext
1288
 */
1289

    
1290
static av_cold int dca_decode_init(AVCodecContext * avctx)
1291
{
1292
    DCAContext *s = avctx->priv_data;
1293
    int i;
1294

    
1295
    s->avctx = avctx;
1296
    dca_init_vlcs();
1297

    
1298
    dsputil_init(&s->dsp, avctx);
1299
    ff_mdct_init(&s->imdct, 6, 1, 1.0);
1300

    
1301
    for(i = 0; i < 6; i++)
1302
        s->samples_chanptr[i] = s->samples + i * 256;
1303
    avctx->sample_fmt = SAMPLE_FMT_S16;
1304

    
1305
    if(s->dsp.float_to_int16_interleave == ff_float_to_int16_interleave_c) {
1306
        s->add_bias = 385.0f;
1307
        s->scale_bias = 1.0 / 32768.0;
1308
    } else {
1309
        s->add_bias = 0.0f;
1310
        s->scale_bias = 1.0;
1311

    
1312
        /* allow downmixing to stereo */
1313
        if (avctx->channels > 0 && avctx->request_channels < avctx->channels &&
1314
                avctx->request_channels == 2) {
1315
            avctx->channels = avctx->request_channels;
1316
        }
1317
    }
1318

    
1319

    
1320
    return 0;
1321
}
1322

    
1323
static av_cold int dca_decode_end(AVCodecContext * avctx)
1324
{
1325
    DCAContext *s = avctx->priv_data;
1326
    ff_mdct_end(&s->imdct);
1327
    return 0;
1328
}
1329

    
1330
AVCodec dca_decoder = {
1331
    .name = "dca",
1332
    .type = CODEC_TYPE_AUDIO,
1333
    .id = CODEC_ID_DTS,
1334
    .priv_data_size = sizeof(DCAContext),
1335
    .init = dca_decode_init,
1336
    .decode = dca_decode_frame,
1337
    .close = dca_decode_end,
1338
    .long_name = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
1339
};