Statistics
| Branch: | Revision:

ffmpeg / libavcodec / dca.c @ 9ed73b48

History | View | Annotate | Download (43.7 KB)

1
/*
2
 * DCA compatible decoder
3
 * Copyright (C) 2004 Gildas Bazin
4
 * Copyright (C) 2004 Benjamin Zores
5
 * Copyright (C) 2006 Benjamin Larsson
6
 * Copyright (C) 2007 Konstantin Shishkov
7
 *
8
 * This file is part of FFmpeg.
9
 *
10
 * FFmpeg is free software; you can redistribute it and/or
11
 * modify it under the terms of the GNU Lesser General Public
12
 * License as published by the Free Software Foundation; either
13
 * version 2.1 of the License, or (at your option) any later version.
14
 *
15
 * FFmpeg is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18
 * Lesser General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Lesser General Public
21
 * License along with FFmpeg; if not, write to the Free Software
22
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23
 */
24

    
25
/**
26
 * @file dca.c
27
 */
28

    
29
#include <math.h>
30
#include <stddef.h>
31
#include <stdio.h>
32

    
33
#include "avcodec.h"
34
#include "dsputil.h"
35
#include "bitstream.h"
36
#include "dcadata.h"
37
#include "dcahuff.h"
38
#include "dca.h"
39

    
40
//#define TRACE
41

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

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

    
62
#define DCA_DOLBY 101           /* FIXME */
63

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

    
67
#define DCA_LFE 0x80
68

    
69
#define HEADER_SIZE 14
70

    
71
#define DCA_MAX_FRAME_SIZE 16384
72

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

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

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

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

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

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

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

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

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

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

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

    
165
    DECLARE_ALIGNED_16(float, samples[1536]);  /* 6 * 256 = 1536, might only need 5 */
166
    const float *samples_chanptr[6];
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
    MDCTContext imdct;
179
} DCAContext;
180

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

    
186
    if (vlcs_initialized)
187
        return;
188

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

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

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

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

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

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

    
239
    /* Frame header */
240
    s->frame_type        = get_bits(&s->gb, 1);
241
    s->samples_deficit   = get_bits(&s->gb, 5) + 1;
242
    s->crc_present       = get_bits(&s->gb, 1);
243
    s->sample_blocks     = get_bits(&s->gb, 7) + 1;
244
    s->frame_size        = get_bits(&s->gb, 14) + 1;
245
    if (s->frame_size < 95)
246
        return -1;
247
    s->amode             = get_bits(&s->gb, 6);
248
    s->sample_rate       = dca_sample_rates[get_bits(&s->gb, 4)];
249
    if (!s->sample_rate)
250
        return -1;
251
    s->bit_rate_index;   = get_bits(&s->gb, 5);
252
    s->bit_rate          = dca_bit_rates[s->bit_rate_index];
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 Hz\n",
293
           s->sample_rate);
294
    av_log(s->avctx, AV_LOG_DEBUG, "bit rate: %i bits/s\n",
295
           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->total_channels    = get_bits(&s->gb, 3) + 1;
324
    s->prim_channels     = s->total_channels;
325
    if (s->prim_channels > DCA_PRIM_CHANNELS_MAX)
326
        s->prim_channels = DCA_PRIM_CHANNELS_MAX;   /* We only support DTS core */
327

    
328

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

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

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

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

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

    
365
    s->current_subframe = 0;
366
    s->current_subsubframe = 0;
367

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

    
390
    return 0;
391
}
392

    
393

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
548
    /*
549
     * Primary audio data arrays
550
     */
551

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

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

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

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

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

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

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

    
649
    return 0;
650
}
651

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

    
660
    int hist_index= s->hist_index[chans];
661
    float *subband_fir_hist2 = s->subband_fir_noidea[chans];
662

    
663
    int subindex;
664

    
665
    scale *= sqrt(1/8.0);
666

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

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

    
684
        ff_imdct_half(&s->imdct, subband_fir_hist, raXin);
685

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

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

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

    
729
    int decifactor, k, j;
730
    const float *prCoeff;
731

    
732
    int interp_index = 0;       /* Index to the interpolated samples */
733
    int deciindex;
734

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

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

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

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

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

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

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

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

    
818

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

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

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

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

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

    
847
    const float *quant_step_table;
848

    
849
    /* FIXME */
850
    float subband_samples[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][8];
851

    
852
    /*
853
     * Audio data
854
     */
855

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

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

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

    
869
            float quant_step_size = quant_step_table[abits];
870
            float rscale;
871

    
872
            /*
873
             * Determine quantization index code book and its type
874
             */
875

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

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

    
890
                    size = abits_sizes[abits-1];
891
                    levels = abits_levels[abits-1];
892

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

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

    
918
            rscale *= s->scalefactor_adj[k][sel];
919

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

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

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

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

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

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

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

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

    
991
    /* Down mixing */
992

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

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

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

    
1010
    return 0;
1011
}
1012

    
1013

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

    
1019
    /*
1020
     * Unpack optional information
1021
     */
1022

    
1023
    if (s->timestamp)
1024
        get_bits(&s->gb, 32);
1025

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

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

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

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

    
1040
    return 0;
1041
}
1042

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

    
1049
static int dca_decode_block(DCAContext * s)
1050
{
1051

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

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

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

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

    
1090
    return 0;
1091
}
1092

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

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

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

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

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

    
1147

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

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

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

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

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

    
1187
    return buf_size;
1188
}
1189

    
1190

    
1191

    
1192
/**
1193
 * DCA initialization
1194
 *
1195
 * @param avctx     pointer to the AVCodecContext
1196
 */
1197

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

    
1203
    s->avctx = avctx;
1204
    dca_init_vlcs();
1205

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

    
1209
    for(i = 0; i < 6; i++)
1210
        s->samples_chanptr[i] = s->samples + i * 256;
1211
    avctx->sample_fmt = SAMPLE_FMT_S16;
1212

    
1213
    if(s->dsp.float_to_int16 == ff_float_to_int16_c) {
1214
        s->add_bias = 385.0f;
1215
        s->scale_bias = 1.0 / 32768.0;
1216
    } else {
1217
        s->add_bias = 0.0f;
1218
        s->scale_bias = 1.0;
1219

    
1220
        /* allow downmixing to stereo */
1221
        if (avctx->channels > 0 && avctx->request_channels < avctx->channels &&
1222
                avctx->request_channels == 2) {
1223
            avctx->channels = avctx->request_channels;
1224
        }
1225
    }
1226

    
1227

    
1228
    return 0;
1229
}
1230

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

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