Statistics
| Branch: | Revision:

ffmpeg / libavcodec / dca.c @ 98c98e04

History | View | Annotate | Download (43.2 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
#define CONVERT_BIAS 384
71

    
72
#define DCA_MAX_FRAME_SIZE 16383
73

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

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

    
87
/** Pre-calculated cosine modulation coefs for the QMF */
88
static float cos_mod[544];
89

    
90
static int av_always_inline get_bitalloc(GetBitContext *gb, BitAlloc *ba, int idx)
91
{
92
    return get_vlc2(gb, ba->vlc[idx].table, ba->vlc[idx].bits, ba->wrap) + ba->offset;
93
}
94

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

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

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

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

    
151
    int high_freq_vq[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];       ///< VQ encoded high frequency subbands
152

    
153
    float lfe_data[2 * DCA_SUBSUBFAMES_MAX * DCA_LFE_MAX *
154
                   2 /*history */ ];    ///< Low frequency effect data
155
    int lfe_scale_factor;
156

    
157
    /* Subband samples history (for ADPCM) */
158
    float subband_samples_hist[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][4];
159
    float subband_fir_hist[DCA_PRIM_CHANNELS_MAX][512];
160
    float subband_fir_noidea[DCA_PRIM_CHANNELS_MAX][64];
161

    
162
    int output;                 ///< type of output
163
    int bias;                   ///< output bias
164

    
165
    DECLARE_ALIGNED_16(float, samples[1536]);  /* 6 * 256 = 1536, might only need 5 */
166
    DECLARE_ALIGNED_16(int16_t, tsamples[1536]);
167

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

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

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

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

    
185
    if (vlcs_inited)
186
        return;
187

    
188
    dca_bitalloc_index.offset = 1;
189
    dca_bitalloc_index.wrap = 1;
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_inited = 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
    s->bias = CONVERT_BIAS;
234

    
235
    init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
236

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

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

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

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

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

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

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

    
321
    /* Primary audio coding header */
322
    s->subframes         = get_bits(&s->gb, 4) + 1;
323
    s->prim_channels     = get_bits(&s->gb, 3) + 1;
324

    
325

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

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

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

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

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

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

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

    
387
    return 0;
388
}
389

    
390

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

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

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

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

    
423
    /* Bit allocation index */
424
    for (j = 0; j < s->prim_channels; j++) {
425
        for (k = 0; k < s->vq_start_subband[j]; k++) {
426
            if (s->bitalloc_huffman[j] == 6)
427
                s->bitalloc[j][k] = get_bits(&s->gb, 5);
428
            else if (s->bitalloc_huffman[j] == 5)
429
                s->bitalloc[j][k] = get_bits(&s->gb, 4);
430
            else {
431
                s->bitalloc[j][k] =
432
                    get_bitalloc(&s->gb, &dca_bitalloc_index, s->bitalloc_huffman[j]);
433
            }
434

    
435
            if (s->bitalloc[j][k] > 26) {
436
//                 av_log(s->avctx,AV_LOG_DEBUG,"bitalloc index [%i][%i] too big (%i)\n",
437
//                          j, k, s->bitalloc[j][k]);
438
                return -1;
439
            }
440
        }
441
    }
442

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

    
455
    for (j = 0; j < s->prim_channels; j++) {
456
        uint32_t *scale_table;
457
        int scale_sum;
458

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

    
461
        if (s->scalefactor_huffman[j] == 6)
462
            scale_table = (uint32_t *) scale_factor_quant7;
463
        else
464
            scale_table = (uint32_t *) scale_factor_quant6;
465

    
466
        /* When huffman coded, only the difference is encoded */
467
        scale_sum = 0;
468

    
469
        for (k = 0; k < s->subband_activity[j]; k++) {
470
            if (k >= s->vq_start_subband[j] || s->bitalloc[j][k] > 0) {
471
                scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum);
472
                s->scale_factor[j][k][0] = scale_table[scale_sum];
473
            }
474

    
475
            if (k < s->vq_start_subband[j] && s->transition_mode[j][k]) {
476
                /* Get second scale factor */
477
                scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum);
478
                s->scale_factor[j][k][1] = scale_table[scale_sum];
479
            }
480
        }
481
    }
482

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

    
490
    /* Scale factors for joint subband coding */
491
    for (j = 0; j < s->prim_channels; j++) {
492
        int source_channel;
493

    
494
        /* Transmitted only if joint subband coding enabled */
495
        if (s->joint_intensity[j] > 0) {
496
            int scale = 0;
497
            source_channel = s->joint_intensity[j] - 1;
498

    
499
            /* When huffman coded, only the difference is encoded
500
             * (is this valid as well for joint scales ???) */
501

    
502
            for (k = s->subband_activity[j]; k < s->subband_activity[source_channel]; k++) {
503
                scale = get_scale(&s->gb, s->joint_huff[j], 0);
504
                scale += 64;    /* bias */
505
                s->joint_scale_factor[j][k] = scale;    /*joint_scale_table[scale]; */
506
            }
507

    
508
            if (!s->debug_flag & 0x02) {
509
                av_log(s->avctx, AV_LOG_DEBUG,
510
                       "Joint stereo coding not supported\n");
511
                s->debug_flag |= 0x02;
512
            }
513
        }
514
    }
515

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

    
532
    /* Dynamic range coefficient */
533
    if (s->dynrange)
534
        s->dynrange_coef = get_bits(&s->gb, 8);
535

    
536
    /* Side information CRC check word */
537
    if (s->crc_present) {
538
        get_bits(&s->gb, 16);
539
    }
540

    
541
    /*
542
     * Primary audio data arrays
543
     */
544

    
545
    /* VQ encoded high frequency subbands */
546
    for (j = 0; j < s->prim_channels; j++)
547
        for (k = s->vq_start_subband[j]; k < s->subband_activity[j]; k++)
548
            /* 1 vector -> 32 samples */
549
            s->high_freq_vq[j][k] = get_bits(&s->gb, 10);
550

    
551
    /* Low frequency effect data */
552
    if (s->lfe) {
553
        /* LFE samples */
554
        int lfe_samples = 2 * s->lfe * s->subsubframes;
555
        float lfe_scale;
556

    
557
        for (j = lfe_samples; j < lfe_samples * 2; j++) {
558
            /* Signed 8 bits int */
559
            s->lfe_data[j] = get_sbits(&s->gb, 8);
560
        }
561

    
562
        /* Scale factor index */
563
        s->lfe_scale_factor = scale_factor_quant7[get_bits(&s->gb, 8)];
564

    
565
        /* Quantization step size * scale factor */
566
        lfe_scale = 0.035 * s->lfe_scale_factor;
567

    
568
        for (j = lfe_samples; j < lfe_samples * 2; j++)
569
            s->lfe_data[j] *= lfe_scale;
570
    }
571

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

    
640
    return 0;
641
}
642

    
643
static void qmf_32_subbands(DCAContext * s, int chans,
644
                            float samples_in[32][8], float *samples_out,
645
                            float scale, float bias)
646
{
647
    float *prCoeff;
648
    int i, j, k;
649
    float praXin[33], *raXin = &praXin[1];
650

    
651
    float *subband_fir_hist = s->subband_fir_hist[chans];
652
    float *subband_fir_hist2 = s->subband_fir_noidea[chans];
653

    
654
    int chindex = 0, subindex;
655

    
656
    praXin[0] = 0.0;
657

    
658
    /* Select filter */
659
    if (!s->multirate_inter)    /* Non-perfect reconstruction */
660
        prCoeff = (float *) fir_32bands_nonperfect;
661
    else                        /* Perfect reconstruction */
662
        prCoeff = (float *) fir_32bands_perfect;
663

    
664
    /* Reconstructed channel sample index */
665
    for (subindex = 0; subindex < 8; subindex++) {
666
        float t1, t2, sum[16], diff[16];
667

    
668
        /* Load in one sample from each subband and clear inactive subbands */
669
        for (i = 0; i < s->subband_activity[chans]; i++)
670
            raXin[i] = samples_in[i][subindex];
671
        for (; i < 32; i++)
672
            raXin[i] = 0.0;
673

    
674
        /* Multiply by cosine modulation coefficients and
675
         * create temporary arrays SUM and DIFF */
676
        for (j = 0, k = 0; k < 16; k++) {
677
            t1 = 0.0;
678
            t2 = 0.0;
679
            for (i = 0; i < 16; i++, j++){
680
                t1 += (raXin[2 * i] + raXin[2 * i + 1]) * cos_mod[j];
681
                t2 += (raXin[2 * i] + raXin[2 * i - 1]) * cos_mod[j + 256];
682
            }
683
            sum[k] = t1 + t2;
684
            diff[k] = t1 - t2;
685
        }
686

    
687
        j = 512;
688
        /* Store history */
689
        for (k = 0; k < 16; k++)
690
            subband_fir_hist[k] = cos_mod[j++] * sum[k];
691
        for (k = 0; k < 16; k++)
692
            subband_fir_hist[32-k-1] = cos_mod[j++] * diff[k];
693

    
694
        /* Multiply by filter coefficients */
695
        for (k = 31, i = 0; i < 32; i++, k--)
696
            for (j = 0; j < 512; j += 64){
697
                subband_fir_hist2[i]    += prCoeff[i+j]  * ( subband_fir_hist[i+j] - subband_fir_hist[j+k]);
698
                subband_fir_hist2[i+32] += prCoeff[i+j+32]*(-subband_fir_hist[i+j] - subband_fir_hist[j+k]);
699
            }
700

    
701
        /* Create 32 PCM output samples */
702
        for (i = 0; i < 32; i++)
703
            samples_out[chindex++] = subband_fir_hist2[i] * scale + bias;
704

    
705
        /* Update working arrays */
706
        memmove(&subband_fir_hist[32], &subband_fir_hist[0], (512 - 32) * sizeof(float));
707
        memmove(&subband_fir_hist2[0], &subband_fir_hist2[32], 32 * sizeof(float));
708
        memset(&subband_fir_hist2[32], 0, 32 * sizeof(float));
709
    }
710
}
711

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

    
725
    int decifactor, k, j;
726
    const float *prCoeff;
727

    
728
    int interp_index = 0;       /* Index to the interpolated samples */
729
    int deciindex;
730

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

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

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

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

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

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

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

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

    
814

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

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

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

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

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

    
843
    float *quant_step_table;
844

    
845
    /* FIXME */
846
    float subband_samples[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][8];
847

    
848
    /*
849
     * Audio data
850
     */
851

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

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

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

    
865
            float quant_step_size = quant_step_table[abits];
866
            float rscale;
867

    
868
            /*
869
             * Determine quantization index code book and its type
870
             */
871

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

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

    
886
                    size = abits_sizes[abits-1];
887
                    levels = abits_levels[abits-1];
888

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

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

    
914
            rscale *= s->scalefactor_adj[k][sel];
915

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

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

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

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

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

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

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

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

    
987
    /* Down mixing */
988

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

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

    
998
        lfe_interpolation_fir(s->lfe, 2 * s->lfe,
999
                              s->lfe_data + lfe_samples +
1000
                              2 * s->lfe * subsubframe,
1001
                              &s->samples[256 * i_channels],
1002
                              8388608.0, s->bias);
1003
        /* Outputs 20bits pcm samples */
1004
    }
1005

    
1006
    return 0;
1007
}
1008

    
1009

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

    
1015
    /*
1016
     * Unpack optional information
1017
     */
1018

    
1019
    if (s->timestamp)
1020
        get_bits(&s->gb, 32);
1021

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

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

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

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

    
1036
    return 0;
1037
}
1038

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

    
1045
static int dca_decode_block(DCAContext * s)
1046
{
1047

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

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

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

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

    
1086
    return 0;
1087
}
1088

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

    
1100
    if((unsigned)src_size > (unsigned)max_size)
1101
        return -1;
1102

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

    
1126
/**
1127
 * Main frame decoding function
1128
 * FIXME add arguments
1129
 */
1130
static int dca_decode_frame(AVCodecContext * avctx,
1131
                            void *data, int *data_size,
1132
                            uint8_t * buf, int buf_size)
1133
{
1134

    
1135
    int i, j, k;
1136
    int16_t *samples = data;
1137
    DCAContext *s = avctx->priv_data;
1138
    int channels;
1139

    
1140

    
1141
    s->dca_buffer_size = dca_convert_bitstream(buf, buf_size, s->dca_buffer, DCA_MAX_FRAME_SIZE);
1142
    if (s->dca_buffer_size == -1) {
1143
        av_log(avctx, AV_LOG_ERROR, "Not a DCA frame\n");
1144
        return -1;
1145
    }
1146

    
1147
    init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
1148
    if (dca_parse_frame_header(s) < 0) {
1149
        //seems like the frame is corrupt, try with the next one
1150
        return buf_size;
1151
    }
1152
    //set AVCodec values with parsed data
1153
    avctx->sample_rate = s->sample_rate;
1154
    avctx->bit_rate = s->bit_rate;
1155

    
1156
    channels = s->prim_channels + !!s->lfe;
1157
    if(avctx->channels == 0) {
1158
        avctx->channels = channels;
1159
    } else if(channels < avctx->channels) {
1160
        av_log(avctx, AV_LOG_WARNING, "DTS source channels are less than "
1161
               "specified: output to %d channels.\n", channels);
1162
        avctx->channels = channels;
1163
    }
1164
    if(avctx->channels == 2) {
1165
        s->output = DCA_STEREO;
1166
    } else if(avctx->channels != channels) {
1167
        av_log(avctx, AV_LOG_ERROR, "Cannot downmix DTS to %d channels.\n",
1168
               avctx->channels);
1169
        return -1;
1170
    }
1171

    
1172
    channels = avctx->channels;
1173
    if(*data_size < (s->sample_blocks / 8) * 256 * sizeof(int16_t) * channels)
1174
        return -1;
1175
    *data_size = 0;
1176
    for (i = 0; i < (s->sample_blocks / 8); i++) {
1177
        dca_decode_block(s);
1178
        s->dsp.float_to_int16(s->tsamples, s->samples, 256 * channels);
1179
        /* interleave samples */
1180
        for (j = 0; j < 256; j++) {
1181
            for (k = 0; k < channels; k++)
1182
                samples[k] = s->tsamples[j + k * 256];
1183
            samples += channels;
1184
        }
1185
        *data_size += 256 * sizeof(int16_t) * channels;
1186
    }
1187

    
1188
    return buf_size;
1189
}
1190

    
1191

    
1192

    
1193
/**
1194
 * Build the cosine modulation tables for the QMF
1195
 *
1196
 * @param s     pointer to the DCAContext
1197
 */
1198

    
1199
static void pre_calc_cosmod(DCAContext * s)
1200
{
1201
    int i, j, k;
1202
    static int cosmod_inited = 0;
1203

    
1204
    if(cosmod_inited) return;
1205
    for (j = 0, k = 0; k < 16; k++)
1206
        for (i = 0; i < 16; i++)
1207
            cos_mod[j++] = cos((2 * i + 1) * (2 * k + 1) * M_PI / 64);
1208

    
1209
    for (k = 0; k < 16; k++)
1210
        for (i = 0; i < 16; i++)
1211
            cos_mod[j++] = cos((i) * (2 * k + 1) * M_PI / 32);
1212

    
1213
    for (k = 0; k < 16; k++)
1214
        cos_mod[j++] = 0.25 / (2 * cos((2 * k + 1) * M_PI / 128));
1215

    
1216
    for (k = 0; k < 16; k++)
1217
        cos_mod[j++] = -0.25 / (2.0 * sin((2 * k + 1) * M_PI / 128));
1218

    
1219
    cosmod_inited = 1;
1220
}
1221

    
1222

    
1223
/**
1224
 * DCA initialization
1225
 *
1226
 * @param avctx     pointer to the AVCodecContext
1227
 */
1228

    
1229
static int dca_decode_init(AVCodecContext * avctx)
1230
{
1231
    DCAContext *s = avctx->priv_data;
1232

    
1233
    s->avctx = avctx;
1234
    dca_init_vlcs();
1235
    pre_calc_cosmod(s);
1236

    
1237
    dsputil_init(&s->dsp, avctx);
1238
    return 0;
1239
}
1240

    
1241

    
1242
AVCodec dca_decoder = {
1243
    .name = "dca",
1244
    .type = CODEC_TYPE_AUDIO,
1245
    .id = CODEC_ID_DTS,
1246
    .priv_data_size = sizeof(DCAContext),
1247
    .init = dca_decode_init,
1248
    .decode = dca_decode_frame,
1249
};