Statistics
| Branch: | Revision:

ffmpeg / libavcodec / dca.c @ d1177cb5

History | View | Annotate | Download (53.8 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
#include <math.h>
26
#include <stddef.h>
27
#include <stdio.h>
28

    
29
#include "libavutil/intmath.h"
30
#include "libavutil/intreadwrite.h"
31
#include "avcodec.h"
32
#include "dsputil.h"
33
#include "fft.h"
34
#include "get_bits.h"
35
#include "put_bits.h"
36
#include "dcadata.h"
37
#include "dcahuff.h"
38
#include "dca.h"
39
#include "synth_filter.h"
40
#include "dcadsp.h"
41

    
42
//#define TRACE
43

    
44
#define DCA_PRIM_CHANNELS_MAX (7)
45
#define DCA_SUBBANDS (32)
46
#define DCA_ABITS_MAX (32)      /* Should be 28 */
47
#define DCA_SUBSUBFRAMES_MAX (4)
48
#define DCA_SUBFRAMES_MAX (16)
49
#define DCA_BLOCKS_MAX (16)
50
#define DCA_LFE_MAX (3)
51

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

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

    
76
static const int64_t dca_core_channel_layout[] = {
77
    CH_FRONT_CENTER,                                               ///< 1, A
78
    CH_LAYOUT_STEREO,                                              ///< 2, A + B (dual mono)
79
    CH_LAYOUT_STEREO,                                              ///< 2, L + R (stereo)
80
    CH_LAYOUT_STEREO,                                              ///< 2, (L+R) + (L-R) (sum-difference)
81
    CH_LAYOUT_STEREO,                                              ///< 2, LT +RT (left and right total)
82
    CH_LAYOUT_STEREO|CH_FRONT_CENTER,                              ///< 3, C+L+R
83
    CH_LAYOUT_STEREO|CH_BACK_CENTER,                               ///< 3, L+R+S
84
    CH_LAYOUT_STEREO|CH_FRONT_CENTER|CH_BACK_CENTER,               ///< 4, C + L + R+ S
85
    CH_LAYOUT_STEREO|CH_SIDE_LEFT|CH_SIDE_RIGHT,                   ///< 4, L + R +SL+ SR
86
    CH_LAYOUT_STEREO|CH_FRONT_CENTER|CH_SIDE_LEFT|CH_SIDE_RIGHT,   ///< 5, C + L + R+ SL+SR
87
    CH_LAYOUT_STEREO|CH_SIDE_LEFT|CH_SIDE_RIGHT|CH_FRONT_LEFT_OF_CENTER|CH_FRONT_RIGHT_OF_CENTER,                 ///< 6, CL + CR + L + R + SL + SR
88
    CH_LAYOUT_STEREO|CH_BACK_LEFT|CH_BACK_RIGHT|CH_FRONT_CENTER|CH_BACK_CENTER,                                   ///< 6, C + L + R+ LR + RR + OV
89
    CH_FRONT_CENTER|CH_FRONT_RIGHT_OF_CENTER|CH_FRONT_LEFT_OF_CENTER|CH_BACK_CENTER|CH_BACK_LEFT|CH_BACK_RIGHT,   ///< 6, CF+ CR+LF+ RF+LR + RR
90
    CH_FRONT_LEFT_OF_CENTER|CH_FRONT_CENTER|CH_FRONT_RIGHT_OF_CENTER|CH_LAYOUT_STEREO|CH_SIDE_LEFT|CH_SIDE_RIGHT, ///< 7, CL + C + CR + L + R + SL + SR
91
    CH_FRONT_LEFT_OF_CENTER|CH_FRONT_RIGHT_OF_CENTER|CH_LAYOUT_STEREO|CH_SIDE_LEFT|CH_SIDE_RIGHT|CH_BACK_LEFT|CH_BACK_RIGHT, ///< 8, CL + CR + L + R + SL1 + SL2+ SR1 + SR2
92
    CH_FRONT_LEFT_OF_CENTER|CH_FRONT_CENTER|CH_FRONT_RIGHT_OF_CENTER|CH_LAYOUT_STEREO|CH_SIDE_LEFT|CH_BACK_CENTER|CH_SIDE_RIGHT, ///< 8, CL + C+ CR + L + R + SL + S+ SR
93
};
94

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

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

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

    
137
static const int8_t dca_channel_reorder_nolfe[][9] = {
138
    { 0, -1, -1, -1, -1, -1, -1, -1, -1},
139
    { 0,  1, -1, -1, -1, -1, -1, -1, -1},
140
    { 0,  1, -1, -1, -1, -1, -1, -1, -1},
141
    { 0,  1, -1, -1, -1, -1, -1, -1, -1},
142
    { 0,  1, -1, -1, -1, -1, -1, -1, -1},
143
    { 2,  0,  1, -1, -1, -1, -1, -1, -1},
144
    { 0,  1,  2, -1, -1, -1, -1, -1, -1},
145
    { 2,  0,  1,  3, -1, -1, -1, -1, -1},
146
    { 0,  1,  2,  3, -1, -1, -1, -1, -1},
147
    { 2,  0,  1,  3,  4, -1, -1, -1, -1},
148
    { 2,  3,  0,  1,  4,  5, -1, -1, -1},
149
    { 2,  0,  1,  3,  4,  5, -1, -1, -1},
150
    { 0,  5,  3,  4,  1,  2, -1, -1, -1},
151
    { 3,  2,  4,  0,  1,  5,  6, -1, -1},
152
    { 4,  5,  0,  1,  6,  2,  7,  3, -1},
153
    { 3,  2,  4,  0,  1,  5,  7,  6, -1},
154
};
155

    
156
static const int8_t dca_channel_reorder_nolfe_xch[][9] = {
157
    { 0,  1, -1, -1, -1, -1, -1, -1, -1},
158
    { 0,  1,  2, -1, -1, -1, -1, -1, -1},
159
    { 0,  1,  2, -1, -1, -1, -1, -1, -1},
160
    { 0,  1,  2, -1, -1, -1, -1, -1, -1},
161
    { 0,  1,  2, -1, -1, -1, -1, -1, -1},
162
    { 2,  0,  1,  3, -1, -1, -1, -1, -1},
163
    { 0,  1,  2,  3, -1, -1, -1, -1, -1},
164
    { 2,  0,  1,  3,  4, -1, -1, -1, -1},
165
    { 0,  1,  3,  4,  2, -1, -1, -1, -1},
166
    { 2,  0,  1,  4,  5,  3, -1, -1, -1},
167
    { 2,  3,  0,  1,  5,  6,  4, -1, -1},
168
    { 2,  0,  1,  3,  4,  5,  6, -1, -1},
169
    { 0,  5,  3,  4,  1,  2,  6, -1, -1},
170
    { 3,  2,  4,  0,  1,  6,  7,  5, -1},
171
    { 4,  5,  0,  1,  7,  2,  8,  3,  6},
172
    { 3,  2,  4,  0,  1,  5,  8,  7,  6},
173
};
174

    
175
#define DCA_DOLBY 101           /* FIXME */
176

    
177
#define DCA_CHANNEL_BITS 6
178
#define DCA_CHANNEL_MASK 0x3F
179

    
180
#define DCA_LFE 0x80
181

    
182
#define HEADER_SIZE 14
183

    
184
#define DCA_MAX_FRAME_SIZE 16384
185

    
186
/** Bit allocation */
187
typedef struct {
188
    int offset;                 ///< code values offset
189
    int maxbits[8];             ///< max bits in VLC
190
    int wrap;                   ///< wrap for get_vlc2()
191
    VLC vlc[8];                 ///< actual codes
192
} BitAlloc;
193

    
194
static BitAlloc dca_bitalloc_index;    ///< indexes for samples VLC select
195
static BitAlloc dca_tmode;             ///< transition mode VLCs
196
static BitAlloc dca_scalefactor;       ///< scalefactor VLCs
197
static BitAlloc dca_smpl_bitalloc[11]; ///< samples VLCs
198

    
199
static av_always_inline int get_bitalloc(GetBitContext *gb, BitAlloc *ba, int idx)
200
{
201
    return get_vlc2(gb, ba->vlc[idx].table, ba->vlc[idx].bits, ba->wrap) + ba->offset;
202
}
203

    
204
typedef struct {
205
    AVCodecContext *avctx;
206
    /* Frame header */
207
    int frame_type;             ///< type of the current frame
208
    int samples_deficit;        ///< deficit sample count
209
    int crc_present;            ///< crc is present in the bitstream
210
    int sample_blocks;          ///< number of PCM sample blocks
211
    int frame_size;             ///< primary frame byte size
212
    int amode;                  ///< audio channels arrangement
213
    int sample_rate;            ///< audio sampling rate
214
    int bit_rate;               ///< transmission bit rate
215
    int bit_rate_index;         ///< transmission bit rate index
216

    
217
    int downmix;                ///< embedded downmix enabled
218
    int dynrange;               ///< embedded dynamic range flag
219
    int timestamp;              ///< embedded time stamp flag
220
    int aux_data;               ///< auxiliary data flag
221
    int hdcd;                   ///< source material is mastered in HDCD
222
    int ext_descr;              ///< extension audio descriptor flag
223
    int ext_coding;             ///< extended coding flag
224
    int aspf;                   ///< audio sync word insertion flag
225
    int lfe;                    ///< low frequency effects flag
226
    int predictor_history;      ///< predictor history flag
227
    int header_crc;             ///< header crc check bytes
228
    int multirate_inter;        ///< multirate interpolator switch
229
    int version;                ///< encoder software revision
230
    int copy_history;           ///< copy history
231
    int source_pcm_res;         ///< source pcm resolution
232
    int front_sum;              ///< front sum/difference flag
233
    int surround_sum;           ///< surround sum/difference flag
234
    int dialog_norm;            ///< dialog normalisation parameter
235

    
236
    /* Primary audio coding header */
237
    int subframes;              ///< number of subframes
238
    int total_channels;         ///< number of channels including extensions
239
    int prim_channels;          ///< number of primary audio channels
240
    int subband_activity[DCA_PRIM_CHANNELS_MAX];    ///< subband activity count
241
    int vq_start_subband[DCA_PRIM_CHANNELS_MAX];    ///< high frequency vq start subband
242
    int joint_intensity[DCA_PRIM_CHANNELS_MAX];     ///< joint intensity coding index
243
    int transient_huffman[DCA_PRIM_CHANNELS_MAX];   ///< transient mode code book
244
    int scalefactor_huffman[DCA_PRIM_CHANNELS_MAX]; ///< scale factor code book
245
    int bitalloc_huffman[DCA_PRIM_CHANNELS_MAX];    ///< bit allocation quantizer select
246
    int quant_index_huffman[DCA_PRIM_CHANNELS_MAX][DCA_ABITS_MAX]; ///< quantization index codebook select
247
    float scalefactor_adj[DCA_PRIM_CHANNELS_MAX][DCA_ABITS_MAX];   ///< scale factor adjustment
248

    
249
    /* Primary audio coding side information */
250
    int subsubframes[DCA_SUBFRAMES_MAX];           ///< number of subsubframes
251
    int partial_samples[DCA_SUBFRAMES_MAX];        ///< partial subsubframe samples count
252
    int prediction_mode[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];    ///< prediction mode (ADPCM used or not)
253
    int prediction_vq[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];      ///< prediction VQ coefs
254
    int bitalloc[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];           ///< bit allocation index
255
    int transition_mode[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];    ///< transition mode (transients)
256
    int scale_factor[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][2];    ///< scale factors (2 if transient)
257
    int joint_huff[DCA_PRIM_CHANNELS_MAX];                       ///< joint subband scale factors codebook
258
    int joint_scale_factor[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS]; ///< joint subband scale factors
259
    int downmix_coef[DCA_PRIM_CHANNELS_MAX][2];                  ///< stereo downmix coefficients
260
    int dynrange_coef;                                           ///< dynamic range coefficient
261

    
262
    int high_freq_vq[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS];       ///< VQ encoded high frequency subbands
263

    
264
    float lfe_data[2 * DCA_LFE_MAX * (DCA_BLOCKS_MAX + 4)];      ///< Low frequency effect data
265
    int lfe_scale_factor;
266

    
267
    /* Subband samples history (for ADPCM) */
268
    float subband_samples_hist[DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][4];
269
    DECLARE_ALIGNED(16, float, subband_fir_hist)[DCA_PRIM_CHANNELS_MAX][512];
270
    DECLARE_ALIGNED(16, float, subband_fir_noidea)[DCA_PRIM_CHANNELS_MAX][32];
271
    int hist_index[DCA_PRIM_CHANNELS_MAX];
272
    DECLARE_ALIGNED(16, float, raXin)[32];
273

    
274
    int output;                 ///< type of output
275
    float add_bias;             ///< output bias
276
    float scale_bias;           ///< output scale
277

    
278
    DECLARE_ALIGNED(16, float, subband_samples)[DCA_BLOCKS_MAX][DCA_PRIM_CHANNELS_MAX][DCA_SUBBANDS][8];
279
    DECLARE_ALIGNED(16, float, samples)[(DCA_PRIM_CHANNELS_MAX+1)*256];
280
    const float *samples_chanptr[DCA_PRIM_CHANNELS_MAX+1];
281

    
282
    uint8_t dca_buffer[DCA_MAX_FRAME_SIZE];
283
    int dca_buffer_size;        ///< how much data is in the dca_buffer
284

    
285
    const int8_t* channel_order_tab;                             ///< channel reordering table, lfe and non lfe
286
    GetBitContext gb;
287
    /* Current position in DCA frame */
288
    int current_subframe;
289
    int current_subsubframe;
290

    
291
    int debug_flag;             ///< used for suppressing repeated error messages output
292
    DSPContext dsp;
293
    FFTContext imdct;
294
    SynthFilterContext synth;
295
    DCADSPContext dcadsp;
296
} DCAContext;
297

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

    
307
static av_cold void dca_init_vlcs(void)
308
{
309
    static int vlcs_initialized = 0;
310
    int i, j, c = 14;
311
    static VLC_TYPE dca_table[23622][2];
312

    
313
    if (vlcs_initialized)
314
        return;
315

    
316
    dca_bitalloc_index.offset = 1;
317
    dca_bitalloc_index.wrap = 2;
318
    for (i = 0; i < 5; i++) {
319
        dca_bitalloc_index.vlc[i].table = &dca_table[dca_vlc_offs[i]];
320
        dca_bitalloc_index.vlc[i].table_allocated = dca_vlc_offs[i + 1] - dca_vlc_offs[i];
321
        init_vlc(&dca_bitalloc_index.vlc[i], bitalloc_12_vlc_bits[i], 12,
322
                 bitalloc_12_bits[i], 1, 1,
323
                 bitalloc_12_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
324
    }
325
    dca_scalefactor.offset = -64;
326
    dca_scalefactor.wrap = 2;
327
    for (i = 0; i < 5; i++) {
328
        dca_scalefactor.vlc[i].table = &dca_table[dca_vlc_offs[i + 5]];
329
        dca_scalefactor.vlc[i].table_allocated = dca_vlc_offs[i + 6] - dca_vlc_offs[i + 5];
330
        init_vlc(&dca_scalefactor.vlc[i], SCALES_VLC_BITS, 129,
331
                 scales_bits[i], 1, 1,
332
                 scales_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
333
    }
334
    dca_tmode.offset = 0;
335
    dca_tmode.wrap = 1;
336
    for (i = 0; i < 4; i++) {
337
        dca_tmode.vlc[i].table = &dca_table[dca_vlc_offs[i + 10]];
338
        dca_tmode.vlc[i].table_allocated = dca_vlc_offs[i + 11] - dca_vlc_offs[i + 10];
339
        init_vlc(&dca_tmode.vlc[i], tmode_vlc_bits[i], 4,
340
                 tmode_bits[i], 1, 1,
341
                 tmode_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);
342
    }
343

    
344
    for (i = 0; i < 10; i++)
345
        for (j = 0; j < 7; j++){
346
            if (!bitalloc_codes[i][j]) break;
347
            dca_smpl_bitalloc[i+1].offset = bitalloc_offsets[i];
348
            dca_smpl_bitalloc[i+1].wrap = 1 + (j > 4);
349
            dca_smpl_bitalloc[i+1].vlc[j].table = &dca_table[dca_vlc_offs[c]];
350
            dca_smpl_bitalloc[i+1].vlc[j].table_allocated = dca_vlc_offs[c + 1] - dca_vlc_offs[c];
351
            init_vlc(&dca_smpl_bitalloc[i+1].vlc[j], bitalloc_maxbits[i][j],
352
                     bitalloc_sizes[i],
353
                     bitalloc_bits[i][j], 1, 1,
354
                     bitalloc_codes[i][j], 2, 2, INIT_VLC_USE_NEW_STATIC);
355
            c++;
356
        }
357
    vlcs_initialized = 1;
358
}
359

    
360
static inline void get_array(GetBitContext *gb, int *dst, int len, int bits)
361
{
362
    while(len--)
363
        *dst++ = get_bits(gb, bits);
364
}
365

    
366
static int dca_parse_audio_coding_header(DCAContext * s, int base_channel)
367
{
368
    int i, j;
369
    static const float adj_table[4] = { 1.0, 1.1250, 1.2500, 1.4375 };
370
    static const int bitlen[11] = { 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3 };
371
    static const int thr[11] = { 0, 1, 3, 3, 3, 3, 7, 7, 7, 7, 7 };
372

    
373
    s->total_channels    = get_bits(&s->gb, 3) + 1 + base_channel;
374
    s->prim_channels     = s->total_channels;
375

    
376
    if (s->prim_channels > DCA_PRIM_CHANNELS_MAX)
377
        s->prim_channels = DCA_PRIM_CHANNELS_MAX;
378

    
379

    
380
    for (i = base_channel; i < s->prim_channels; i++) {
381
        s->subband_activity[i] = get_bits(&s->gb, 5) + 2;
382
        if (s->subband_activity[i] > DCA_SUBBANDS)
383
            s->subband_activity[i] = DCA_SUBBANDS;
384
    }
385
    for (i = base_channel; i < s->prim_channels; i++) {
386
        s->vq_start_subband[i] = get_bits(&s->gb, 5) + 1;
387
        if (s->vq_start_subband[i] > DCA_SUBBANDS)
388
            s->vq_start_subband[i] = DCA_SUBBANDS;
389
    }
390
    get_array(&s->gb, s->joint_intensity + base_channel,     s->prim_channels - base_channel, 3);
391
    get_array(&s->gb, s->transient_huffman + base_channel,   s->prim_channels - base_channel, 2);
392
    get_array(&s->gb, s->scalefactor_huffman + base_channel, s->prim_channels - base_channel, 3);
393
    get_array(&s->gb, s->bitalloc_huffman + base_channel,    s->prim_channels - base_channel, 3);
394

    
395
    /* Get codebooks quantization indexes */
396
    if (!base_channel)
397
        memset(s->quant_index_huffman, 0, sizeof(s->quant_index_huffman));
398
    for (j = 1; j < 11; j++)
399
        for (i = base_channel; i < s->prim_channels; i++)
400
            s->quant_index_huffman[i][j] = get_bits(&s->gb, bitlen[j]);
401

    
402
    /* Get scale factor adjustment */
403
    for (j = 0; j < 11; j++)
404
        for (i = base_channel; i < s->prim_channels; i++)
405
            s->scalefactor_adj[i][j] = 1;
406

    
407
    for (j = 1; j < 11; j++)
408
        for (i = base_channel; i < s->prim_channels; i++)
409
            if (s->quant_index_huffman[i][j] < thr[j])
410
                s->scalefactor_adj[i][j] = adj_table[get_bits(&s->gb, 2)];
411

    
412
    if (s->crc_present) {
413
        /* Audio header CRC check */
414
        get_bits(&s->gb, 16);
415
    }
416

    
417
    s->current_subframe = 0;
418
    s->current_subsubframe = 0;
419

    
420
#ifdef TRACE
421
    av_log(s->avctx, AV_LOG_DEBUG, "subframes: %i\n", s->subframes);
422
    av_log(s->avctx, AV_LOG_DEBUG, "prim channels: %i\n", s->prim_channels);
423
    for (i = base_channel; i < s->prim_channels; i++){
424
        av_log(s->avctx, AV_LOG_DEBUG, "subband activity: %i\n", s->subband_activity[i]);
425
        av_log(s->avctx, AV_LOG_DEBUG, "vq start subband: %i\n", s->vq_start_subband[i]);
426
        av_log(s->avctx, AV_LOG_DEBUG, "joint intensity: %i\n", s->joint_intensity[i]);
427
        av_log(s->avctx, AV_LOG_DEBUG, "transient mode codebook: %i\n", s->transient_huffman[i]);
428
        av_log(s->avctx, AV_LOG_DEBUG, "scale factor codebook: %i\n", s->scalefactor_huffman[i]);
429
        av_log(s->avctx, AV_LOG_DEBUG, "bit allocation quantizer: %i\n", s->bitalloc_huffman[i]);
430
        av_log(s->avctx, AV_LOG_DEBUG, "quant index huff:");
431
        for (j = 0; j < 11; j++)
432
            av_log(s->avctx, AV_LOG_DEBUG, " %i",
433
                   s->quant_index_huffman[i][j]);
434
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
435
        av_log(s->avctx, AV_LOG_DEBUG, "scalefac adj:");
436
        for (j = 0; j < 11; j++)
437
            av_log(s->avctx, AV_LOG_DEBUG, " %1.3f", s->scalefactor_adj[i][j]);
438
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
439
    }
440
#endif
441

    
442
  return 0;
443
}
444

    
445
static int dca_parse_frame_header(DCAContext * s)
446
{
447
    init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
448

    
449
    /* Sync code */
450
    get_bits(&s->gb, 32);
451

    
452
    /* Frame header */
453
    s->frame_type        = get_bits(&s->gb, 1);
454
    s->samples_deficit   = get_bits(&s->gb, 5) + 1;
455
    s->crc_present       = get_bits(&s->gb, 1);
456
    s->sample_blocks     = get_bits(&s->gb, 7) + 1;
457
    s->frame_size        = get_bits(&s->gb, 14) + 1;
458
    if (s->frame_size < 95)
459
        return -1;
460
    s->amode             = get_bits(&s->gb, 6);
461
    s->sample_rate       = dca_sample_rates[get_bits(&s->gb, 4)];
462
    if (!s->sample_rate)
463
        return -1;
464
    s->bit_rate_index    = get_bits(&s->gb, 5);
465
    s->bit_rate          = dca_bit_rates[s->bit_rate_index];
466
    if (!s->bit_rate)
467
        return -1;
468

    
469
    s->downmix           = get_bits(&s->gb, 1);
470
    s->dynrange          = get_bits(&s->gb, 1);
471
    s->timestamp         = get_bits(&s->gb, 1);
472
    s->aux_data          = get_bits(&s->gb, 1);
473
    s->hdcd              = get_bits(&s->gb, 1);
474
    s->ext_descr         = get_bits(&s->gb, 3);
475
    s->ext_coding        = get_bits(&s->gb, 1);
476
    s->aspf              = get_bits(&s->gb, 1);
477
    s->lfe               = get_bits(&s->gb, 2);
478
    s->predictor_history = get_bits(&s->gb, 1);
479

    
480
    /* TODO: check CRC */
481
    if (s->crc_present)
482
        s->header_crc    = get_bits(&s->gb, 16);
483

    
484
    s->multirate_inter   = get_bits(&s->gb, 1);
485
    s->version           = get_bits(&s->gb, 4);
486
    s->copy_history      = get_bits(&s->gb, 2);
487
    s->source_pcm_res    = get_bits(&s->gb, 3);
488
    s->front_sum         = get_bits(&s->gb, 1);
489
    s->surround_sum      = get_bits(&s->gb, 1);
490
    s->dialog_norm       = get_bits(&s->gb, 4);
491

    
492
    /* FIXME: channels mixing levels */
493
    s->output = s->amode;
494
    if (s->lfe) s->output |= DCA_LFE;
495

    
496
#ifdef TRACE
497
    av_log(s->avctx, AV_LOG_DEBUG, "frame type: %i\n", s->frame_type);
498
    av_log(s->avctx, AV_LOG_DEBUG, "samples deficit: %i\n", s->samples_deficit);
499
    av_log(s->avctx, AV_LOG_DEBUG, "crc present: %i\n", s->crc_present);
500
    av_log(s->avctx, AV_LOG_DEBUG, "sample blocks: %i (%i samples)\n",
501
           s->sample_blocks, s->sample_blocks * 32);
502
    av_log(s->avctx, AV_LOG_DEBUG, "frame size: %i bytes\n", s->frame_size);
503
    av_log(s->avctx, AV_LOG_DEBUG, "amode: %i (%i channels)\n",
504
           s->amode, dca_channels[s->amode]);
505
    av_log(s->avctx, AV_LOG_DEBUG, "sample rate: %i Hz\n",
506
           s->sample_rate);
507
    av_log(s->avctx, AV_LOG_DEBUG, "bit rate: %i bits/s\n",
508
           s->bit_rate);
509
    av_log(s->avctx, AV_LOG_DEBUG, "downmix: %i\n", s->downmix);
510
    av_log(s->avctx, AV_LOG_DEBUG, "dynrange: %i\n", s->dynrange);
511
    av_log(s->avctx, AV_LOG_DEBUG, "timestamp: %i\n", s->timestamp);
512
    av_log(s->avctx, AV_LOG_DEBUG, "aux_data: %i\n", s->aux_data);
513
    av_log(s->avctx, AV_LOG_DEBUG, "hdcd: %i\n", s->hdcd);
514
    av_log(s->avctx, AV_LOG_DEBUG, "ext descr: %i\n", s->ext_descr);
515
    av_log(s->avctx, AV_LOG_DEBUG, "ext coding: %i\n", s->ext_coding);
516
    av_log(s->avctx, AV_LOG_DEBUG, "aspf: %i\n", s->aspf);
517
    av_log(s->avctx, AV_LOG_DEBUG, "lfe: %i\n", s->lfe);
518
    av_log(s->avctx, AV_LOG_DEBUG, "predictor history: %i\n",
519
           s->predictor_history);
520
    av_log(s->avctx, AV_LOG_DEBUG, "header crc: %i\n", s->header_crc);
521
    av_log(s->avctx, AV_LOG_DEBUG, "multirate inter: %i\n",
522
           s->multirate_inter);
523
    av_log(s->avctx, AV_LOG_DEBUG, "version number: %i\n", s->version);
524
    av_log(s->avctx, AV_LOG_DEBUG, "copy history: %i\n", s->copy_history);
525
    av_log(s->avctx, AV_LOG_DEBUG,
526
           "source pcm resolution: %i (%i bits/sample)\n",
527
           s->source_pcm_res, dca_bits_per_sample[s->source_pcm_res]);
528
    av_log(s->avctx, AV_LOG_DEBUG, "front sum: %i\n", s->front_sum);
529
    av_log(s->avctx, AV_LOG_DEBUG, "surround sum: %i\n", s->surround_sum);
530
    av_log(s->avctx, AV_LOG_DEBUG, "dialog norm: %i\n", s->dialog_norm);
531
    av_log(s->avctx, AV_LOG_DEBUG, "\n");
532
#endif
533

    
534
    /* Primary audio coding header */
535
    s->subframes         = get_bits(&s->gb, 4) + 1;
536

    
537
    return dca_parse_audio_coding_header(s, 0);
538
}
539

    
540

    
541
static inline int get_scale(GetBitContext *gb, int level, int value)
542
{
543
   if (level < 5) {
544
       /* huffman encoded */
545
       value += get_bitalloc(gb, &dca_scalefactor, level);
546
   } else if (level < 8)
547
       value = get_bits(gb, level + 1);
548
   return value;
549
}
550

    
551
static int dca_subframe_header(DCAContext * s, int base_channel, int block_index)
552
{
553
    /* Primary audio coding side information */
554
    int j, k;
555

    
556
    if (!base_channel) {
557
        s->subsubframes[s->current_subframe] = get_bits(&s->gb, 2) + 1;
558
        s->partial_samples[s->current_subframe] = get_bits(&s->gb, 3);
559
    }
560

    
561
    for (j = base_channel; j < s->prim_channels; j++) {
562
        for (k = 0; k < s->subband_activity[j]; k++)
563
            s->prediction_mode[j][k] = get_bits(&s->gb, 1);
564
    }
565

    
566
    /* Get prediction codebook */
567
    for (j = base_channel; j < s->prim_channels; j++) {
568
        for (k = 0; k < s->subband_activity[j]; k++) {
569
            if (s->prediction_mode[j][k] > 0) {
570
                /* (Prediction coefficient VQ address) */
571
                s->prediction_vq[j][k] = get_bits(&s->gb, 12);
572
            }
573
        }
574
    }
575

    
576
    /* Bit allocation index */
577
    for (j = base_channel; j < s->prim_channels; j++) {
578
        for (k = 0; k < s->vq_start_subband[j]; k++) {
579
            if (s->bitalloc_huffman[j] == 6)
580
                s->bitalloc[j][k] = get_bits(&s->gb, 5);
581
            else if (s->bitalloc_huffman[j] == 5)
582
                s->bitalloc[j][k] = get_bits(&s->gb, 4);
583
            else if (s->bitalloc_huffman[j] == 7) {
584
                av_log(s->avctx, AV_LOG_ERROR,
585
                       "Invalid bit allocation index\n");
586
                return -1;
587
            } else {
588
                s->bitalloc[j][k] =
589
                    get_bitalloc(&s->gb, &dca_bitalloc_index, s->bitalloc_huffman[j]);
590
            }
591

    
592
            if (s->bitalloc[j][k] > 26) {
593
//                 av_log(s->avctx,AV_LOG_DEBUG,"bitalloc index [%i][%i] too big (%i)\n",
594
//                          j, k, s->bitalloc[j][k]);
595
                return -1;
596
            }
597
        }
598
    }
599

    
600
    /* Transition mode */
601
    for (j = base_channel; j < s->prim_channels; j++) {
602
        for (k = 0; k < s->subband_activity[j]; k++) {
603
            s->transition_mode[j][k] = 0;
604
            if (s->subsubframes[s->current_subframe] > 1 &&
605
                k < s->vq_start_subband[j] && s->bitalloc[j][k] > 0) {
606
                s->transition_mode[j][k] =
607
                    get_bitalloc(&s->gb, &dca_tmode, s->transient_huffman[j]);
608
            }
609
        }
610
    }
611

    
612
    for (j = base_channel; j < s->prim_channels; j++) {
613
        const uint32_t *scale_table;
614
        int scale_sum;
615

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

    
618
        if (s->scalefactor_huffman[j] == 6)
619
            scale_table = scale_factor_quant7;
620
        else
621
            scale_table = scale_factor_quant6;
622

    
623
        /* When huffman coded, only the difference is encoded */
624
        scale_sum = 0;
625

    
626
        for (k = 0; k < s->subband_activity[j]; k++) {
627
            if (k >= s->vq_start_subband[j] || s->bitalloc[j][k] > 0) {
628
                scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum);
629
                s->scale_factor[j][k][0] = scale_table[scale_sum];
630
            }
631

    
632
            if (k < s->vq_start_subband[j] && s->transition_mode[j][k]) {
633
                /* Get second scale factor */
634
                scale_sum = get_scale(&s->gb, s->scalefactor_huffman[j], scale_sum);
635
                s->scale_factor[j][k][1] = scale_table[scale_sum];
636
            }
637
        }
638
    }
639

    
640
    /* Joint subband scale factor codebook select */
641
    for (j = base_channel; j < s->prim_channels; j++) {
642
        /* Transmitted only if joint subband coding enabled */
643
        if (s->joint_intensity[j] > 0)
644
            s->joint_huff[j] = get_bits(&s->gb, 3);
645
    }
646

    
647
    /* Scale factors for joint subband coding */
648
    for (j = base_channel; j < s->prim_channels; j++) {
649
        int source_channel;
650

    
651
        /* Transmitted only if joint subband coding enabled */
652
        if (s->joint_intensity[j] > 0) {
653
            int scale = 0;
654
            source_channel = s->joint_intensity[j] - 1;
655

    
656
            /* When huffman coded, only the difference is encoded
657
             * (is this valid as well for joint scales ???) */
658

    
659
            for (k = s->subband_activity[j]; k < s->subband_activity[source_channel]; k++) {
660
                scale = get_scale(&s->gb, s->joint_huff[j], 0);
661
                scale += 64;    /* bias */
662
                s->joint_scale_factor[j][k] = scale;    /*joint_scale_table[scale]; */
663
            }
664

    
665
            if (!(s->debug_flag & 0x02)) {
666
                av_log(s->avctx, AV_LOG_DEBUG,
667
                       "Joint stereo coding not supported\n");
668
                s->debug_flag |= 0x02;
669
            }
670
        }
671
    }
672

    
673
    /* Stereo downmix coefficients */
674
    if (!base_channel && s->prim_channels > 2) {
675
        if (s->downmix) {
676
            for (j = base_channel; j < s->prim_channels; j++) {
677
                s->downmix_coef[j][0] = get_bits(&s->gb, 7);
678
                s->downmix_coef[j][1] = get_bits(&s->gb, 7);
679
            }
680
        } else {
681
            int am = s->amode & DCA_CHANNEL_MASK;
682
            for (j = base_channel; j < s->prim_channels; j++) {
683
                s->downmix_coef[j][0] = dca_default_coeffs[am][j][0];
684
                s->downmix_coef[j][1] = dca_default_coeffs[am][j][1];
685
            }
686
        }
687
    }
688

    
689
    /* Dynamic range coefficient */
690
    if (s->dynrange)
691
        s->dynrange_coef = get_bits(&s->gb, 8);
692

    
693
    /* Side information CRC check word */
694
    if (s->crc_present) {
695
        get_bits(&s->gb, 16);
696
    }
697

    
698
    /*
699
     * Primary audio data arrays
700
     */
701

    
702
    /* VQ encoded high frequency subbands */
703
    for (j = base_channel; j < s->prim_channels; j++)
704
        for (k = s->vq_start_subband[j]; k < s->subband_activity[j]; k++)
705
            /* 1 vector -> 32 samples */
706
            s->high_freq_vq[j][k] = get_bits(&s->gb, 10);
707

    
708
    /* Low frequency effect data */
709
    if (!base_channel && s->lfe) {
710
        /* LFE samples */
711
        int lfe_samples = 2 * s->lfe * (4 + block_index);
712
        int lfe_end_sample = 2 * s->lfe * (4 + block_index + s->subsubframes[s->current_subframe]);
713
        float lfe_scale;
714

    
715
        for (j = lfe_samples; j < lfe_end_sample; j++) {
716
            /* Signed 8 bits int */
717
            s->lfe_data[j] = get_sbits(&s->gb, 8);
718
        }
719

    
720
        /* Scale factor index */
721
        s->lfe_scale_factor = scale_factor_quant7[get_bits(&s->gb, 8)];
722

    
723
        /* Quantization step size * scale factor */
724
        lfe_scale = 0.035 * s->lfe_scale_factor;
725

    
726
        for (j = lfe_samples; j < lfe_end_sample; j++)
727
            s->lfe_data[j] *= lfe_scale;
728
    }
729

    
730
#ifdef TRACE
731
    av_log(s->avctx, AV_LOG_DEBUG, "subsubframes: %i\n", s->subsubframes[s->current_subframe]);
732
    av_log(s->avctx, AV_LOG_DEBUG, "partial samples: %i\n",
733
           s->partial_samples[s->current_subframe]);
734
    for (j = base_channel; j < s->prim_channels; j++) {
735
        av_log(s->avctx, AV_LOG_DEBUG, "prediction mode:");
736
        for (k = 0; k < s->subband_activity[j]; k++)
737
            av_log(s->avctx, AV_LOG_DEBUG, " %i", s->prediction_mode[j][k]);
738
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
739
    }
740
    for (j = base_channel; j < s->prim_channels; j++) {
741
        for (k = 0; k < s->subband_activity[j]; k++)
742
                av_log(s->avctx, AV_LOG_DEBUG,
743
                       "prediction coefs: %f, %f, %f, %f\n",
744
                       (float) adpcm_vb[s->prediction_vq[j][k]][0] / 8192,
745
                       (float) adpcm_vb[s->prediction_vq[j][k]][1] / 8192,
746
                       (float) adpcm_vb[s->prediction_vq[j][k]][2] / 8192,
747
                       (float) adpcm_vb[s->prediction_vq[j][k]][3] / 8192);
748
    }
749
    for (j = base_channel; j < s->prim_channels; j++) {
750
        av_log(s->avctx, AV_LOG_DEBUG, "bitalloc index: ");
751
        for (k = 0; k < s->vq_start_subband[j]; k++)
752
            av_log(s->avctx, AV_LOG_DEBUG, "%2.2i ", s->bitalloc[j][k]);
753
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
754
    }
755
    for (j = base_channel; j < s->prim_channels; j++) {
756
        av_log(s->avctx, AV_LOG_DEBUG, "Transition mode:");
757
        for (k = 0; k < s->subband_activity[j]; k++)
758
            av_log(s->avctx, AV_LOG_DEBUG, " %i", s->transition_mode[j][k]);
759
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
760
    }
761
    for (j = base_channel; j < s->prim_channels; j++) {
762
        av_log(s->avctx, AV_LOG_DEBUG, "Scale factor:");
763
        for (k = 0; k < s->subband_activity[j]; k++) {
764
            if (k >= s->vq_start_subband[j] || s->bitalloc[j][k] > 0)
765
                av_log(s->avctx, AV_LOG_DEBUG, " %i", s->scale_factor[j][k][0]);
766
            if (k < s->vq_start_subband[j] && s->transition_mode[j][k])
767
                av_log(s->avctx, AV_LOG_DEBUG, " %i(t)", s->scale_factor[j][k][1]);
768
        }
769
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
770
    }
771
    for (j = base_channel; j < s->prim_channels; j++) {
772
        if (s->joint_intensity[j] > 0) {
773
            int source_channel = s->joint_intensity[j] - 1;
774
            av_log(s->avctx, AV_LOG_DEBUG, "Joint scale factor index:\n");
775
            for (k = s->subband_activity[j]; k < s->subband_activity[source_channel]; k++)
776
                av_log(s->avctx, AV_LOG_DEBUG, " %i", s->joint_scale_factor[j][k]);
777
            av_log(s->avctx, AV_LOG_DEBUG, "\n");
778
        }
779
    }
780
    if (!base_channel && s->prim_channels > 2 && s->downmix) {
781
        av_log(s->avctx, AV_LOG_DEBUG, "Downmix coeffs:\n");
782
        for (j = 0; j < s->prim_channels; j++) {
783
            av_log(s->avctx, AV_LOG_DEBUG, "Channel 0,%d = %f\n", j, dca_downmix_coeffs[s->downmix_coef[j][0]]);
784
            av_log(s->avctx, AV_LOG_DEBUG, "Channel 1,%d = %f\n", j, dca_downmix_coeffs[s->downmix_coef[j][1]]);
785
        }
786
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
787
    }
788
    for (j = base_channel; j < s->prim_channels; j++)
789
        for (k = s->vq_start_subband[j]; k < s->subband_activity[j]; k++)
790
            av_log(s->avctx, AV_LOG_DEBUG, "VQ index: %i\n", s->high_freq_vq[j][k]);
791
    if (!base_channel && s->lfe) {
792
        int lfe_samples = 2 * s->lfe * (4 + block_index);
793
        int lfe_end_sample = 2 * s->lfe * (4 + block_index + s->subsubframes[s->current_subframe]);
794

    
795
        av_log(s->avctx, AV_LOG_DEBUG, "LFE samples:\n");
796
        for (j = lfe_samples; j < lfe_end_sample; j++)
797
            av_log(s->avctx, AV_LOG_DEBUG, " %f", s->lfe_data[j]);
798
        av_log(s->avctx, AV_LOG_DEBUG, "\n");
799
    }
800
#endif
801

    
802
    return 0;
803
}
804

    
805
static void qmf_32_subbands(DCAContext * s, int chans,
806
                            float samples_in[32][8], float *samples_out,
807
                            float scale, float bias)
808
{
809
    const float *prCoeff;
810
    int i;
811

    
812
    int sb_act = s->subband_activity[chans];
813
    int subindex;
814

    
815
    scale *= sqrt(1/8.0);
816

    
817
    /* Select filter */
818
    if (!s->multirate_inter)    /* Non-perfect reconstruction */
819
        prCoeff = fir_32bands_nonperfect;
820
    else                        /* Perfect reconstruction */
821
        prCoeff = fir_32bands_perfect;
822

    
823
    /* Reconstructed channel sample index */
824
    for (subindex = 0; subindex < 8; subindex++) {
825
        /* Load in one sample from each subband and clear inactive subbands */
826
        for (i = 0; i < sb_act; i++){
827
            uint32_t v = AV_RN32A(&samples_in[i][subindex]) ^ ((i-1)&2)<<30;
828
            AV_WN32A(&s->raXin[i], v);
829
        }
830
        for (; i < 32; i++)
831
            s->raXin[i] = 0.0;
832

    
833
        s->synth.synth_filter_float(&s->imdct,
834
                              s->subband_fir_hist[chans], &s->hist_index[chans],
835
                              s->subband_fir_noidea[chans], prCoeff,
836
                              samples_out, s->raXin, scale, bias);
837
        samples_out+= 32;
838

    
839
    }
840
}
841

    
842
static void lfe_interpolation_fir(DCAContext *s, int decimation_select,
843
                                  int num_deci_sample, float *samples_in,
844
                                  float *samples_out, float scale,
845
                                  float bias)
846
{
847
    /* samples_in: An array holding decimated samples.
848
     *   Samples in current subframe starts from samples_in[0],
849
     *   while samples_in[-1], samples_in[-2], ..., stores samples
850
     *   from last subframe as history.
851
     *
852
     * samples_out: An array holding interpolated samples
853
     */
854

    
855
    int decifactor;
856
    const float *prCoeff;
857
    int deciindex;
858

    
859
    /* Select decimation filter */
860
    if (decimation_select == 1) {
861
        decifactor = 64;
862
        prCoeff = lfe_fir_128;
863
    } else {
864
        decifactor = 32;
865
        prCoeff = lfe_fir_64;
866
    }
867
    /* Interpolation */
868
    for (deciindex = 0; deciindex < num_deci_sample; deciindex++) {
869
        s->dcadsp.lfe_fir(samples_out, samples_in, prCoeff, decifactor,
870
                          scale, bias);
871
        samples_in++;
872
        samples_out += 2 * decifactor;
873
    }
874
}
875

    
876
/* downmixing routines */
877
#define MIX_REAR1(samples, si1, rs, coef) \
878
     samples[i]     += samples[si1] * coef[rs][0]; \
879
     samples[i+256] += samples[si1] * coef[rs][1];
880

    
881
#define MIX_REAR2(samples, si1, si2, rs, coef) \
882
     samples[i]     += samples[si1] * coef[rs][0] + samples[si2] * coef[rs+1][0]; \
883
     samples[i+256] += samples[si1] * coef[rs][1] + samples[si2] * coef[rs+1][1];
884

    
885
#define MIX_FRONT3(samples, coef) \
886
    t = samples[i]; \
887
    samples[i]     = t * coef[0][0] + samples[i+256] * coef[1][0] + samples[i+512] * coef[2][0]; \
888
    samples[i+256] = t * coef[0][1] + samples[i+256] * coef[1][1] + samples[i+512] * coef[2][1];
889

    
890
#define DOWNMIX_TO_STEREO(op1, op2) \
891
    for (i = 0; i < 256; i++){ \
892
        op1 \
893
        op2 \
894
    }
895

    
896
static void dca_downmix(float *samples, int srcfmt,
897
                        int downmix_coef[DCA_PRIM_CHANNELS_MAX][2])
898
{
899
    int i;
900
    float t;
901
    float coef[DCA_PRIM_CHANNELS_MAX][2];
902

    
903
    for (i=0; i<DCA_PRIM_CHANNELS_MAX; i++) {
904
        coef[i][0] = dca_downmix_coeffs[downmix_coef[i][0]];
905
        coef[i][1] = dca_downmix_coeffs[downmix_coef[i][1]];
906
    }
907

    
908
    switch (srcfmt) {
909
    case DCA_MONO:
910
    case DCA_CHANNEL:
911
    case DCA_STEREO_TOTAL:
912
    case DCA_STEREO_SUMDIFF:
913
    case DCA_4F2R:
914
        av_log(NULL, 0, "Not implemented!\n");
915
        break;
916
    case DCA_STEREO:
917
        break;
918
    case DCA_3F:
919
        DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),);
920
        break;
921
    case DCA_2F1R:
922
        DOWNMIX_TO_STEREO(MIX_REAR1(samples, i + 512, 2, coef),);
923
        break;
924
    case DCA_3F1R:
925
        DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
926
                          MIX_REAR1(samples, i + 768, 3, coef));
927
        break;
928
    case DCA_2F2R:
929
        DOWNMIX_TO_STEREO(MIX_REAR2(samples, i + 512, i + 768, 2, coef),);
930
        break;
931
    case DCA_3F2R:
932
        DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef),
933
                          MIX_REAR2(samples, i + 768, i + 1024, 3, coef));
934
        break;
935
    }
936
}
937

    
938

    
939
/* Very compact version of the block code decoder that does not use table
940
 * look-up but is slightly slower */
941
static int decode_blockcode(int code, int levels, int *values)
942
{
943
    int i;
944
    int offset = (levels - 1) >> 1;
945

    
946
    for (i = 0; i < 4; i++) {
947
        int div = FASTDIV(code, levels);
948
        values[i] = code - offset - div*levels;
949
        code = div;
950
    }
951

    
952
    if (code == 0)
953
        return 0;
954
    else {
955
        av_log(NULL, AV_LOG_ERROR, "ERROR: block code look-up failed\n");
956
        return -1;
957
    }
958
}
959

    
960
static const uint8_t abits_sizes[7] = { 7, 10, 12, 13, 15, 17, 19 };
961
static const uint8_t abits_levels[7] = { 3, 5, 7, 9, 13, 17, 25 };
962

    
963
static int dca_subsubframe(DCAContext * s, int base_channel, int block_index)
964
{
965
    int k, l;
966
    int subsubframe = s->current_subsubframe;
967

    
968
    const float *quant_step_table;
969

    
970
    /* FIXME */
971
    float (*subband_samples)[DCA_SUBBANDS][8] = s->subband_samples[block_index];
972
    LOCAL_ALIGNED_16(int, block, [8]);
973

    
974
    /*
975
     * Audio data
976
     */
977

    
978
    /* Select quantization step size table */
979
    if (s->bit_rate_index == 0x1f)
980
        quant_step_table = lossless_quant_d;
981
    else
982
        quant_step_table = lossy_quant_d;
983

    
984
    for (k = base_channel; k < s->prim_channels; k++) {
985
        for (l = 0; l < s->vq_start_subband[k]; l++) {
986
            int m;
987

    
988
            /* Select the mid-tread linear quantizer */
989
            int abits = s->bitalloc[k][l];
990

    
991
            float quant_step_size = quant_step_table[abits];
992

    
993
            /*
994
             * Determine quantization index code book and its type
995
             */
996

    
997
            /* Select quantization index code book */
998
            int sel = s->quant_index_huffman[k][abits];
999

    
1000
            /*
1001
             * Extract bits from the bit stream
1002
             */
1003
            if (!abits){
1004
                memset(subband_samples[k][l], 0, 8 * sizeof(subband_samples[0][0][0]));
1005
            } else {
1006
                /* Deal with transients */
1007
                int sfi = s->transition_mode[k][l] && subsubframe >= s->transition_mode[k][l];
1008
                float rscale = quant_step_size * s->scale_factor[k][l][sfi] * s->scalefactor_adj[k][sel];
1009

    
1010
                if (abits >= 11 || !dca_smpl_bitalloc[abits].vlc[sel].table){
1011
                    if (abits <= 7){
1012
                        /* Block code */
1013
                        int block_code1, block_code2, size, levels;
1014

    
1015
                        size = abits_sizes[abits-1];
1016
                        levels = abits_levels[abits-1];
1017

    
1018
                        block_code1 = get_bits(&s->gb, size);
1019
                        /* FIXME Should test return value */
1020
                        decode_blockcode(block_code1, levels, block);
1021
                        block_code2 = get_bits(&s->gb, size);
1022
                        decode_blockcode(block_code2, levels, &block[4]);
1023
                    }else{
1024
                        /* no coding */
1025
                        for (m = 0; m < 8; m++)
1026
                            block[m] = get_sbits(&s->gb, abits - 3);
1027
                    }
1028
                }else{
1029
                    /* Huffman coded */
1030
                    for (m = 0; m < 8; m++)
1031
                        block[m] = get_bitalloc(&s->gb, &dca_smpl_bitalloc[abits], sel);
1032
                }
1033

    
1034
                s->dsp.int32_to_float_fmul_scalar(subband_samples[k][l],
1035
                                                  block, rscale, 8);
1036
            }
1037

    
1038
            /*
1039
             * Inverse ADPCM if in prediction mode
1040
             */
1041
            if (s->prediction_mode[k][l]) {
1042
                int n;
1043
                for (m = 0; m < 8; m++) {
1044
                    for (n = 1; n <= 4; n++)
1045
                        if (m >= n)
1046
                            subband_samples[k][l][m] +=
1047
                                (adpcm_vb[s->prediction_vq[k][l]][n - 1] *
1048
                                 subband_samples[k][l][m - n] / 8192);
1049
                        else if (s->predictor_history)
1050
                            subband_samples[k][l][m] +=
1051
                                (adpcm_vb[s->prediction_vq[k][l]][n - 1] *
1052
                                 s->subband_samples_hist[k][l][m - n +
1053
                                                               4] / 8192);
1054
                }
1055
            }
1056
        }
1057

    
1058
        /*
1059
         * Decode VQ encoded high frequencies
1060
         */
1061
        for (l = s->vq_start_subband[k]; l < s->subband_activity[k]; l++) {
1062
            /* 1 vector -> 32 samples but we only need the 8 samples
1063
             * for this subsubframe. */
1064
            int m;
1065

    
1066
            if (!s->debug_flag & 0x01) {
1067
                av_log(s->avctx, AV_LOG_DEBUG, "Stream with high frequencies VQ coding\n");
1068
                s->debug_flag |= 0x01;
1069
            }
1070

    
1071
            for (m = 0; m < 8; m++) {
1072
                subband_samples[k][l][m] =
1073
                    high_freq_vq[s->high_freq_vq[k][l]][subsubframe * 8 +
1074
                                                        m]
1075
                    * (float) s->scale_factor[k][l][0] / 16.0;
1076
            }
1077
        }
1078
    }
1079

    
1080
    /* Check for DSYNC after subsubframe */
1081
    if (s->aspf || subsubframe == s->subsubframes[s->current_subframe] - 1) {
1082
        if (0xFFFF == get_bits(&s->gb, 16)) {   /* 0xFFFF */
1083
#ifdef TRACE
1084
            av_log(s->avctx, AV_LOG_DEBUG, "Got subframe DSYNC\n");
1085
#endif
1086
        } else {
1087
            av_log(s->avctx, AV_LOG_ERROR, "Didn't get subframe DSYNC\n");
1088
        }
1089
    }
1090

    
1091
    /* Backup predictor history for adpcm */
1092
    for (k = base_channel; k < s->prim_channels; k++)
1093
        for (l = 0; l < s->vq_start_subband[k]; l++)
1094
            memcpy(s->subband_samples_hist[k][l], &subband_samples[k][l][4],
1095
                        4 * sizeof(subband_samples[0][0][0]));
1096

    
1097
    return 0;
1098
}
1099

    
1100
static int dca_filter_channels(DCAContext * s, int block_index)
1101
{
1102
    float (*subband_samples)[DCA_SUBBANDS][8] = s->subband_samples[block_index];
1103
    int k;
1104

    
1105
    /* 32 subbands QMF */
1106
    for (k = 0; k < s->prim_channels; k++) {
1107
/*        static float pcm_to_double[8] =
1108
            {32768.0, 32768.0, 524288.0, 524288.0, 0, 8388608.0, 8388608.0};*/
1109
         qmf_32_subbands(s, k, subband_samples[k], &s->samples[256 * s->channel_order_tab[k]],
1110
                            M_SQRT1_2*s->scale_bias /*pcm_to_double[s->source_pcm_res] */ ,
1111
                            s->add_bias );
1112
    }
1113

    
1114
    /* Down mixing */
1115
    if (s->avctx->request_channels == 2 && s->prim_channels > 2) {
1116
        dca_downmix(s->samples, s->amode, s->downmix_coef);
1117
    }
1118

    
1119
    /* Generate LFE samples for this subsubframe FIXME!!! */
1120
    if (s->output & DCA_LFE) {
1121
        lfe_interpolation_fir(s, s->lfe, 2 * s->lfe,
1122
                              s->lfe_data + 2 * s->lfe * (block_index + 4),
1123
                              &s->samples[256 * dca_lfe_index[s->amode]],
1124
                              (1.0/256.0)*s->scale_bias,  s->add_bias);
1125
        /* Outputs 20bits pcm samples */
1126
    }
1127

    
1128
    return 0;
1129
}
1130

    
1131

    
1132
static int dca_subframe_footer(DCAContext * s, int base_channel)
1133
{
1134
    int aux_data_count = 0, i;
1135

    
1136
    /*
1137
     * Unpack optional information
1138
     */
1139

    
1140
    /* presumably optional information only appears in the core? */
1141
    if (!base_channel) {
1142
        if (s->timestamp)
1143
            get_bits(&s->gb, 32);
1144

    
1145
        if (s->aux_data)
1146
            aux_data_count = get_bits(&s->gb, 6);
1147

    
1148
        for (i = 0; i < aux_data_count; i++)
1149
            get_bits(&s->gb, 8);
1150

    
1151
        if (s->crc_present && (s->downmix || s->dynrange))
1152
            get_bits(&s->gb, 16);
1153
    }
1154

    
1155
    return 0;
1156
}
1157

    
1158
/**
1159
 * Decode a dca frame block
1160
 *
1161
 * @param s     pointer to the DCAContext
1162
 */
1163

    
1164
static int dca_decode_block(DCAContext * s, int base_channel, int block_index)
1165
{
1166

    
1167
    /* Sanity check */
1168
    if (s->current_subframe >= s->subframes) {
1169
        av_log(s->avctx, AV_LOG_DEBUG, "check failed: %i>%i",
1170
               s->current_subframe, s->subframes);
1171
        return -1;
1172
    }
1173

    
1174
    if (!s->current_subsubframe) {
1175
#ifdef TRACE
1176
        av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subframe_header\n");
1177
#endif
1178
        /* Read subframe header */
1179
        if (dca_subframe_header(s, base_channel, block_index))
1180
            return -1;
1181
    }
1182

    
1183
    /* Read subsubframe */
1184
#ifdef TRACE
1185
    av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subsubframe\n");
1186
#endif
1187
    if (dca_subsubframe(s, base_channel, block_index))
1188
        return -1;
1189

    
1190
    /* Update state */
1191
    s->current_subsubframe++;
1192
    if (s->current_subsubframe >= s->subsubframes[s->current_subframe]) {
1193
        s->current_subsubframe = 0;
1194
        s->current_subframe++;
1195
    }
1196
    if (s->current_subframe >= s->subframes) {
1197
#ifdef TRACE
1198
        av_log(s->avctx, AV_LOG_DEBUG, "DSYNC dca_subframe_footer\n");
1199
#endif
1200
        /* Read subframe footer */
1201
        if (dca_subframe_footer(s, base_channel))
1202
            return -1;
1203
    }
1204

    
1205
    return 0;
1206
}
1207

    
1208
/**
1209
 * Convert bitstream to one representation based on sync marker
1210
 */
1211
static int dca_convert_bitstream(const uint8_t * src, int src_size, uint8_t * dst,
1212
                          int max_size)
1213
{
1214
    uint32_t mrk;
1215
    int i, tmp;
1216
    const uint16_t *ssrc = (const uint16_t *) src;
1217
    uint16_t *sdst = (uint16_t *) dst;
1218
    PutBitContext pb;
1219

    
1220
    if ((unsigned)src_size > (unsigned)max_size) {
1221
//        av_log(NULL, AV_LOG_ERROR, "Input frame size larger then DCA_MAX_FRAME_SIZE!\n");
1222
//        return -1;
1223
        src_size = max_size;
1224
    }
1225

    
1226
    mrk = AV_RB32(src);
1227
    switch (mrk) {
1228
    case DCA_MARKER_RAW_BE:
1229
        memcpy(dst, src, src_size);
1230
        return src_size;
1231
    case DCA_MARKER_RAW_LE:
1232
        for (i = 0; i < (src_size + 1) >> 1; i++)
1233
            *sdst++ = bswap_16(*ssrc++);
1234
        return src_size;
1235
    case DCA_MARKER_14B_BE:
1236
    case DCA_MARKER_14B_LE:
1237
        init_put_bits(&pb, dst, max_size);
1238
        for (i = 0; i < (src_size + 1) >> 1; i++, src += 2) {
1239
            tmp = ((mrk == DCA_MARKER_14B_BE) ? AV_RB16(src) : AV_RL16(src)) & 0x3FFF;
1240
            put_bits(&pb, 14, tmp);
1241
        }
1242
        flush_put_bits(&pb);
1243
        return (put_bits_count(&pb) + 7) >> 3;
1244
    default:
1245
        return -1;
1246
    }
1247
}
1248

    
1249
/**
1250
 * Main frame decoding function
1251
 * FIXME add arguments
1252
 */
1253
static int dca_decode_frame(AVCodecContext * avctx,
1254
                            void *data, int *data_size,
1255
                            AVPacket *avpkt)
1256
{
1257
    const uint8_t *buf = avpkt->data;
1258
    int buf_size = avpkt->size;
1259

    
1260
    int lfe_samples;
1261
    int num_core_channels = 0;
1262
    int i;
1263
    int xch_present = 0;
1264
    int16_t *samples = data;
1265
    DCAContext *s = avctx->priv_data;
1266
    int channels;
1267

    
1268

    
1269
    s->dca_buffer_size = dca_convert_bitstream(buf, buf_size, s->dca_buffer, DCA_MAX_FRAME_SIZE);
1270
    if (s->dca_buffer_size == -1) {
1271
        av_log(avctx, AV_LOG_ERROR, "Not a valid DCA frame\n");
1272
        return -1;
1273
    }
1274

    
1275
    init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);
1276
    if (dca_parse_frame_header(s) < 0) {
1277
        //seems like the frame is corrupt, try with the next one
1278
        *data_size=0;
1279
        return buf_size;
1280
    }
1281
    //set AVCodec values with parsed data
1282
    avctx->sample_rate = s->sample_rate;
1283
    avctx->bit_rate = s->bit_rate;
1284

    
1285
    for (i = 0; i < (s->sample_blocks / 8); i++) {
1286
        dca_decode_block(s, 0, i);
1287
    }
1288

    
1289
    /* record number of core channels incase less than max channels are requested */
1290
    num_core_channels = s->prim_channels;
1291

    
1292
    /* extensions start at 32-bit boundaries into bitstream */
1293
    skip_bits(&s->gb, (-get_bits_count(&s->gb)) & 31);
1294

    
1295
    while(get_bits_left(&s->gb) >= 32) {
1296
        uint32_t bits = get_bits(&s->gb, 32);
1297

    
1298
        switch(bits) {
1299
        case 0x5a5a5a5a: {
1300
            int ext_base_ch = s->prim_channels;
1301
            int ext_amode;
1302

    
1303
            /* skip length-to-end-of-frame field for the moment */
1304
            skip_bits(&s->gb, 10);
1305

    
1306
            /* extension amode should == 1, number of channels in extension */
1307
            /* AFAIK XCh is not used for more channels */
1308
            if ((ext_amode = get_bits(&s->gb, 4)) != 1) {
1309
                av_log(avctx, AV_LOG_ERROR, "XCh extension amode %d not"
1310
                       " supported!\n",ext_amode);
1311
                continue;
1312
            }
1313

    
1314
            /* much like core primary audio coding header */
1315
            dca_parse_audio_coding_header(s, ext_base_ch);
1316

    
1317
            for (i = 0; i < (s->sample_blocks / 8); i++) {
1318
                dca_decode_block(s, ext_base_ch, i);
1319
            }
1320

    
1321
            xch_present = 1;
1322
            break;
1323
        }
1324
        case 0x1d95f262:
1325
            av_log(avctx, AV_LOG_DEBUG, "Possible X96 extension found at %d bits\n", get_bits_count(&s->gb));
1326
            av_log(avctx, AV_LOG_DEBUG, "FSIZE96 = %d bytes\n", get_bits(&s->gb, 12)+1);
1327
            av_log(avctx, AV_LOG_DEBUG, "REVNO = %d\n", get_bits(&s->gb, 4));
1328
            break;
1329
        }
1330

    
1331
        skip_bits(&s->gb, (-get_bits_count(&s->gb)) & 31);
1332
    }
1333

    
1334
    channels = s->prim_channels + !!s->lfe;
1335

    
1336
    if (s->amode<16) {
1337
        avctx->channel_layout = dca_core_channel_layout[s->amode];
1338

    
1339
        if (xch_present && (!avctx->request_channels ||
1340
                            avctx->request_channels > num_core_channels)) {
1341
            avctx->channel_layout |= CH_BACK_CENTER;
1342
            if (s->lfe) {
1343
                avctx->channel_layout |= CH_LOW_FREQUENCY;
1344
                s->channel_order_tab = dca_channel_reorder_lfe_xch[s->amode];
1345
            } else {
1346
                s->channel_order_tab = dca_channel_reorder_nolfe_xch[s->amode];
1347
            }
1348
        } else {
1349
            if (s->lfe) {
1350
                avctx->channel_layout |= CH_LOW_FREQUENCY;
1351
                s->channel_order_tab = dca_channel_reorder_lfe[s->amode];
1352
            } else
1353
                s->channel_order_tab = dca_channel_reorder_nolfe[s->amode];
1354
        }
1355

    
1356
        if (s->prim_channels > 0 &&
1357
            s->channel_order_tab[s->prim_channels - 1] < 0)
1358
            return -1;
1359

    
1360
        if (avctx->request_channels == 2 && s->prim_channels > 2) {
1361
            channels = 2;
1362
            s->output = DCA_STEREO;
1363
            avctx->channel_layout = CH_LAYOUT_STEREO;
1364
        }
1365
    } else {
1366
        av_log(avctx, AV_LOG_ERROR, "Non standard configuration %d !\n",s->amode);
1367
        return -1;
1368
    }
1369

    
1370

    
1371
    /* There is nothing that prevents a dts frame to change channel configuration
1372
       but FFmpeg doesn't support that so only set the channels if it is previously
1373
       unset. Ideally during the first probe for channels the crc should be checked
1374
       and only set avctx->channels when the crc is ok. Right now the decoder could
1375
       set the channels based on a broken first frame.*/
1376
    if (!avctx->channels)
1377
        avctx->channels = channels;
1378

    
1379
    if (*data_size < (s->sample_blocks / 8) * 256 * sizeof(int16_t) * channels)
1380
        return -1;
1381
    *data_size = 256 / 8 * s->sample_blocks * sizeof(int16_t) * channels;
1382

    
1383
    /* filter to get final output */
1384
    for (i = 0; i < (s->sample_blocks / 8); i++) {
1385
        dca_filter_channels(s, i);
1386
        s->dsp.float_to_int16_interleave(samples, s->samples_chanptr, 256, channels);
1387
        samples += 256 * channels;
1388
    }
1389

    
1390
    /* update lfe history */
1391
    lfe_samples = 2 * s->lfe * (s->sample_blocks / 8);
1392
    for (i = 0; i < 2 * s->lfe * 4; i++) {
1393
        s->lfe_data[i] = s->lfe_data[i + lfe_samples];
1394
    }
1395

    
1396
    return buf_size;
1397
}
1398

    
1399

    
1400

    
1401
/**
1402
 * DCA initialization
1403
 *
1404
 * @param avctx     pointer to the AVCodecContext
1405
 */
1406

    
1407
static av_cold int dca_decode_init(AVCodecContext * avctx)
1408
{
1409
    DCAContext *s = avctx->priv_data;
1410
    int i;
1411

    
1412
    s->avctx = avctx;
1413
    dca_init_vlcs();
1414

    
1415
    dsputil_init(&s->dsp, avctx);
1416
    ff_mdct_init(&s->imdct, 6, 1, 1.0);
1417
    ff_synth_filter_init(&s->synth);
1418
    ff_dcadsp_init(&s->dcadsp);
1419

    
1420
    for (i = 0; i < DCA_PRIM_CHANNELS_MAX+1; i++)
1421
        s->samples_chanptr[i] = s->samples + i * 256;
1422
    avctx->sample_fmt = SAMPLE_FMT_S16;
1423

    
1424
    if (s->dsp.float_to_int16_interleave == ff_float_to_int16_interleave_c) {
1425
        s->add_bias = 385.0f;
1426
        s->scale_bias = 1.0 / 32768.0;
1427
    } else {
1428
        s->add_bias = 0.0f;
1429
        s->scale_bias = 1.0;
1430

    
1431
        /* allow downmixing to stereo */
1432
        if (avctx->channels > 0 && avctx->request_channels < avctx->channels &&
1433
                avctx->request_channels == 2) {
1434
            avctx->channels = avctx->request_channels;
1435
        }
1436
    }
1437

    
1438

    
1439
    return 0;
1440
}
1441

    
1442
static av_cold int dca_decode_end(AVCodecContext * avctx)
1443
{
1444
    DCAContext *s = avctx->priv_data;
1445
    ff_mdct_end(&s->imdct);
1446
    return 0;
1447
}
1448

    
1449
AVCodec dca_decoder = {
1450
    .name = "dca",
1451
    .type = AVMEDIA_TYPE_AUDIO,
1452
    .id = CODEC_ID_DTS,
1453
    .priv_data_size = sizeof(DCAContext),
1454
    .init = dca_decode_init,
1455
    .decode = dca_decode_frame,
1456
    .close = dca_decode_end,
1457
    .long_name = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
1458
};