Statistics
| Branch: | Revision:

ffmpeg / libavcodec / dca.c @ cc826626

History | View | Annotate | Download (45.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 "parser.h"
39

    
40
/** DCA syncwords, also used for bitstream type detection */
41
//@{
42
#define DCA_MARKER_RAW_BE 0x7FFE8001
43
#define DCA_MARKER_RAW_LE 0xFE7F0180
44
#define DCA_MARKER_14B_BE 0x1FFFE800
45
#define DCA_MARKER_14B_LE 0xFF1F00E8
46
//@}
47

    
48
//#define TRACE
49

    
50
#define DCA_PRIM_CHANNELS_MAX (5)
51
#define DCA_SUBBANDS (32)
52
#define DCA_ABITS_MAX (32)      /* Should be 28 */
53
#define DCA_SUBSUBFAMES_MAX (4)
54
#define DCA_LFE_MAX (3)
55

    
56
enum DCAMode {
57
    DCA_MONO = 0,
58
    DCA_CHANNEL,
59
    DCA_STEREO,
60
    DCA_STEREO_SUMDIFF,
61
    DCA_STEREO_TOTAL,
62
    DCA_3F,
63
    DCA_2F1R,
64
    DCA_3F1R,
65
    DCA_2F2R,
66
    DCA_3F2R,
67
    DCA_4F2R
68
};
69

    
70
#define DCA_DOLBY 101           /* FIXME */
71

    
72
#define DCA_CHANNEL_BITS 6
73
#define DCA_CHANNEL_MASK 0x3F
74

    
75
#define DCA_LFE 0x80
76

    
77
#define HEADER_SIZE 14
78
#define CONVERT_BIAS 384
79

    
80
#define DCA_MAX_FRAME_SIZE 16383
81

    
82
/** Bit allocation */
83
typedef struct {
84
    int offset;                 ///< code values offset
85
    int maxbits[8];             ///< max bits in VLC
86
    int wrap;                   ///< wrap for get_vlc2()
87
    VLC vlc[8];                 ///< actual codes
88
} BitAlloc;
89

    
90
static BitAlloc dca_bitalloc_index;    ///< indexes for samples VLC select
91
static BitAlloc dca_tmode;             ///< transition mode VLCs
92
static BitAlloc dca_scalefactor;       ///< scalefactor VLCs
93
static BitAlloc dca_smpl_bitalloc[11]; ///< samples VLCs
94

    
95
/** Pre-calculated cosine modulation coefs for the QMF */
96
static float cos_mod[544];
97

    
98
static int av_always_inline get_bitalloc(GetBitContext *gb, BitAlloc *ba, int idx)
99
{
100
    return get_vlc2(gb, ba->vlc[idx].table, ba->vlc[idx].bits, ba->wrap) + ba->offset;
101
}
102

    
103
typedef struct {
104
    AVCodecContext *avctx;
105
    /* Frame header */
106
    int frame_type;             ///< type of the current frame
107
    int samples_deficit;        ///< deficit sample count
108
    int crc_present;            ///< crc is present in the bitstream
109
    int sample_blocks;          ///< number of PCM sample blocks
110
    int frame_size;             ///< primary frame byte size
111
    int amode;                  ///< audio channels arrangement
112
    int sample_rate;            ///< audio sampling rate
113
    int bit_rate;               ///< transmission bit rate
114

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

    
134
    /* Primary audio coding header */
135
    int subframes;              ///< number of subframes
136
    int prim_channels;          ///< number of primary audio channels
137
    int subband_activity[DCA_PRIM_CHANNELS_MAX];    ///< subband activity count
138
    int vq_start_subband[DCA_PRIM_CHANNELS_MAX];    ///< high frequency vq start subband
139
    int joint_intensity[DCA_PRIM_CHANNELS_MAX];     ///< joint intensity coding index
140
    int transient_huffman[DCA_PRIM_CHANNELS_MAX];   ///< transient mode code book
141
    int scalefactor_huffman[DCA_PRIM_CHANNELS_MAX]; ///< scale factor code book
142
    int bitalloc_huffman[DCA_PRIM_CHANNELS_MAX];    ///< bit allocation quantizer select
143
    int quant_index_huffman[DCA_PRIM_CHANNELS_MAX][DCA_ABITS_MAX]; ///< quantization index codebook select
144
    float scalefactor_adj[DCA_PRIM_CHANNELS_MAX][DCA_ABITS_MAX];   ///< scale factor adjustment
145

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

    
159
    int high_freq_vq[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];       ///< VQ encoded high frequency subbands
160

    
161
    float lfe_data[2 * DCA_SUBSUBFAMES_MAX * DCA_LFE_MAX *
162
                   2 /*history */ ];    ///< Low frequency effect data
163
    int lfe_scale_factor;
164

    
165
    /* Subband samples history (for ADPCM) */
166
    float subband_samples_hist[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][4];
167
    float subband_fir_hist[DCA_PRIM_CHANNELS_MAX][512];
168
    float subband_fir_noidea[DCA_PRIM_CHANNELS_MAX][64];
169

    
170
    int output;                 ///< type of output
171
    int bias;                   ///< output bias
172

    
173
    DECLARE_ALIGNED_16(float, samples[1536]);  /* 6 * 256 = 1536, might only need 5 */
174
    DECLARE_ALIGNED_16(int16_t, tsamples[1536]);
175

    
176
    uint8_t dca_buffer[DCA_MAX_FRAME_SIZE];
177
    int dca_buffer_size;        ///< how much data is in the dca_buffer
178

    
179
    GetBitContext gb;
180
    /* Current position in DCA frame */
181
    int current_subframe;
182
    int current_subsubframe;
183

    
184
    int debug_flag;             ///< used for suppressing repeated error messages output
185
    DSPContext dsp;
186
} DCAContext;
187

    
188
static void dca_init_vlcs(void)
189
{
190
    static int vlcs_inited = 0;
191
    int i, j;
192

    
193
    if (vlcs_inited)
194
        return;
195

    
196
    dca_bitalloc_index.offset = 1;
197
    dca_bitalloc_index.wrap = 1;
198
    for (i = 0; i < 5; i++)
199
        init_vlc(&dca_bitalloc_index.vlc[i], bitalloc_12_vlc_bits[i], 12,
200
                 bitalloc_12_bits[i], 1, 1,
201
                 bitalloc_12_codes[i], 2, 2, 1);
202
    dca_scalefactor.offset = -64;
203
    dca_scalefactor.wrap = 2;
204
    for (i = 0; i < 5; i++)
205
        init_vlc(&dca_scalefactor.vlc[i], SCALES_VLC_BITS, 129,
206
                 scales_bits[i], 1, 1,
207
                 scales_codes[i], 2, 2, 1);
208
    dca_tmode.offset = 0;
209
    dca_tmode.wrap = 1;
210
    for (i = 0; i < 4; i++)
211
        init_vlc(&dca_tmode.vlc[i], tmode_vlc_bits[i], 4,
212
                 tmode_bits[i], 1, 1,
213
                 tmode_codes[i], 2, 2, 1);
214

    
215
    for(i = 0; i < 10; i++)
216
        for(j = 0; j < 7; j++){
217
            if(!bitalloc_codes[i][j]) break;
218
            dca_smpl_bitalloc[i+1].offset = bitalloc_offsets[i];
219
            dca_smpl_bitalloc[i+1].wrap = 1 + (j > 4);
220
            init_vlc(&dca_smpl_bitalloc[i+1].vlc[j], bitalloc_maxbits[i][j],
221
                     bitalloc_sizes[i],
222
                     bitalloc_bits[i][j], 1, 1,
223
                     bitalloc_codes[i][j], 2, 2, 1);
224
        }
225
    vlcs_inited = 1;
226
}
227

    
228
static inline void get_array(GetBitContext *gb, int *dst, int len, int bits)
229
{
230
    while(len--)
231
        *dst++ = get_bits(gb, bits);
232
}
233

    
234
static int dca_parse_frame_header(DCAContext * s)
235
{
236
    int i, j;
237
    static const float adj_table[4] = { 1.0, 1.1250, 1.2500, 1.4375 };
238
    static const int bitlen[11] = { 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3 };
239
    static const int thr[11] = { 0, 1, 3, 3, 3, 3, 7, 7, 7, 7, 7 };
240

    
241
    s->bias = CONVERT_BIAS;
242

    
243
    init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
244

    
245
    /* Sync code */
246
    get_bits(&s->gb, 32);
247

    
248
    /* Frame header */
249
    s->frame_type        = get_bits(&s->gb, 1);
250
    s->samples_deficit   = get_bits(&s->gb, 5) + 1;
251
    s->crc_present       = get_bits(&s->gb, 1);
252
    s->sample_blocks     = get_bits(&s->gb, 7) + 1;
253
    s->frame_size        = get_bits(&s->gb, 14) + 1;
254
    if (s->frame_size < 95)
255
        return -1;
256
    s->amode             = get_bits(&s->gb, 6);
257
    s->sample_rate       = dca_sample_rates[get_bits(&s->gb, 4)];
258
    if (!s->sample_rate)
259
        return -1;
260
    s->bit_rate          = dca_bit_rates[get_bits(&s->gb, 5)];
261
    if (!s->bit_rate)
262
        return -1;
263

    
264
    s->downmix           = get_bits(&s->gb, 1);
265
    s->dynrange          = get_bits(&s->gb, 1);
266
    s->timestamp         = get_bits(&s->gb, 1);
267
    s->aux_data          = get_bits(&s->gb, 1);
268
    s->hdcd              = get_bits(&s->gb, 1);
269
    s->ext_descr         = get_bits(&s->gb, 3);
270
    s->ext_coding        = get_bits(&s->gb, 1);
271
    s->aspf              = get_bits(&s->gb, 1);
272
    s->lfe               = get_bits(&s->gb, 2);
273
    s->predictor_history = get_bits(&s->gb, 1);
274

    
275
    /* TODO: check CRC */
276
    if (s->crc_present)
277
        s->header_crc    = get_bits(&s->gb, 16);
278

    
279
    s->multirate_inter   = get_bits(&s->gb, 1);
280
    s->version           = get_bits(&s->gb, 4);
281
    s->copy_history      = get_bits(&s->gb, 2);
282
    s->source_pcm_res    = get_bits(&s->gb, 3);
283
    s->front_sum         = get_bits(&s->gb, 1);
284
    s->surround_sum      = get_bits(&s->gb, 1);
285
    s->dialog_norm       = get_bits(&s->gb, 4);
286

    
287
    /* FIXME: channels mixing levels */
288
    s->output = s->amode;
289
    if(s->lfe) s->output |= DCA_LFE;
290

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

    
329
    /* Primary audio coding header */
330
    s->subframes         = get_bits(&s->gb, 4) + 1;
331
    s->prim_channels     = get_bits(&s->gb, 3) + 1;
332

    
333

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

    
349
    /* Get codebooks quantization indexes */
350
    memset(s->quant_index_huffman, 0, sizeof(s->quant_index_huffman));
351
    for (j = 1; j < 11; j++)
352
        for (i = 0; i < s->prim_channels; i++)
353
            s->quant_index_huffman[i][j] = get_bits(&s->gb, bitlen[j]);
354

    
355
    /* Get scale factor adjustment */
356
    for (j = 0; j < 11; j++)
357
        for (i = 0; i < s->prim_channels; i++)
358
            s->scalefactor_adj[i][j] = 1;
359

    
360
    for (j = 1; j < 11; j++)
361
        for (i = 0; i < s->prim_channels; i++)
362
            if (s->quant_index_huffman[i][j] < thr[j])
363
                s->scalefactor_adj[i][j] = adj_table[get_bits(&s->gb, 2)];
364

    
365
    if (s->crc_present) {
366
        /* Audio header CRC check */
367
        get_bits(&s->gb, 16);
368
    }
369

    
370
    s->current_subframe = 0;
371
    s->current_subsubframe = 0;
372

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

    
395
    return 0;
396
}
397

    
398

    
399
static inline int get_scale(GetBitContext *gb, int level, int value)
400
{
401
   if (level < 5) {
402
       /* huffman encoded */
403
       value += get_bitalloc(gb, &dca_scalefactor, level);
404
   } else if(level < 8)
405
       value = get_bits(gb, level + 1);
406
   return value;
407
}
408

    
409
static int dca_subframe_header(DCAContext * s)
410
{
411
    /* Primary audio coding side information */
412
    int j, k;
413

    
414
    s->subsubframes = get_bits(&s->gb, 2) + 1;
415
    s->partial_samples = get_bits(&s->gb, 3);
416
    for (j = 0; j < s->prim_channels; j++) {
417
        for (k = 0; k < s->subband_activity[j]; k++)
418
            s->prediction_mode[j][k] = get_bits(&s->gb, 1);
419
    }
420

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

    
431
    /* Bit allocation index */
432
    for (j = 0; j < s->prim_channels; j++) {
433
        for (k = 0; k < s->vq_start_subband[j]; k++) {
434
            if (s->bitalloc_huffman[j] == 6)
435
                s->bitalloc[j][k] = get_bits(&s->gb, 5);
436
            else if (s->bitalloc_huffman[j] == 5)
437
                s->bitalloc[j][k] = get_bits(&s->gb, 4);
438
            else {
439
                s->bitalloc[j][k] =
440
                    get_bitalloc(&s->gb, &dca_bitalloc_index, s->bitalloc_huffman[j]);
441
            }
442

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
524
    /* Stereo downmix coefficients */
525
    if (s->prim_channels > 2 && 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
    }
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) \
754
     samples[i] += samples[si1]; \
755
     samples[i+256] += samples[si1];
756

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

    
761
#define MIX_FRONT3(samples) \
762
    t = samples[i]; \
763
    samples[i] += samples[i+256]; \
764
    samples[i+256] = samples[i+512] + t;
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
{
774
    int i;
775
    float t;
776

    
777
    switch (srcfmt) {
778
    case DCA_MONO:
779
    case DCA_CHANNEL:
780
    case DCA_STEREO_TOTAL:
781
    case DCA_STEREO_SUMDIFF:
782
    case DCA_4F2R:
783
        av_log(NULL, 0, "Not implemented!\n");
784
        break;
785
    case DCA_STEREO:
786
        break;
787
    case DCA_3F:
788
        DOWNMIX_TO_STEREO(MIX_FRONT3(samples),);
789
        break;
790
    case DCA_2F1R:
791
        DOWNMIX_TO_STEREO(MIX_REAR1(samples, i + 512),);
792
        break;
793
    case DCA_3F1R:
794
        DOWNMIX_TO_STEREO(MIX_FRONT3(samples),
795
                          MIX_REAR1(samples, i + 768));
796
        break;
797
    case DCA_2F2R:
798
        DOWNMIX_TO_STEREO(MIX_REAR2(samples, i + 512, i + 768),);
799
        break;
800
    case DCA_3F2R:
801
        DOWNMIX_TO_STEREO(MIX_FRONT3(samples),
802
                          MIX_REAR2(samples, i + 768, i + 1024));
803
        break;
804
    }
805
}
806

    
807

    
808
/* Very compact version of the block code decoder that does not use table
809
 * look-up but is slightly slower */
810
static int decode_blockcode(int code, int levels, int *values)
811
{
812
    int i;
813
    int offset = (levels - 1) >> 1;
814

    
815
    for (i = 0; i < 4; i++) {
816
        values[i] = (code % levels) - offset;
817
        code /= levels;
818
    }
819

    
820
    if (code == 0)
821
        return 0;
822
    else {
823
        av_log(NULL, AV_LOG_ERROR, "ERROR: block code look-up failed\n");
824
        return -1;
825
    }
826
}
827

    
828
static const uint8_t abits_sizes[7] = { 7, 10, 12, 13, 15, 17, 19 };
829
static const uint8_t abits_levels[7] = { 3, 5, 7, 9, 13, 17, 25 };
830

    
831
static int dca_subsubframe(DCAContext * s)
832
{
833
    int k, l;
834
    int subsubframe = s->current_subsubframe;
835

    
836
    float *quant_step_table;
837

    
838
    /* FIXME */
839
    float subband_samples[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][8];
840

    
841
    /*
842
     * Audio data
843
     */
844

    
845
    /* Select quantization step size table */
846
    if (s->bit_rate == 0x1f)
847
        quant_step_table = (float *) lossless_quant_d;
848
    else
849
        quant_step_table = (float *) lossy_quant_d;
850

    
851
    for (k = 0; k < s->prim_channels; k++) {
852
        for (l = 0; l < s->vq_start_subband[k]; l++) {
853
            int m;
854

    
855
            /* Select the mid-tread linear quantizer */
856
            int abits = s->bitalloc[k][l];
857

    
858
            float quant_step_size = quant_step_table[abits];
859
            float rscale;
860

    
861
            /*
862
             * Determine quantization index code book and its type
863
             */
864

    
865
            /* Select quantization index code book */
866
            int sel = s->quant_index_huffman[k][abits];
867

    
868
            /*
869
             * Extract bits from the bit stream
870
             */
871
            if(!abits){
872
                memset(subband_samples[k][l], 0, 8 * sizeof(subband_samples[0][0][0]));
873
            }else if(abits >= 11 || !dca_smpl_bitalloc[abits].vlc[sel].table){
874
                if(abits <= 7){
875
                    /* Block code */
876
                    int block_code1, block_code2, size, levels;
877
                    int block[8];
878

    
879
                    size = abits_sizes[abits-1];
880
                    levels = abits_levels[abits-1];
881

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

    
900
            /* Deal with transients */
901
            if (s->transition_mode[k][l] &&
902
                subsubframe >= s->transition_mode[k][l])
903
                rscale = quant_step_size * s->scale_factor[k][l][1];
904
            else
905
                rscale = quant_step_size * s->scale_factor[k][l][0];
906

    
907
            rscale *= s->scalefactor_adj[k][sel];
908

    
909
            for (m = 0; m < 8; m++)
910
                subband_samples[k][l][m] *= rscale;
911

    
912
            /*
913
             * Inverse ADPCM if in prediction mode
914
             */
915
            if (s->prediction_mode[k][l]) {
916
                int n;
917
                for (m = 0; m < 8; m++) {
918
                    for (n = 1; n <= 4; n++)
919
                        if (m >= n)
920
                            subband_samples[k][l][m] +=
921
                                (adpcm_vb[s->prediction_vq[k][l]][n - 1] *
922
                                 subband_samples[k][l][m - n] / 8192);
923
                        else if (s->predictor_history)
924
                            subband_samples[k][l][m] +=
925
                                (adpcm_vb[s->prediction_vq[k][l]][n - 1] *
926
                                 s->subband_samples_hist[k][l][m - n +
927
                                                               4] / 8192);
928
                }
929
            }
930
        }
931

    
932
        /*
933
         * Decode VQ encoded high frequencies
934
         */
935
        for (l = s->vq_start_subband[k]; l < s->subband_activity[k]; l++) {
936
            /* 1 vector -> 32 samples but we only need the 8 samples
937
             * for this subsubframe. */
938
            int m;
939

    
940
            if (!s->debug_flag & 0x01) {
941
                av_log(s->avctx, AV_LOG_DEBUG, "Stream with high frequencies VQ coding\n");
942
                s->debug_flag |= 0x01;
943
            }
944

    
945
            for (m = 0; m < 8; m++) {
946
                subband_samples[k][l][m] =
947
                    high_freq_vq[s->high_freq_vq[k][l]][subsubframe * 8 +
948
                                                        m]
949
                    * (float) s->scale_factor[k][l][0] / 16.0;
950
            }
951
        }
952
    }
953

    
954
    /* Check for DSYNC after subsubframe */
955
    if (s->aspf || subsubframe == s->subsubframes - 1) {
956
        if (0xFFFF == get_bits(&s->gb, 16)) {   /* 0xFFFF */
957
#ifdef TRACE
958
            av_log(s->avctx, AV_LOG_DEBUG, "Got subframe DSYNC\n");
959
#endif
960
        } else {
961
            av_log(s->avctx, AV_LOG_ERROR, "Didn't get subframe DSYNC\n");
962
        }
963
    }
964

    
965
    /* Backup predictor history for adpcm */
966
    for (k = 0; k < s->prim_channels; k++)
967
        for (l = 0; l < s->vq_start_subband[k]; l++)
968
            memcpy(s->subband_samples_hist[k][l], &subband_samples[k][l][4],
969
                        4 * sizeof(subband_samples[0][0][0]));
970

    
971
    /* 32 subbands QMF */
972
    for (k = 0; k < s->prim_channels; k++) {
973
/*        static float pcm_to_double[8] =
974
            {32768.0, 32768.0, 524288.0, 524288.0, 0, 8388608.0, 8388608.0};*/
975
         qmf_32_subbands(s, k, subband_samples[k], &s->samples[256 * k],
976
                            2.0 / 3 /*pcm_to_double[s->source_pcm_res] */ ,
977
                            0 /*s->bias */ );
978
    }
979

    
980
    /* Down mixing */
981

    
982
    if (s->prim_channels > dca_channels[s->output & DCA_CHANNEL_MASK]) {
983
        dca_downmix(s->samples, s->amode);
984
    }
985

    
986
    /* Generate LFE samples for this subsubframe FIXME!!! */
987
    if (s->output & DCA_LFE) {
988
        int lfe_samples = 2 * s->lfe * s->subsubframes;
989
        int i_channels = dca_channels[s->output & DCA_CHANNEL_MASK];
990

    
991
        lfe_interpolation_fir(s->lfe, 2 * s->lfe,
992
                              s->lfe_data + lfe_samples +
993
                              2 * s->lfe * subsubframe,
994
                              &s->samples[256 * i_channels],
995
                              8388608.0, s->bias);
996
        /* Outputs 20bits pcm samples */
997
    }
998

    
999
    return 0;
1000
}
1001

    
1002

    
1003
static int dca_subframe_footer(DCAContext * s)
1004
{
1005
    int aux_data_count = 0, i;
1006
    int lfe_samples;
1007

    
1008
    /*
1009
     * Unpack optional information
1010
     */
1011

    
1012
    if (s->timestamp)
1013
        get_bits(&s->gb, 32);
1014

    
1015
    if (s->aux_data)
1016
        aux_data_count = get_bits(&s->gb, 6);
1017

    
1018
    for (i = 0; i < aux_data_count; i++)
1019
        get_bits(&s->gb, 8);
1020

    
1021
    if (s->crc_present && (s->downmix || s->dynrange))
1022
        get_bits(&s->gb, 16);
1023

    
1024
    lfe_samples = 2 * s->lfe * s->subsubframes;
1025
    for (i = 0; i < lfe_samples; i++) {
1026
        s->lfe_data[i] = s->lfe_data[i + lfe_samples];
1027
    }
1028

    
1029
    return 0;
1030
}
1031

    
1032
/**
1033
 * Decode a dca frame block
1034
 *
1035
 * @param s     pointer to the DCAContext
1036
 */
1037

    
1038
static int dca_decode_block(DCAContext * s)
1039
{
1040

    
1041
    /* Sanity check */
1042
    if (s->current_subframe >= s->subframes) {
1043
        av_log(s->avctx, AV_LOG_DEBUG, "check failed: %i>%i",
1044
               s->current_subframe, s->subframes);
1045
        return -1;
1046
    }
1047

    
1048
    if (!s->current_subsubframe) {
1049
#ifdef TRACE
1050
        av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subframe_header\n");
1051
#endif
1052
        /* Read subframe header */
1053
        if (dca_subframe_header(s))
1054
            return -1;
1055
    }
1056

    
1057
    /* Read subsubframe */
1058
#ifdef TRACE
1059
    av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subsubframe\n");
1060
#endif
1061
    if (dca_subsubframe(s))
1062
        return -1;
1063

    
1064
    /* Update state */
1065
    s->current_subsubframe++;
1066
    if (s->current_subsubframe >= s->subsubframes) {
1067
        s->current_subsubframe = 0;
1068
        s->current_subframe++;
1069
    }
1070
    if (s->current_subframe >= s->subframes) {
1071
#ifdef TRACE
1072
        av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subframe_footer\n");
1073
#endif
1074
        /* Read subframe footer */
1075
        if (dca_subframe_footer(s))
1076
            return -1;
1077
    }
1078

    
1079
    return 0;
1080
}
1081

    
1082
/**
1083
 * Convert bitstream to one representation based on sync marker
1084
 */
1085
static int dca_convert_bitstream(uint8_t * src, int src_size, uint8_t * dst,
1086
                          int max_size)
1087
{
1088
    uint32_t mrk;
1089
    int i, tmp;
1090
    uint16_t *ssrc = (uint16_t *) src, *sdst = (uint16_t *) dst;
1091
    PutBitContext pb;
1092

    
1093
    if((unsigned)src_size > (unsigned)max_size)
1094
        return -1;
1095

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

    
1119
/**
1120
 * Main frame decoding function
1121
 * FIXME add arguments
1122
 */
1123
static int dca_decode_frame(AVCodecContext * avctx,
1124
                            void *data, int *data_size,
1125
                            uint8_t * buf, int buf_size)
1126
{
1127

    
1128
    int i, j, k;
1129
    int16_t *samples = data;
1130
    DCAContext *s = avctx->priv_data;
1131
    int channels;
1132

    
1133

    
1134
    s->dca_buffer_size = dca_convert_bitstream(buf, buf_size, s->dca_buffer, DCA_MAX_FRAME_SIZE);
1135
    if (s->dca_buffer_size == -1) {
1136
        av_log(avctx, AV_LOG_ERROR, "Not a DCA frame\n");
1137
        return -1;
1138
    }
1139

    
1140
    init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
1141
    if (dca_parse_frame_header(s) < 0) {
1142
        //seems like the frame is corrupt, try with the next one
1143
        return buf_size;
1144
    }
1145
    //set AVCodec values with parsed data
1146
    avctx->sample_rate = s->sample_rate;
1147
    avctx->bit_rate = s->bit_rate;
1148

    
1149
    channels = s->prim_channels + !!s->lfe;
1150
    if(avctx->channels == 0) {
1151
        avctx->channels = channels;
1152
    } else if(channels < avctx->channels) {
1153
        av_log(avctx, AV_LOG_WARNING, "DTS source channels are less than "
1154
               "specified: output to %d channels.\n", channels);
1155
        avctx->channels = channels;
1156
    }
1157
    if(avctx->channels == 2) {
1158
        s->output = DCA_STEREO;
1159
    } else if(avctx->channels != channels) {
1160
        av_log(avctx, AV_LOG_ERROR, "Cannot downmix DTS to %d channels.\n",
1161
               avctx->channels);
1162
        return -1;
1163
    }
1164

    
1165
    channels = avctx->channels;
1166
    if(*data_size < (s->sample_blocks / 8) * 256 * sizeof(int16_t) * channels)
1167
        return -1;
1168
    *data_size = 0;
1169
    for (i = 0; i < (s->sample_blocks / 8); i++) {
1170
        dca_decode_block(s);
1171
        s->dsp.float_to_int16(s->tsamples, s->samples, 256 * channels);
1172
        /* interleave samples */
1173
        for (j = 0; j < 256; j++) {
1174
            for (k = 0; k < channels; k++)
1175
                samples[k] = s->tsamples[j + k * 256];
1176
            samples += channels;
1177
        }
1178
        *data_size += 256 * sizeof(int16_t) * channels;
1179
    }
1180

    
1181
    return buf_size;
1182
}
1183

    
1184

    
1185

    
1186
/**
1187
 * Build the cosine modulation tables for the QMF
1188
 *
1189
 * @param s     pointer to the DCAContext
1190
 */
1191

    
1192
static void pre_calc_cosmod(DCAContext * s)
1193
{
1194
    int i, j, k;
1195
    static int cosmod_inited = 0;
1196

    
1197
    if(cosmod_inited) return;
1198
    for (j = 0, k = 0; k < 16; k++)
1199
        for (i = 0; i < 16; i++)
1200
            cos_mod[j++] = cos((2 * i + 1) * (2 * k + 1) * M_PI / 64);
1201

    
1202
    for (k = 0; k < 16; k++)
1203
        for (i = 0; i < 16; i++)
1204
            cos_mod[j++] = cos((i) * (2 * k + 1) * M_PI / 32);
1205

    
1206
    for (k = 0; k < 16; k++)
1207
        cos_mod[j++] = 0.25 / (2 * cos((2 * k + 1) * M_PI / 128));
1208

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

    
1212
    cosmod_inited = 1;
1213
}
1214

    
1215

    
1216
/**
1217
 * DCA initialization
1218
 *
1219
 * @param avctx     pointer to the AVCodecContext
1220
 */
1221

    
1222
static int dca_decode_init(AVCodecContext * avctx)
1223
{
1224
    DCAContext *s = avctx->priv_data;
1225

    
1226
    s->avctx = avctx;
1227
    dca_init_vlcs();
1228
    pre_calc_cosmod(s);
1229

    
1230
    dsputil_init(&s->dsp, avctx);
1231
    return 0;
1232
}
1233

    
1234

    
1235
AVCodec dca_decoder = {
1236
    .name = "dca",
1237
    .type = CODEC_TYPE_AUDIO,
1238
    .id = CODEC_ID_DTS,
1239
    .priv_data_size = sizeof(DCAContext),
1240
    .init = dca_decode_init,
1241
    .decode = dca_decode_frame,
1242
};
1243

    
1244
#ifdef CONFIG_DCA_PARSER
1245

    
1246
typedef struct DCAParseContext {
1247
    ParseContext pc;
1248
    uint32_t lastmarker;
1249
} DCAParseContext;
1250

    
1251
#define IS_MARKER(state, i, buf, buf_size) \
1252
 ((state == DCA_MARKER_14B_LE && (i < buf_size-2) && (buf[i+1] & 0xF0) == 0xF0 && buf[i+2] == 0x07) \
1253
 || (state == DCA_MARKER_14B_BE && (i < buf_size-2) && buf[i+1] == 0x07 && (buf[i+2] & 0xF0) == 0xF0) \
1254
 || state == DCA_MARKER_RAW_LE || state == DCA_MARKER_RAW_BE)
1255

    
1256
/**
1257
 * finds the end of the current frame in the bitstream.
1258
 * @return the position of the first byte of the next frame, or -1
1259
 */
1260
static int dca_find_frame_end(DCAParseContext * pc1, const uint8_t * buf,
1261
                              int buf_size)
1262
{
1263
    int start_found, i;
1264
    uint32_t state;
1265
    ParseContext *pc = &pc1->pc;
1266

    
1267
    start_found = pc->frame_start_found;
1268
    state = pc->state;
1269

    
1270
    i = 0;
1271
    if (!start_found) {
1272
        for (i = 0; i < buf_size; i++) {
1273
            state = (state << 8) | buf[i];
1274
            if (IS_MARKER(state, i, buf, buf_size)) {
1275
                if (pc1->lastmarker && state == pc1->lastmarker) {
1276
                    start_found = 1;
1277
                    break;
1278
                } else if (!pc1->lastmarker) {
1279
                    start_found = 1;
1280
                    pc1->lastmarker = state;
1281
                    break;
1282
                }
1283
            }
1284
        }
1285
    }
1286
    if (start_found) {
1287
        for (; i < buf_size; i++) {
1288
            state = (state << 8) | buf[i];
1289
            if (state == pc1->lastmarker && IS_MARKER(state, i, buf, buf_size)) {
1290
                pc->frame_start_found = 0;
1291
                pc->state = -1;
1292
                return i - 3;
1293
            }
1294
        }
1295
    }
1296
    pc->frame_start_found = start_found;
1297
    pc->state = state;
1298
    return END_NOT_FOUND;
1299
}
1300

    
1301
static int dca_parse_init(AVCodecParserContext * s)
1302
{
1303
    DCAParseContext *pc1 = s->priv_data;
1304

    
1305
    pc1->lastmarker = 0;
1306
    return 0;
1307
}
1308

    
1309
static int dca_parse(AVCodecParserContext * s,
1310
                     AVCodecContext * avctx,
1311
                     uint8_t ** poutbuf, int *poutbuf_size,
1312
                     const uint8_t * buf, int buf_size)
1313
{
1314
    DCAParseContext *pc1 = s->priv_data;
1315
    ParseContext *pc = &pc1->pc;
1316
    int next;
1317

    
1318
    if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
1319
        next = buf_size;
1320
    } else {
1321
        next = dca_find_frame_end(pc1, buf, buf_size);
1322

    
1323
        if (ff_combine_frame(pc, next, (uint8_t **) & buf, &buf_size) < 0) {
1324
            *poutbuf = NULL;
1325
            *poutbuf_size = 0;
1326
            return buf_size;
1327
        }
1328
    }
1329
    *poutbuf = (uint8_t *) buf;
1330
    *poutbuf_size = buf_size;
1331
    return next;
1332
}
1333

    
1334
AVCodecParser dca_parser = {
1335
    {CODEC_ID_DTS},
1336
    sizeof(DCAParseContext),
1337
    dca_parse_init,
1338
    dca_parse,
1339
    ff_parse_close,
1340
};
1341
#endif /* CONFIG_DCA_PARSER */