Statistics
| Branch: | Revision:

ffmpeg / libavcodec / qdm2.c @ 84dc2d8a

History | View | Annotate | Download (69 KB)

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

    
25
/**
26
 * @file libavcodec/qdm2.c
27
 * QDM2 decoder
28
 * @author Ewald Snel, Benjamin Larsson, Alex Beregszaszi, Roberto Togni
29
 * The decoder is not perfect yet, there are still some distortions
30
 * especially on files encoded with 16 or 8 subbands.
31
 */
32

    
33
#include <math.h>
34
#include <stddef.h>
35
#include <stdio.h>
36

    
37
#define ALT_BITSTREAM_READER_LE
38
#include "avcodec.h"
39
#include "get_bits.h"
40
#include "dsputil.h"
41
#include "mpegaudio.h"
42

    
43
#include "qdm2data.h"
44

    
45
#undef NDEBUG
46
#include <assert.h>
47

    
48

    
49
#define SOFTCLIP_THRESHOLD 27600
50
#define HARDCLIP_THRESHOLD 35716
51

    
52

    
53
#define QDM2_LIST_ADD(list, size, packet) \
54
do { \
55
      if (size > 0) { \
56
    list[size - 1].next = &list[size]; \
57
      } \
58
      list[size].packet = packet; \
59
      list[size].next = NULL; \
60
      size++; \
61
} while(0)
62

    
63
// Result is 8, 16 or 30
64
#define QDM2_SB_USED(sub_sampling) (((sub_sampling) >= 2) ? 30 : 8 << (sub_sampling))
65

    
66
#define FIX_NOISE_IDX(noise_idx) \
67
  if ((noise_idx) >= 3840) \
68
    (noise_idx) -= 3840; \
69

    
70
#define SB_DITHERING_NOISE(sb,noise_idx) (noise_table[(noise_idx)++] * sb_noise_attenuation[(sb)])
71

    
72
#define BITS_LEFT(length,gb) ((length) - get_bits_count ((gb)))
73

    
74
#define SAMPLES_NEEDED \
75
     av_log (NULL,AV_LOG_INFO,"This file triggers some untested code. Please contact the developers.\n");
76

    
77
#define SAMPLES_NEEDED_2(why) \
78
     av_log (NULL,AV_LOG_INFO,"This file triggers some missing code. Please contact the developers.\nPosition: %s\n",why);
79

    
80

    
81
typedef int8_t sb_int8_array[2][30][64];
82

    
83
/**
84
 * Subpacket
85
 */
86
typedef struct {
87
    int type;            ///< subpacket type
88
    unsigned int size;   ///< subpacket size
89
    const uint8_t *data; ///< pointer to subpacket data (points to input data buffer, it's not a private copy)
90
} QDM2SubPacket;
91

    
92
/**
93
 * A node in the subpacket list
94
 */
95
typedef struct QDM2SubPNode {
96
    QDM2SubPacket *packet;      ///< packet
97
    struct QDM2SubPNode *next; ///< pointer to next packet in the list, NULL if leaf node
98
} QDM2SubPNode;
99

    
100
typedef struct {
101
    float re;
102
    float im;
103
} QDM2Complex;
104

    
105
typedef struct {
106
    float level;
107
    QDM2Complex *complex;
108
    const float *table;
109
    int   phase;
110
    int   phase_shift;
111
    int   duration;
112
    short time_index;
113
    short cutoff;
114
} FFTTone;
115

    
116
typedef struct {
117
    int16_t sub_packet;
118
    uint8_t channel;
119
    int16_t offset;
120
    int16_t exp;
121
    uint8_t phase;
122
} FFTCoefficient;
123

    
124
typedef struct {
125
    DECLARE_ALIGNED(16, QDM2Complex, complex)[MPA_MAX_CHANNELS][256];
126
} QDM2FFT;
127

    
128
/**
129
 * QDM2 decoder context
130
 */
131
typedef struct {
132
    /// Parameters from codec header, do not change during playback
133
    int nb_channels;         ///< number of channels
134
    int channels;            ///< number of channels
135
    int group_size;          ///< size of frame group (16 frames per group)
136
    int fft_size;            ///< size of FFT, in complex numbers
137
    int checksum_size;       ///< size of data block, used also for checksum
138

    
139
    /// Parameters built from header parameters, do not change during playback
140
    int group_order;         ///< order of frame group
141
    int fft_order;           ///< order of FFT (actually fftorder+1)
142
    int fft_frame_size;      ///< size of fft frame, in components (1 comples = re + im)
143
    int frame_size;          ///< size of data frame
144
    int frequency_range;
145
    int sub_sampling;        ///< subsampling: 0=25%, 1=50%, 2=100% */
146
    int coeff_per_sb_select; ///< selector for "num. of coeffs. per subband" tables. Can be 0, 1, 2
147
    int cm_table_select;     ///< selector for "coding method" tables. Can be 0, 1 (from init: 0-4)
148

    
149
    /// Packets and packet lists
150
    QDM2SubPacket sub_packets[16];      ///< the packets themselves
151
    QDM2SubPNode sub_packet_list_A[16]; ///< list of all packets
152
    QDM2SubPNode sub_packet_list_B[16]; ///< FFT packets B are on list
153
    int sub_packets_B;                  ///< number of packets on 'B' list
154
    QDM2SubPNode sub_packet_list_C[16]; ///< packets with errors?
155
    QDM2SubPNode sub_packet_list_D[16]; ///< DCT packets
156

    
157
    /// FFT and tones
158
    FFTTone fft_tones[1000];
159
    int fft_tone_start;
160
    int fft_tone_end;
161
    FFTCoefficient fft_coefs[1000];
162
    int fft_coefs_index;
163
    int fft_coefs_min_index[5];
164
    int fft_coefs_max_index[5];
165
    int fft_level_exp[6];
166
    RDFTContext rdft_ctx;
167
    QDM2FFT fft;
168

    
169
    /// I/O data
170
    const uint8_t *compressed_data;
171
    int compressed_size;
172
    float output_buffer[1024];
173

    
174
    /// Synthesis filter
175
    DECLARE_ALIGNED(16, MPA_INT, synth_buf)[MPA_MAX_CHANNELS][512*2];
176
    int synth_buf_offset[MPA_MAX_CHANNELS];
177
    DECLARE_ALIGNED(16, int32_t, sb_samples)[MPA_MAX_CHANNELS][128][SBLIMIT];
178

    
179
    /// Mixed temporary data used in decoding
180
    float tone_level[MPA_MAX_CHANNELS][30][64];
181
    int8_t coding_method[MPA_MAX_CHANNELS][30][64];
182
    int8_t quantized_coeffs[MPA_MAX_CHANNELS][10][8];
183
    int8_t tone_level_idx_base[MPA_MAX_CHANNELS][30][8];
184
    int8_t tone_level_idx_hi1[MPA_MAX_CHANNELS][3][8][8];
185
    int8_t tone_level_idx_mid[MPA_MAX_CHANNELS][26][8];
186
    int8_t tone_level_idx_hi2[MPA_MAX_CHANNELS][26];
187
    int8_t tone_level_idx[MPA_MAX_CHANNELS][30][64];
188
    int8_t tone_level_idx_temp[MPA_MAX_CHANNELS][30][64];
189

    
190
    // Flags
191
    int has_errors;         ///< packet has errors
192
    int superblocktype_2_3; ///< select fft tables and some algorithm based on superblock type
193
    int do_synth_filter;    ///< used to perform or skip synthesis filter
194

    
195
    int sub_packet;
196
    int noise_idx; ///< index for dithering noise table
197
} QDM2Context;
198

    
199

    
200
static uint8_t empty_buffer[FF_INPUT_BUFFER_PADDING_SIZE];
201

    
202
static VLC vlc_tab_level;
203
static VLC vlc_tab_diff;
204
static VLC vlc_tab_run;
205
static VLC fft_level_exp_alt_vlc;
206
static VLC fft_level_exp_vlc;
207
static VLC fft_stereo_exp_vlc;
208
static VLC fft_stereo_phase_vlc;
209
static VLC vlc_tab_tone_level_idx_hi1;
210
static VLC vlc_tab_tone_level_idx_mid;
211
static VLC vlc_tab_tone_level_idx_hi2;
212
static VLC vlc_tab_type30;
213
static VLC vlc_tab_type34;
214
static VLC vlc_tab_fft_tone_offset[5];
215

    
216
static uint16_t softclip_table[HARDCLIP_THRESHOLD - SOFTCLIP_THRESHOLD + 1];
217
static float noise_table[4096];
218
static uint8_t random_dequant_index[256][5];
219
static uint8_t random_dequant_type24[128][3];
220
static float noise_samples[128];
221

    
222

    
223
static av_cold void softclip_table_init(void) {
224
    int i;
225
    double dfl = SOFTCLIP_THRESHOLD - 32767;
226
    float delta = 1.0 / -dfl;
227
    for (i = 0; i < HARDCLIP_THRESHOLD - SOFTCLIP_THRESHOLD + 1; i++)
228
        softclip_table[i] = SOFTCLIP_THRESHOLD - ((int)(sin((float)i * delta) * dfl) & 0x0000FFFF);
229
}
230

    
231

    
232
// random generated table
233
static av_cold void rnd_table_init(void) {
234
    int i,j;
235
    uint32_t ldw,hdw;
236
    uint64_t tmp64_1;
237
    uint64_t random_seed = 0;
238
    float delta = 1.0 / 16384.0;
239
    for(i = 0; i < 4096 ;i++) {
240
        random_seed = random_seed * 214013 + 2531011;
241
        noise_table[i] = (delta * (float)(((int32_t)random_seed >> 16) & 0x00007FFF)- 1.0) * 1.3;
242
    }
243

    
244
    for (i = 0; i < 256 ;i++) {
245
        random_seed = 81;
246
        ldw = i;
247
        for (j = 0; j < 5 ;j++) {
248
            random_dequant_index[i][j] = (uint8_t)((ldw / random_seed) & 0xFF);
249
            ldw = (uint32_t)ldw % (uint32_t)random_seed;
250
            tmp64_1 = (random_seed * 0x55555556);
251
            hdw = (uint32_t)(tmp64_1 >> 32);
252
            random_seed = (uint64_t)(hdw + (ldw >> 31));
253
        }
254
    }
255
    for (i = 0; i < 128 ;i++) {
256
        random_seed = 25;
257
        ldw = i;
258
        for (j = 0; j < 3 ;j++) {
259
            random_dequant_type24[i][j] = (uint8_t)((ldw / random_seed) & 0xFF);
260
            ldw = (uint32_t)ldw % (uint32_t)random_seed;
261
            tmp64_1 = (random_seed * 0x66666667);
262
            hdw = (uint32_t)(tmp64_1 >> 33);
263
            random_seed = hdw + (ldw >> 31);
264
        }
265
    }
266
}
267

    
268

    
269
static av_cold void init_noise_samples(void) {
270
    int i;
271
    int random_seed = 0;
272
    float delta = 1.0 / 16384.0;
273
    for (i = 0; i < 128;i++) {
274
        random_seed = random_seed * 214013 + 2531011;
275
        noise_samples[i] = (delta * (float)((random_seed >> 16) & 0x00007fff) - 1.0);
276
    }
277
}
278

    
279
static const uint16_t qdm2_vlc_offs[] = {
280
    0,260,566,598,894,1166,1230,1294,1678,1950,2214,2278,2310,2570,2834,3124,3448,3838,
281
};
282

    
283
static av_cold void qdm2_init_vlc(void)
284
{
285
    static int vlcs_initialized = 0;
286
    static VLC_TYPE qdm2_table[3838][2];
287

    
288
    if (!vlcs_initialized) {
289

    
290
        vlc_tab_level.table = &qdm2_table[qdm2_vlc_offs[0]];
291
        vlc_tab_level.table_allocated = qdm2_vlc_offs[1] - qdm2_vlc_offs[0];
292
        init_vlc (&vlc_tab_level, 8, 24,
293
            vlc_tab_level_huffbits, 1, 1,
294
            vlc_tab_level_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
295

    
296
        vlc_tab_diff.table = &qdm2_table[qdm2_vlc_offs[1]];
297
        vlc_tab_diff.table_allocated = qdm2_vlc_offs[2] - qdm2_vlc_offs[1];
298
        init_vlc (&vlc_tab_diff, 8, 37,
299
            vlc_tab_diff_huffbits, 1, 1,
300
            vlc_tab_diff_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
301

    
302
        vlc_tab_run.table = &qdm2_table[qdm2_vlc_offs[2]];
303
        vlc_tab_run.table_allocated = qdm2_vlc_offs[3] - qdm2_vlc_offs[2];
304
        init_vlc (&vlc_tab_run, 5, 6,
305
            vlc_tab_run_huffbits, 1, 1,
306
            vlc_tab_run_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
307

    
308
        fft_level_exp_alt_vlc.table = &qdm2_table[qdm2_vlc_offs[3]];
309
        fft_level_exp_alt_vlc.table_allocated = qdm2_vlc_offs[4] - qdm2_vlc_offs[3];
310
        init_vlc (&fft_level_exp_alt_vlc, 8, 28,
311
            fft_level_exp_alt_huffbits, 1, 1,
312
            fft_level_exp_alt_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
313

    
314

    
315
        fft_level_exp_vlc.table = &qdm2_table[qdm2_vlc_offs[4]];
316
        fft_level_exp_vlc.table_allocated = qdm2_vlc_offs[5] - qdm2_vlc_offs[4];
317
        init_vlc (&fft_level_exp_vlc, 8, 20,
318
            fft_level_exp_huffbits, 1, 1,
319
            fft_level_exp_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
320

    
321
        fft_stereo_exp_vlc.table = &qdm2_table[qdm2_vlc_offs[5]];
322
        fft_stereo_exp_vlc.table_allocated = qdm2_vlc_offs[6] - qdm2_vlc_offs[5];
323
        init_vlc (&fft_stereo_exp_vlc, 6, 7,
324
            fft_stereo_exp_huffbits, 1, 1,
325
            fft_stereo_exp_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
326

    
327
        fft_stereo_phase_vlc.table = &qdm2_table[qdm2_vlc_offs[6]];
328
        fft_stereo_phase_vlc.table_allocated = qdm2_vlc_offs[7] - qdm2_vlc_offs[6];
329
        init_vlc (&fft_stereo_phase_vlc, 6, 9,
330
            fft_stereo_phase_huffbits, 1, 1,
331
            fft_stereo_phase_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
332

    
333
        vlc_tab_tone_level_idx_hi1.table = &qdm2_table[qdm2_vlc_offs[7]];
334
        vlc_tab_tone_level_idx_hi1.table_allocated = qdm2_vlc_offs[8] - qdm2_vlc_offs[7];
335
        init_vlc (&vlc_tab_tone_level_idx_hi1, 8, 20,
336
            vlc_tab_tone_level_idx_hi1_huffbits, 1, 1,
337
            vlc_tab_tone_level_idx_hi1_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
338

    
339
        vlc_tab_tone_level_idx_mid.table = &qdm2_table[qdm2_vlc_offs[8]];
340
        vlc_tab_tone_level_idx_mid.table_allocated = qdm2_vlc_offs[9] - qdm2_vlc_offs[8];
341
        init_vlc (&vlc_tab_tone_level_idx_mid, 8, 24,
342
            vlc_tab_tone_level_idx_mid_huffbits, 1, 1,
343
            vlc_tab_tone_level_idx_mid_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
344

    
345
        vlc_tab_tone_level_idx_hi2.table = &qdm2_table[qdm2_vlc_offs[9]];
346
        vlc_tab_tone_level_idx_hi2.table_allocated = qdm2_vlc_offs[10] - qdm2_vlc_offs[9];
347
        init_vlc (&vlc_tab_tone_level_idx_hi2, 8, 24,
348
            vlc_tab_tone_level_idx_hi2_huffbits, 1, 1,
349
            vlc_tab_tone_level_idx_hi2_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
350

    
351
        vlc_tab_type30.table = &qdm2_table[qdm2_vlc_offs[10]];
352
        vlc_tab_type30.table_allocated = qdm2_vlc_offs[11] - qdm2_vlc_offs[10];
353
        init_vlc (&vlc_tab_type30, 6, 9,
354
            vlc_tab_type30_huffbits, 1, 1,
355
            vlc_tab_type30_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
356

    
357
        vlc_tab_type34.table = &qdm2_table[qdm2_vlc_offs[11]];
358
        vlc_tab_type34.table_allocated = qdm2_vlc_offs[12] - qdm2_vlc_offs[11];
359
        init_vlc (&vlc_tab_type34, 5, 10,
360
            vlc_tab_type34_huffbits, 1, 1,
361
            vlc_tab_type34_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
362

    
363
        vlc_tab_fft_tone_offset[0].table = &qdm2_table[qdm2_vlc_offs[12]];
364
        vlc_tab_fft_tone_offset[0].table_allocated = qdm2_vlc_offs[13] - qdm2_vlc_offs[12];
365
        init_vlc (&vlc_tab_fft_tone_offset[0], 8, 23,
366
            vlc_tab_fft_tone_offset_0_huffbits, 1, 1,
367
            vlc_tab_fft_tone_offset_0_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
368

    
369
        vlc_tab_fft_tone_offset[1].table = &qdm2_table[qdm2_vlc_offs[13]];
370
        vlc_tab_fft_tone_offset[1].table_allocated = qdm2_vlc_offs[14] - qdm2_vlc_offs[13];
371
        init_vlc (&vlc_tab_fft_tone_offset[1], 8, 28,
372
            vlc_tab_fft_tone_offset_1_huffbits, 1, 1,
373
            vlc_tab_fft_tone_offset_1_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
374

    
375
        vlc_tab_fft_tone_offset[2].table = &qdm2_table[qdm2_vlc_offs[14]];
376
        vlc_tab_fft_tone_offset[2].table_allocated = qdm2_vlc_offs[15] - qdm2_vlc_offs[14];
377
        init_vlc (&vlc_tab_fft_tone_offset[2], 8, 32,
378
            vlc_tab_fft_tone_offset_2_huffbits, 1, 1,
379
            vlc_tab_fft_tone_offset_2_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
380

    
381
        vlc_tab_fft_tone_offset[3].table = &qdm2_table[qdm2_vlc_offs[15]];
382
        vlc_tab_fft_tone_offset[3].table_allocated = qdm2_vlc_offs[16] - qdm2_vlc_offs[15];
383
        init_vlc (&vlc_tab_fft_tone_offset[3], 8, 35,
384
            vlc_tab_fft_tone_offset_3_huffbits, 1, 1,
385
            vlc_tab_fft_tone_offset_3_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
386

    
387
        vlc_tab_fft_tone_offset[4].table = &qdm2_table[qdm2_vlc_offs[16]];
388
        vlc_tab_fft_tone_offset[4].table_allocated = qdm2_vlc_offs[17] - qdm2_vlc_offs[16];
389
        init_vlc (&vlc_tab_fft_tone_offset[4], 8, 38,
390
            vlc_tab_fft_tone_offset_4_huffbits, 1, 1,
391
            vlc_tab_fft_tone_offset_4_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
392

    
393
        vlcs_initialized=1;
394
    }
395
}
396

    
397

    
398
/* for floating point to fixed point conversion */
399
static const float f2i_scale = (float) (1 << (FRAC_BITS - 15));
400

    
401

    
402
static int qdm2_get_vlc (GetBitContext *gb, VLC *vlc, int flag, int depth)
403
{
404
    int value;
405

    
406
    value = get_vlc2(gb, vlc->table, vlc->bits, depth);
407

    
408
    /* stage-2, 3 bits exponent escape sequence */
409
    if (value-- == 0)
410
        value = get_bits (gb, get_bits (gb, 3) + 1);
411

    
412
    /* stage-3, optional */
413
    if (flag) {
414
        int tmp = vlc_stage3_values[value];
415

    
416
        if ((value & ~3) > 0)
417
            tmp += get_bits (gb, (value >> 2));
418
        value = tmp;
419
    }
420

    
421
    return value;
422
}
423

    
424

    
425
static int qdm2_get_se_vlc (VLC *vlc, GetBitContext *gb, int depth)
426
{
427
    int value = qdm2_get_vlc (gb, vlc, 0, depth);
428

    
429
    return (value & 1) ? ((value + 1) >> 1) : -(value >> 1);
430
}
431

    
432

    
433
/**
434
 * QDM2 checksum
435
 *
436
 * @param data      pointer to data to be checksum'ed
437
 * @param length    data length
438
 * @param value     checksum value
439
 *
440
 * @return          0 if checksum is OK
441
 */
442
static uint16_t qdm2_packet_checksum (const uint8_t *data, int length, int value) {
443
    int i;
444

    
445
    for (i=0; i < length; i++)
446
        value -= data[i];
447

    
448
    return (uint16_t)(value & 0xffff);
449
}
450

    
451

    
452
/**
453
 * Fills a QDM2SubPacket structure with packet type, size, and data pointer.
454
 *
455
 * @param gb            bitreader context
456
 * @param sub_packet    packet under analysis
457
 */
458
static void qdm2_decode_sub_packet_header (GetBitContext *gb, QDM2SubPacket *sub_packet)
459
{
460
    sub_packet->type = get_bits (gb, 8);
461

    
462
    if (sub_packet->type == 0) {
463
        sub_packet->size = 0;
464
        sub_packet->data = NULL;
465
    } else {
466
        sub_packet->size = get_bits (gb, 8);
467

    
468
      if (sub_packet->type & 0x80) {
469
          sub_packet->size <<= 8;
470
          sub_packet->size  |= get_bits (gb, 8);
471
          sub_packet->type  &= 0x7f;
472
      }
473

    
474
      if (sub_packet->type == 0x7f)
475
          sub_packet->type |= (get_bits (gb, 8) << 8);
476

    
477
      sub_packet->data = &gb->buffer[get_bits_count(gb) / 8]; // FIXME: this depends on bitreader internal data
478
    }
479

    
480
    av_log(NULL,AV_LOG_DEBUG,"Subpacket: type=%d size=%d start_offs=%x\n",
481
        sub_packet->type, sub_packet->size, get_bits_count(gb) / 8);
482
}
483

    
484

    
485
/**
486
 * Return node pointer to first packet of requested type in list.
487
 *
488
 * @param list    list of subpackets to be scanned
489
 * @param type    type of searched subpacket
490
 * @return        node pointer for subpacket if found, else NULL
491
 */
492
static QDM2SubPNode* qdm2_search_subpacket_type_in_list (QDM2SubPNode *list, int type)
493
{
494
    while (list != NULL && list->packet != NULL) {
495
        if (list->packet->type == type)
496
            return list;
497
        list = list->next;
498
    }
499
    return NULL;
500
}
501

    
502

    
503
/**
504
 * Replaces 8 elements with their average value.
505
 * Called by qdm2_decode_superblock before starting subblock decoding.
506
 *
507
 * @param q       context
508
 */
509
static void average_quantized_coeffs (QDM2Context *q)
510
{
511
    int i, j, n, ch, sum;
512

    
513
    n = coeff_per_sb_for_avg[q->coeff_per_sb_select][QDM2_SB_USED(q->sub_sampling) - 1] + 1;
514

    
515
    for (ch = 0; ch < q->nb_channels; ch++)
516
        for (i = 0; i < n; i++) {
517
            sum = 0;
518

    
519
            for (j = 0; j < 8; j++)
520
                sum += q->quantized_coeffs[ch][i][j];
521

    
522
            sum /= 8;
523
            if (sum > 0)
524
                sum--;
525

    
526
            for (j=0; j < 8; j++)
527
                q->quantized_coeffs[ch][i][j] = sum;
528
        }
529
}
530

    
531

    
532
/**
533
 * Build subband samples with noise weighted by q->tone_level.
534
 * Called by synthfilt_build_sb_samples.
535
 *
536
 * @param q     context
537
 * @param sb    subband index
538
 */
539
static void build_sb_samples_from_noise (QDM2Context *q, int sb)
540
{
541
    int ch, j;
542

    
543
    FIX_NOISE_IDX(q->noise_idx);
544

    
545
    if (!q->nb_channels)
546
        return;
547

    
548
    for (ch = 0; ch < q->nb_channels; ch++)
549
        for (j = 0; j < 64; j++) {
550
            q->sb_samples[ch][j * 2][sb] = (int32_t)(f2i_scale * SB_DITHERING_NOISE(sb,q->noise_idx) * q->tone_level[ch][sb][j] + .5);
551
            q->sb_samples[ch][j * 2 + 1][sb] = (int32_t)(f2i_scale * SB_DITHERING_NOISE(sb,q->noise_idx) * q->tone_level[ch][sb][j] + .5);
552
        }
553
}
554

    
555

    
556
/**
557
 * Called while processing data from subpackets 11 and 12.
558
 * Used after making changes to coding_method array.
559
 *
560
 * @param sb               subband index
561
 * @param channels         number of channels
562
 * @param coding_method    q->coding_method[0][0][0]
563
 */
564
static void fix_coding_method_array (int sb, int channels, sb_int8_array coding_method)
565
{
566
    int j,k;
567
    int ch;
568
    int run, case_val;
569
    int switchtable[23] = {0,5,1,5,5,5,5,5,2,5,5,5,5,5,5,5,3,5,5,5,5,5,4};
570

    
571
    for (ch = 0; ch < channels; ch++) {
572
        for (j = 0; j < 64; ) {
573
            if((coding_method[ch][sb][j] - 8) > 22) {
574
                run = 1;
575
                case_val = 8;
576
            } else {
577
                switch (switchtable[coding_method[ch][sb][j]-8]) {
578
                    case 0: run = 10; case_val = 10; break;
579
                    case 1: run = 1; case_val = 16; break;
580
                    case 2: run = 5; case_val = 24; break;
581
                    case 3: run = 3; case_val = 30; break;
582
                    case 4: run = 1; case_val = 30; break;
583
                    case 5: run = 1; case_val = 8; break;
584
                    default: run = 1; case_val = 8; break;
585
                }
586
            }
587
            for (k = 0; k < run; k++)
588
                if (j + k < 128)
589
                    if (coding_method[ch][sb + (j + k) / 64][(j + k) % 64] > coding_method[ch][sb][j])
590
                        if (k > 0) {
591
                           SAMPLES_NEEDED
592
                            //not debugged, almost never used
593
                            memset(&coding_method[ch][sb][j + k], case_val, k * sizeof(int8_t));
594
                            memset(&coding_method[ch][sb][j + k], case_val, 3 * sizeof(int8_t));
595
                        }
596
            j += run;
597
        }
598
    }
599
}
600

    
601

    
602
/**
603
 * Related to synthesis filter
604
 * Called by process_subpacket_10
605
 *
606
 * @param q       context
607
 * @param flag    1 if called after getting data from subpacket 10, 0 if no subpacket 10
608
 */
609
static void fill_tone_level_array (QDM2Context *q, int flag)
610
{
611
    int i, sb, ch, sb_used;
612
    int tmp, tab;
613

    
614
    // This should never happen
615
    if (q->nb_channels <= 0)
616
        return;
617

    
618
    for (ch = 0; ch < q->nb_channels; ch++)
619
        for (sb = 0; sb < 30; sb++)
620
            for (i = 0; i < 8; i++) {
621
                if ((tab=coeff_per_sb_for_dequant[q->coeff_per_sb_select][sb]) < (last_coeff[q->coeff_per_sb_select] - 1))
622
                    tmp = q->quantized_coeffs[ch][tab + 1][i] * dequant_table[q->coeff_per_sb_select][tab + 1][sb]+
623
                          q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];
624
                else
625
                    tmp = q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];
626
                if(tmp < 0)
627
                    tmp += 0xff;
628
                q->tone_level_idx_base[ch][sb][i] = (tmp / 256) & 0xff;
629
            }
630

    
631
    sb_used = QDM2_SB_USED(q->sub_sampling);
632

    
633
    if ((q->superblocktype_2_3 != 0) && !flag) {
634
        for (sb = 0; sb < sb_used; sb++)
635
            for (ch = 0; ch < q->nb_channels; ch++)
636
                for (i = 0; i < 64; i++) {
637
                    q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];
638
                    if (q->tone_level_idx[ch][sb][i] < 0)
639
                        q->tone_level[ch][sb][i] = 0;
640
                    else
641
                        q->tone_level[ch][sb][i] = fft_tone_level_table[0][q->tone_level_idx[ch][sb][i] & 0x3f];
642
                }
643
    } else {
644
        tab = q->superblocktype_2_3 ? 0 : 1;
645
        for (sb = 0; sb < sb_used; sb++) {
646
            if ((sb >= 4) && (sb <= 23)) {
647
                for (ch = 0; ch < q->nb_channels; ch++)
648
                    for (i = 0; i < 64; i++) {
649
                        tmp = q->tone_level_idx_base[ch][sb][i / 8] -
650
                              q->tone_level_idx_hi1[ch][sb / 8][i / 8][i % 8] -
651
                              q->tone_level_idx_mid[ch][sb - 4][i / 8] -
652
                              q->tone_level_idx_hi2[ch][sb - 4];
653
                        q->tone_level_idx[ch][sb][i] = tmp & 0xff;
654
                        if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
655
                            q->tone_level[ch][sb][i] = 0;
656
                        else
657
                            q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
658
                }
659
            } else {
660
                if (sb > 4) {
661
                    for (ch = 0; ch < q->nb_channels; ch++)
662
                        for (i = 0; i < 64; i++) {
663
                            tmp = q->tone_level_idx_base[ch][sb][i / 8] -
664
                                  q->tone_level_idx_hi1[ch][2][i / 8][i % 8] -
665
                                  q->tone_level_idx_hi2[ch][sb - 4];
666
                            q->tone_level_idx[ch][sb][i] = tmp & 0xff;
667
                            if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
668
                                q->tone_level[ch][sb][i] = 0;
669
                            else
670
                                q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
671
                    }
672
                } else {
673
                    for (ch = 0; ch < q->nb_channels; ch++)
674
                        for (i = 0; i < 64; i++) {
675
                            tmp = q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];
676
                            if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
677
                                q->tone_level[ch][sb][i] = 0;
678
                            else
679
                                q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
680
                        }
681
                }
682
            }
683
        }
684
    }
685

    
686
    return;
687
}
688

    
689

    
690
/**
691
 * Related to synthesis filter
692
 * Called by process_subpacket_11
693
 * c is built with data from subpacket 11
694
 * Most of this function is used only if superblock_type_2_3 == 0, never seen it in samples
695
 *
696
 * @param tone_level_idx
697
 * @param tone_level_idx_temp
698
 * @param coding_method        q->coding_method[0][0][0]
699
 * @param nb_channels          number of channels
700
 * @param c                    coming from subpacket 11, passed as 8*c
701
 * @param superblocktype_2_3   flag based on superblock packet type
702
 * @param cm_table_select      q->cm_table_select
703
 */
704
static void fill_coding_method_array (sb_int8_array tone_level_idx, sb_int8_array tone_level_idx_temp,
705
                sb_int8_array coding_method, int nb_channels,
706
                int c, int superblocktype_2_3, int cm_table_select)
707
{
708
    int ch, sb, j;
709
    int tmp, acc, esp_40, comp;
710
    int add1, add2, add3, add4;
711
    int64_t multres;
712

    
713
    // This should never happen
714
    if (nb_channels <= 0)
715
        return;
716

    
717
    if (!superblocktype_2_3) {
718
        /* This case is untested, no samples available */
719
        SAMPLES_NEEDED
720
        for (ch = 0; ch < nb_channels; ch++)
721
            for (sb = 0; sb < 30; sb++) {
722
                for (j = 1; j < 63; j++) {  // The loop only iterates to 63 so the code doesn't overflow the buffer
723
                    add1 = tone_level_idx[ch][sb][j] - 10;
724
                    if (add1 < 0)
725
                        add1 = 0;
726
                    add2 = add3 = add4 = 0;
727
                    if (sb > 1) {
728
                        add2 = tone_level_idx[ch][sb - 2][j] + tone_level_idx_offset_table[sb][0] - 6;
729
                        if (add2 < 0)
730
                            add2 = 0;
731
                    }
732
                    if (sb > 0) {
733
                        add3 = tone_level_idx[ch][sb - 1][j] + tone_level_idx_offset_table[sb][1] - 6;
734
                        if (add3 < 0)
735
                            add3 = 0;
736
                    }
737
                    if (sb < 29) {
738
                        add4 = tone_level_idx[ch][sb + 1][j] + tone_level_idx_offset_table[sb][3] - 6;
739
                        if (add4 < 0)
740
                            add4 = 0;
741
                    }
742
                    tmp = tone_level_idx[ch][sb][j + 1] * 2 - add4 - add3 - add2 - add1;
743
                    if (tmp < 0)
744
                        tmp = 0;
745
                    tone_level_idx_temp[ch][sb][j + 1] = tmp & 0xff;
746
                }
747
                tone_level_idx_temp[ch][sb][0] = tone_level_idx_temp[ch][sb][1];
748
            }
749
            acc = 0;
750
            for (ch = 0; ch < nb_channels; ch++)
751
                for (sb = 0; sb < 30; sb++)
752
                    for (j = 0; j < 64; j++)
753
                        acc += tone_level_idx_temp[ch][sb][j];
754

    
755
            multres = 0x66666667 * (acc * 10);
756
            esp_40 = (multres >> 32) / 8 + ((multres & 0xffffffff) >> 31);
757
            for (ch = 0;  ch < nb_channels; ch++)
758
                for (sb = 0; sb < 30; sb++)
759
                    for (j = 0; j < 64; j++) {
760
                        comp = tone_level_idx_temp[ch][sb][j]* esp_40 * 10;
761
                        if (comp < 0)
762
                            comp += 0xff;
763
                        comp /= 256; // signed shift
764
                        switch(sb) {
765
                            case 0:
766
                                if (comp < 30)
767
                                    comp = 30;
768
                                comp += 15;
769
                                break;
770
                            case 1:
771
                                if (comp < 24)
772
                                    comp = 24;
773
                                comp += 10;
774
                                break;
775
                            case 2:
776
                            case 3:
777
                            case 4:
778
                                if (comp < 16)
779
                                    comp = 16;
780
                        }
781
                        if (comp <= 5)
782
                            tmp = 0;
783
                        else if (comp <= 10)
784
                            tmp = 10;
785
                        else if (comp <= 16)
786
                            tmp = 16;
787
                        else if (comp <= 24)
788
                            tmp = -1;
789
                        else
790
                            tmp = 0;
791
                        coding_method[ch][sb][j] = ((tmp & 0xfffa) + 30 )& 0xff;
792
                    }
793
            for (sb = 0; sb < 30; sb++)
794
                fix_coding_method_array(sb, nb_channels, coding_method);
795
            for (ch = 0; ch < nb_channels; ch++)
796
                for (sb = 0; sb < 30; sb++)
797
                    for (j = 0; j < 64; j++)
798
                        if (sb >= 10) {
799
                            if (coding_method[ch][sb][j] < 10)
800
                                coding_method[ch][sb][j] = 10;
801
                        } else {
802
                            if (sb >= 2) {
803
                                if (coding_method[ch][sb][j] < 16)
804
                                    coding_method[ch][sb][j] = 16;
805
                            } else {
806
                                if (coding_method[ch][sb][j] < 30)
807
                                    coding_method[ch][sb][j] = 30;
808
                            }
809
                        }
810
    } else { // superblocktype_2_3 != 0
811
        for (ch = 0; ch < nb_channels; ch++)
812
            for (sb = 0; sb < 30; sb++)
813
                for (j = 0; j < 64; j++)
814
                    coding_method[ch][sb][j] = coding_method_table[cm_table_select][sb];
815
    }
816

    
817
    return;
818
}
819

    
820

    
821
/**
822
 *
823
 * Called by process_subpacket_11 to process more data from subpacket 11 with sb 0-8
824
 * Called by process_subpacket_12 to process data from subpacket 12 with sb 8-sb_used
825
 *
826
 * @param q         context
827
 * @param gb        bitreader context
828
 * @param length    packet length in bits
829
 * @param sb_min    lower subband processed (sb_min included)
830
 * @param sb_max    higher subband processed (sb_max excluded)
831
 */
832
static void synthfilt_build_sb_samples (QDM2Context *q, GetBitContext *gb, int length, int sb_min, int sb_max)
833
{
834
    int sb, j, k, n, ch, run, channels;
835
    int joined_stereo, zero_encoding, chs;
836
    int type34_first;
837
    float type34_div = 0;
838
    float type34_predictor;
839
    float samples[10], sign_bits[16];
840

    
841
    if (length == 0) {
842
        // If no data use noise
843
        for (sb=sb_min; sb < sb_max; sb++)
844
            build_sb_samples_from_noise (q, sb);
845

    
846
        return;
847
    }
848

    
849
    for (sb = sb_min; sb < sb_max; sb++) {
850
        FIX_NOISE_IDX(q->noise_idx);
851

    
852
        channels = q->nb_channels;
853

    
854
        if (q->nb_channels <= 1 || sb < 12)
855
            joined_stereo = 0;
856
        else if (sb >= 24)
857
            joined_stereo = 1;
858
        else
859
            joined_stereo = (BITS_LEFT(length,gb) >= 1) ? get_bits1 (gb) : 0;
860

    
861
        if (joined_stereo) {
862
            if (BITS_LEFT(length,gb) >= 16)
863
                for (j = 0; j < 16; j++)
864
                    sign_bits[j] = get_bits1 (gb);
865

    
866
            for (j = 0; j < 64; j++)
867
                if (q->coding_method[1][sb][j] > q->coding_method[0][sb][j])
868
                    q->coding_method[0][sb][j] = q->coding_method[1][sb][j];
869

    
870
            fix_coding_method_array(sb, q->nb_channels, q->coding_method);
871
            channels = 1;
872
        }
873

    
874
        for (ch = 0; ch < channels; ch++) {
875
            zero_encoding = (BITS_LEFT(length,gb) >= 1) ? get_bits1(gb) : 0;
876
            type34_predictor = 0.0;
877
            type34_first = 1;
878

    
879
            for (j = 0; j < 128; ) {
880
                switch (q->coding_method[ch][sb][j / 2]) {
881
                    case 8:
882
                        if (BITS_LEFT(length,gb) >= 10) {
883
                            if (zero_encoding) {
884
                                for (k = 0; k < 5; k++) {
885
                                    if ((j + 2 * k) >= 128)
886
                                        break;
887
                                    samples[2 * k] = get_bits1(gb) ? dequant_1bit[joined_stereo][2 * get_bits1(gb)] : 0;
888
                                }
889
                            } else {
890
                                n = get_bits(gb, 8);
891
                                for (k = 0; k < 5; k++)
892
                                    samples[2 * k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];
893
                            }
894
                            for (k = 0; k < 5; k++)
895
                                samples[2 * k + 1] = SB_DITHERING_NOISE(sb,q->noise_idx);
896
                        } else {
897
                            for (k = 0; k < 10; k++)
898
                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
899
                        }
900
                        run = 10;
901
                        break;
902

    
903
                    case 10:
904
                        if (BITS_LEFT(length,gb) >= 1) {
905
                            float f = 0.81;
906

    
907
                            if (get_bits1(gb))
908
                                f = -f;
909
                            f -= noise_samples[((sb + 1) * (j +5 * ch + 1)) & 127] * 9.0 / 40.0;
910
                            samples[0] = f;
911
                        } else {
912
                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
913
                        }
914
                        run = 1;
915
                        break;
916

    
917
                    case 16:
918
                        if (BITS_LEFT(length,gb) >= 10) {
919
                            if (zero_encoding) {
920
                                for (k = 0; k < 5; k++) {
921
                                    if ((j + k) >= 128)
922
                                        break;
923
                                    samples[k] = (get_bits1(gb) == 0) ? 0 : dequant_1bit[joined_stereo][2 * get_bits1(gb)];
924
                                }
925
                            } else {
926
                                n = get_bits (gb, 8);
927
                                for (k = 0; k < 5; k++)
928
                                    samples[k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];
929
                            }
930
                        } else {
931
                            for (k = 0; k < 5; k++)
932
                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
933
                        }
934
                        run = 5;
935
                        break;
936

    
937
                    case 24:
938
                        if (BITS_LEFT(length,gb) >= 7) {
939
                            n = get_bits(gb, 7);
940
                            for (k = 0; k < 3; k++)
941
                                samples[k] = (random_dequant_type24[n][k] - 2.0) * 0.5;
942
                        } else {
943
                            for (k = 0; k < 3; k++)
944
                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
945
                        }
946
                        run = 3;
947
                        break;
948

    
949
                    case 30:
950
                        if (BITS_LEFT(length,gb) >= 4)
951
                            samples[0] = type30_dequant[qdm2_get_vlc(gb, &vlc_tab_type30, 0, 1)];
952
                        else
953
                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
954

    
955
                        run = 1;
956
                        break;
957

    
958
                    case 34:
959
                        if (BITS_LEFT(length,gb) >= 7) {
960
                            if (type34_first) {
961
                                type34_div = (float)(1 << get_bits(gb, 2));
962
                                samples[0] = ((float)get_bits(gb, 5) - 16.0) / 15.0;
963
                                type34_predictor = samples[0];
964
                                type34_first = 0;
965
                            } else {
966
                                samples[0] = type34_delta[qdm2_get_vlc(gb, &vlc_tab_type34, 0, 1)] / type34_div + type34_predictor;
967
                                type34_predictor = samples[0];
968
                            }
969
                        } else {
970
                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
971
                        }
972
                        run = 1;
973
                        break;
974

    
975
                    default:
976
                        samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
977
                        run = 1;
978
                        break;
979
                }
980

    
981
                if (joined_stereo) {
982
                    float tmp[10][MPA_MAX_CHANNELS];
983

    
984
                    for (k = 0; k < run; k++) {
985
                        tmp[k][0] = samples[k];
986
                        tmp[k][1] = (sign_bits[(j + k) / 8]) ? -samples[k] : samples[k];
987
                    }
988
                    for (chs = 0; chs < q->nb_channels; chs++)
989
                        for (k = 0; k < run; k++)
990
                            if ((j + k) < 128)
991
                                q->sb_samples[chs][j + k][sb] = (int32_t)(f2i_scale * q->tone_level[chs][sb][((j + k)/2)] * tmp[k][chs] + .5);
992
                } else {
993
                    for (k = 0; k < run; k++)
994
                        if ((j + k) < 128)
995
                            q->sb_samples[ch][j + k][sb] = (int32_t)(f2i_scale * q->tone_level[ch][sb][(j + k)/2] * samples[k] + .5);
996
                }
997

    
998
                j += run;
999
            } // j loop
1000
        } // channel loop
1001
    } // subband loop
1002
}
1003

    
1004

    
1005
/**
1006
 * Init the first element of a channel in quantized_coeffs with data from packet 10 (quantized_coeffs[ch][0]).
1007
 * This is similar to process_subpacket_9, but for a single channel and for element [0]
1008
 * same VLC tables as process_subpacket_9 are used.
1009
 *
1010
 * @param q         context
1011
 * @param quantized_coeffs    pointer to quantized_coeffs[ch][0]
1012
 * @param gb        bitreader context
1013
 * @param length    packet length in bits
1014
 */
1015
static void init_quantized_coeffs_elem0 (int8_t *quantized_coeffs, GetBitContext *gb, int length)
1016
{
1017
    int i, k, run, level, diff;
1018

    
1019
    if (BITS_LEFT(length,gb) < 16)
1020
        return;
1021
    level = qdm2_get_vlc(gb, &vlc_tab_level, 0, 2);
1022

    
1023
    quantized_coeffs[0] = level;
1024

    
1025
    for (i = 0; i < 7; ) {
1026
        if (BITS_LEFT(length,gb) < 16)
1027
            break;
1028
        run = qdm2_get_vlc(gb, &vlc_tab_run, 0, 1) + 1;
1029

    
1030
        if (BITS_LEFT(length,gb) < 16)
1031
            break;
1032
        diff = qdm2_get_se_vlc(&vlc_tab_diff, gb, 2);
1033

    
1034
        for (k = 1; k <= run; k++)
1035
            quantized_coeffs[i + k] = (level + ((k * diff) / run));
1036

    
1037
        level += diff;
1038
        i += run;
1039
    }
1040
}
1041

    
1042

    
1043
/**
1044
 * Related to synthesis filter, process data from packet 10
1045
 * Init part of quantized_coeffs via function init_quantized_coeffs_elem0
1046
 * Init tone_level_idx_hi1, tone_level_idx_hi2, tone_level_idx_mid with data from packet 10
1047
 *
1048
 * @param q         context
1049
 * @param gb        bitreader context
1050
 * @param length    packet length in bits
1051
 */
1052
static void init_tone_level_dequantization (QDM2Context *q, GetBitContext *gb, int length)
1053
{
1054
    int sb, j, k, n, ch;
1055

    
1056
    for (ch = 0; ch < q->nb_channels; ch++) {
1057
        init_quantized_coeffs_elem0(q->quantized_coeffs[ch][0], gb, length);
1058

    
1059
        if (BITS_LEFT(length,gb) < 16) {
1060
            memset(q->quantized_coeffs[ch][0], 0, 8);
1061
            break;
1062
        }
1063
    }
1064

    
1065
    n = q->sub_sampling + 1;
1066

    
1067
    for (sb = 0; sb < n; sb++)
1068
        for (ch = 0; ch < q->nb_channels; ch++)
1069
            for (j = 0; j < 8; j++) {
1070
                if (BITS_LEFT(length,gb) < 1)
1071
                    break;
1072
                if (get_bits1(gb)) {
1073
                    for (k=0; k < 8; k++) {
1074
                        if (BITS_LEFT(length,gb) < 16)
1075
                            break;
1076
                        q->tone_level_idx_hi1[ch][sb][j][k] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_hi1, 0, 2);
1077
                    }
1078
                } else {
1079
                    for (k=0; k < 8; k++)
1080
                        q->tone_level_idx_hi1[ch][sb][j][k] = 0;
1081
                }
1082
            }
1083

    
1084
    n = QDM2_SB_USED(q->sub_sampling) - 4;
1085

    
1086
    for (sb = 0; sb < n; sb++)
1087
        for (ch = 0; ch < q->nb_channels; ch++) {
1088
            if (BITS_LEFT(length,gb) < 16)
1089
                break;
1090
            q->tone_level_idx_hi2[ch][sb] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_hi2, 0, 2);
1091
            if (sb > 19)
1092
                q->tone_level_idx_hi2[ch][sb] -= 16;
1093
            else
1094
                for (j = 0; j < 8; j++)
1095
                    q->tone_level_idx_mid[ch][sb][j] = -16;
1096
        }
1097

    
1098
    n = QDM2_SB_USED(q->sub_sampling) - 5;
1099

    
1100
    for (sb = 0; sb < n; sb++)
1101
        for (ch = 0; ch < q->nb_channels; ch++)
1102
            for (j = 0; j < 8; j++) {
1103
                if (BITS_LEFT(length,gb) < 16)
1104
                    break;
1105
                q->tone_level_idx_mid[ch][sb][j] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_mid, 0, 2) - 32;
1106
            }
1107
}
1108

    
1109
/**
1110
 * Process subpacket 9, init quantized_coeffs with data from it
1111
 *
1112
 * @param q       context
1113
 * @param node    pointer to node with packet
1114
 */
1115
static void process_subpacket_9 (QDM2Context *q, QDM2SubPNode *node)
1116
{
1117
    GetBitContext gb;
1118
    int i, j, k, n, ch, run, level, diff;
1119

    
1120
    init_get_bits(&gb, node->packet->data, node->packet->size*8);
1121

    
1122
    n = coeff_per_sb_for_avg[q->coeff_per_sb_select][QDM2_SB_USED(q->sub_sampling) - 1] + 1; // same as averagesomething function
1123

    
1124
    for (i = 1; i < n; i++)
1125
        for (ch=0; ch < q->nb_channels; ch++) {
1126
            level = qdm2_get_vlc(&gb, &vlc_tab_level, 0, 2);
1127
            q->quantized_coeffs[ch][i][0] = level;
1128

    
1129
            for (j = 0; j < (8 - 1); ) {
1130
                run = qdm2_get_vlc(&gb, &vlc_tab_run, 0, 1) + 1;
1131
                diff = qdm2_get_se_vlc(&vlc_tab_diff, &gb, 2);
1132

    
1133
                for (k = 1; k <= run; k++)
1134
                    q->quantized_coeffs[ch][i][j + k] = (level + ((k*diff) / run));
1135

    
1136
                level += diff;
1137
                j += run;
1138
            }
1139
        }
1140

    
1141
    for (ch = 0; ch < q->nb_channels; ch++)
1142
        for (i = 0; i < 8; i++)
1143
            q->quantized_coeffs[ch][0][i] = 0;
1144
}
1145

    
1146

    
1147
/**
1148
 * Process subpacket 10 if not null, else
1149
 *
1150
 * @param q         context
1151
 * @param node      pointer to node with packet
1152
 * @param length    packet length in bits
1153
 */
1154
static void process_subpacket_10 (QDM2Context *q, QDM2SubPNode *node, int length)
1155
{
1156
    GetBitContext gb;
1157

    
1158
    init_get_bits(&gb, ((node == NULL) ? empty_buffer : node->packet->data), ((node == NULL) ? 0 : node->packet->size*8));
1159

    
1160
    if (length != 0) {
1161
        init_tone_level_dequantization(q, &gb, length);
1162
        fill_tone_level_array(q, 1);
1163
    } else {
1164
        fill_tone_level_array(q, 0);
1165
    }
1166
}
1167

    
1168

    
1169
/**
1170
 * Process subpacket 11
1171
 *
1172
 * @param q         context
1173
 * @param node      pointer to node with packet
1174
 * @param length    packet length in bit
1175
 */
1176
static void process_subpacket_11 (QDM2Context *q, QDM2SubPNode *node, int length)
1177
{
1178
    GetBitContext gb;
1179

    
1180
    init_get_bits(&gb, ((node == NULL) ? empty_buffer : node->packet->data), ((node == NULL) ? 0 : node->packet->size*8));
1181
    if (length >= 32) {
1182
        int c = get_bits (&gb, 13);
1183

    
1184
        if (c > 3)
1185
            fill_coding_method_array (q->tone_level_idx, q->tone_level_idx_temp, q->coding_method,
1186
                                      q->nb_channels, 8*c, q->superblocktype_2_3, q->cm_table_select);
1187
    }
1188

    
1189
    synthfilt_build_sb_samples(q, &gb, length, 0, 8);
1190
}
1191

    
1192

    
1193
/**
1194
 * Process subpacket 12
1195
 *
1196
 * @param q         context
1197
 * @param node      pointer to node with packet
1198
 * @param length    packet length in bits
1199
 */
1200
static void process_subpacket_12 (QDM2Context *q, QDM2SubPNode *node, int length)
1201
{
1202
    GetBitContext gb;
1203

    
1204
    init_get_bits(&gb, ((node == NULL) ? empty_buffer : node->packet->data), ((node == NULL) ? 0 : node->packet->size*8));
1205
    synthfilt_build_sb_samples(q, &gb, length, 8, QDM2_SB_USED(q->sub_sampling));
1206
}
1207

    
1208
/*
1209
 * Process new subpackets for synthesis filter
1210
 *
1211
 * @param q       context
1212
 * @param list    list with synthesis filter packets (list D)
1213
 */
1214
static void process_synthesis_subpackets (QDM2Context *q, QDM2SubPNode *list)
1215
{
1216
    QDM2SubPNode *nodes[4];
1217

    
1218
    nodes[0] = qdm2_search_subpacket_type_in_list(list, 9);
1219
    if (nodes[0] != NULL)
1220
        process_subpacket_9(q, nodes[0]);
1221

    
1222
    nodes[1] = qdm2_search_subpacket_type_in_list(list, 10);
1223
    if (nodes[1] != NULL)
1224
        process_subpacket_10(q, nodes[1], nodes[1]->packet->size << 3);
1225
    else
1226
        process_subpacket_10(q, NULL, 0);
1227

    
1228
    nodes[2] = qdm2_search_subpacket_type_in_list(list, 11);
1229
    if (nodes[0] != NULL && nodes[1] != NULL && nodes[2] != NULL)
1230
        process_subpacket_11(q, nodes[2], (nodes[2]->packet->size << 3));
1231
    else
1232
        process_subpacket_11(q, NULL, 0);
1233

    
1234
    nodes[3] = qdm2_search_subpacket_type_in_list(list, 12);
1235
    if (nodes[0] != NULL && nodes[1] != NULL && nodes[3] != NULL)
1236
        process_subpacket_12(q, nodes[3], (nodes[3]->packet->size << 3));
1237
    else
1238
        process_subpacket_12(q, NULL, 0);
1239
}
1240

    
1241

    
1242
/*
1243
 * Decode superblock, fill packet lists.
1244
 *
1245
 * @param q    context
1246
 */
1247
static void qdm2_decode_super_block (QDM2Context *q)
1248
{
1249
    GetBitContext gb;
1250
    QDM2SubPacket header, *packet;
1251
    int i, packet_bytes, sub_packet_size, sub_packets_D;
1252
    unsigned int next_index = 0;
1253

    
1254
    memset(q->tone_level_idx_hi1, 0, sizeof(q->tone_level_idx_hi1));
1255
    memset(q->tone_level_idx_mid, 0, sizeof(q->tone_level_idx_mid));
1256
    memset(q->tone_level_idx_hi2, 0, sizeof(q->tone_level_idx_hi2));
1257

    
1258
    q->sub_packets_B = 0;
1259
    sub_packets_D = 0;
1260

    
1261
    average_quantized_coeffs(q); // average elements in quantized_coeffs[max_ch][10][8]
1262

    
1263
    init_get_bits(&gb, q->compressed_data, q->compressed_size*8);
1264
    qdm2_decode_sub_packet_header(&gb, &header);
1265

    
1266
    if (header.type < 2 || header.type >= 8) {
1267
        q->has_errors = 1;
1268
        av_log(NULL,AV_LOG_ERROR,"bad superblock type\n");
1269
        return;
1270
    }
1271

    
1272
    q->superblocktype_2_3 = (header.type == 2 || header.type == 3);
1273
    packet_bytes = (q->compressed_size - get_bits_count(&gb) / 8);
1274

    
1275
    init_get_bits(&gb, header.data, header.size*8);
1276

    
1277
    if (header.type == 2 || header.type == 4 || header.type == 5) {
1278
        int csum = 257 * get_bits(&gb, 8) + 2 * get_bits(&gb, 8);
1279

    
1280
        csum = qdm2_packet_checksum(q->compressed_data, q->checksum_size, csum);
1281

    
1282
        if (csum != 0) {
1283
            q->has_errors = 1;
1284
            av_log(NULL,AV_LOG_ERROR,"bad packet checksum\n");
1285
            return;
1286
        }
1287
    }
1288

    
1289
    q->sub_packet_list_B[0].packet = NULL;
1290
    q->sub_packet_list_D[0].packet = NULL;
1291

    
1292
    for (i = 0; i < 6; i++)
1293
        if (--q->fft_level_exp[i] < 0)
1294
            q->fft_level_exp[i] = 0;
1295

    
1296
    for (i = 0; packet_bytes > 0; i++) {
1297
        int j;
1298

    
1299
        q->sub_packet_list_A[i].next = NULL;
1300

    
1301
        if (i > 0) {
1302
            q->sub_packet_list_A[i - 1].next = &q->sub_packet_list_A[i];
1303

    
1304
            /* seek to next block */
1305
            init_get_bits(&gb, header.data, header.size*8);
1306
            skip_bits(&gb, next_index*8);
1307

    
1308
            if (next_index >= header.size)
1309
                break;
1310
        }
1311

    
1312
        /* decode subpacket */
1313
        packet = &q->sub_packets[i];
1314
        qdm2_decode_sub_packet_header(&gb, packet);
1315
        next_index = packet->size + get_bits_count(&gb) / 8;
1316
        sub_packet_size = ((packet->size > 0xff) ? 1 : 0) + packet->size + 2;
1317

    
1318
        if (packet->type == 0)
1319
            break;
1320

    
1321
        if (sub_packet_size > packet_bytes) {
1322
            if (packet->type != 10 && packet->type != 11 && packet->type != 12)
1323
                break;
1324
            packet->size += packet_bytes - sub_packet_size;
1325
        }
1326

    
1327
        packet_bytes -= sub_packet_size;
1328

    
1329
        /* add subpacket to 'all subpackets' list */
1330
        q->sub_packet_list_A[i].packet = packet;
1331

    
1332
        /* add subpacket to related list */
1333
        if (packet->type == 8) {
1334
            SAMPLES_NEEDED_2("packet type 8");
1335
            return;
1336
        } else if (packet->type >= 9 && packet->type <= 12) {
1337
            /* packets for MPEG Audio like Synthesis Filter */
1338
            QDM2_LIST_ADD(q->sub_packet_list_D, sub_packets_D, packet);
1339
        } else if (packet->type == 13) {
1340
            for (j = 0; j < 6; j++)
1341
                q->fft_level_exp[j] = get_bits(&gb, 6);
1342
        } else if (packet->type == 14) {
1343
            for (j = 0; j < 6; j++)
1344
                q->fft_level_exp[j] = qdm2_get_vlc(&gb, &fft_level_exp_vlc, 0, 2);
1345
        } else if (packet->type == 15) {
1346
            SAMPLES_NEEDED_2("packet type 15")
1347
            return;
1348
        } else if (packet->type >= 16 && packet->type < 48 && !fft_subpackets[packet->type - 16]) {
1349
            /* packets for FFT */
1350
            QDM2_LIST_ADD(q->sub_packet_list_B, q->sub_packets_B, packet);
1351
        }
1352
    } // Packet bytes loop
1353

    
1354
/* **************************************************************** */
1355
    if (q->sub_packet_list_D[0].packet != NULL) {
1356
        process_synthesis_subpackets(q, q->sub_packet_list_D);
1357
        q->do_synth_filter = 1;
1358
    } else if (q->do_synth_filter) {
1359
        process_subpacket_10(q, NULL, 0);
1360
        process_subpacket_11(q, NULL, 0);
1361
        process_subpacket_12(q, NULL, 0);
1362
    }
1363
/* **************************************************************** */
1364
}
1365

    
1366

    
1367
static void qdm2_fft_init_coefficient (QDM2Context *q, int sub_packet,
1368
                       int offset, int duration, int channel,
1369
                       int exp, int phase)
1370
{
1371
    if (q->fft_coefs_min_index[duration] < 0)
1372
        q->fft_coefs_min_index[duration] = q->fft_coefs_index;
1373

    
1374
    q->fft_coefs[q->fft_coefs_index].sub_packet = ((sub_packet >= 16) ? (sub_packet - 16) : sub_packet);
1375
    q->fft_coefs[q->fft_coefs_index].channel = channel;
1376
    q->fft_coefs[q->fft_coefs_index].offset = offset;
1377
    q->fft_coefs[q->fft_coefs_index].exp = exp;
1378
    q->fft_coefs[q->fft_coefs_index].phase = phase;
1379
    q->fft_coefs_index++;
1380
}
1381

    
1382

    
1383
static void qdm2_fft_decode_tones (QDM2Context *q, int duration, GetBitContext *gb, int b)
1384
{
1385
    int channel, stereo, phase, exp;
1386
    int local_int_4,  local_int_8,  stereo_phase,  local_int_10;
1387
    int local_int_14, stereo_exp, local_int_20, local_int_28;
1388
    int n, offset;
1389

    
1390
    local_int_4 = 0;
1391
    local_int_28 = 0;
1392
    local_int_20 = 2;
1393
    local_int_8 = (4 - duration);
1394
    local_int_10 = 1 << (q->group_order - duration - 1);
1395
    offset = 1;
1396

    
1397
    while (1) {
1398
        if (q->superblocktype_2_3) {
1399
            while ((n = qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2)) < 2) {
1400
                offset = 1;
1401
                if (n == 0) {
1402
                    local_int_4 += local_int_10;
1403
                    local_int_28 += (1 << local_int_8);
1404
                } else {
1405
                    local_int_4 += 8*local_int_10;
1406
                    local_int_28 += (8 << local_int_8);
1407
                }
1408
            }
1409
            offset += (n - 2);
1410
        } else {
1411
            offset += qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2);
1412
            while (offset >= (local_int_10 - 1)) {
1413
                offset += (1 - (local_int_10 - 1));
1414
                local_int_4  += local_int_10;
1415
                local_int_28 += (1 << local_int_8);
1416
            }
1417
        }
1418

    
1419
        if (local_int_4 >= q->group_size)
1420
            return;
1421

    
1422
        local_int_14 = (offset >> local_int_8);
1423

    
1424
        if (q->nb_channels > 1) {
1425
            channel = get_bits1(gb);
1426
            stereo = get_bits1(gb);
1427
        } else {
1428
            channel = 0;
1429
            stereo = 0;
1430
        }
1431

    
1432
        exp = qdm2_get_vlc(gb, (b ? &fft_level_exp_vlc : &fft_level_exp_alt_vlc), 0, 2);
1433
        exp += q->fft_level_exp[fft_level_index_table[local_int_14]];
1434
        exp = (exp < 0) ? 0 : exp;
1435

    
1436
        phase = get_bits(gb, 3);
1437
        stereo_exp = 0;
1438
        stereo_phase = 0;
1439

    
1440
        if (stereo) {
1441
            stereo_exp = (exp - qdm2_get_vlc(gb, &fft_stereo_exp_vlc, 0, 1));
1442
            stereo_phase = (phase - qdm2_get_vlc(gb, &fft_stereo_phase_vlc, 0, 1));
1443
            if (stereo_phase < 0)
1444
                stereo_phase += 8;
1445
        }
1446

    
1447
        if (q->frequency_range > (local_int_14 + 1)) {
1448
            int sub_packet = (local_int_20 + local_int_28);
1449

    
1450
            qdm2_fft_init_coefficient(q, sub_packet, offset, duration, channel, exp, phase);
1451
            if (stereo)
1452
                qdm2_fft_init_coefficient(q, sub_packet, offset, duration, (1 - channel), stereo_exp, stereo_phase);
1453
        }
1454

    
1455
        offset++;
1456
    }
1457
}
1458

    
1459

    
1460
static void qdm2_decode_fft_packets (QDM2Context *q)
1461
{
1462
    int i, j, min, max, value, type, unknown_flag;
1463
    GetBitContext gb;
1464

    
1465
    if (q->sub_packet_list_B[0].packet == NULL)
1466
        return;
1467

    
1468
    /* reset minimum indexes for FFT coefficients */
1469
    q->fft_coefs_index = 0;
1470
    for (i=0; i < 5; i++)
1471
        q->fft_coefs_min_index[i] = -1;
1472

    
1473
    /* process subpackets ordered by type, largest type first */
1474
    for (i = 0, max = 256; i < q->sub_packets_B; i++) {
1475
        QDM2SubPacket *packet= NULL;
1476

    
1477
        /* find subpacket with largest type less than max */
1478
        for (j = 0, min = 0; j < q->sub_packets_B; j++) {
1479
            value = q->sub_packet_list_B[j].packet->type;
1480
            if (value > min && value < max) {
1481
                min = value;
1482
                packet = q->sub_packet_list_B[j].packet;
1483
            }
1484
        }
1485

    
1486
        max = min;
1487

    
1488
        /* check for errors (?) */
1489
        if (!packet)
1490
            return;
1491

    
1492
        if (i == 0 && (packet->type < 16 || packet->type >= 48 || fft_subpackets[packet->type - 16]))
1493
            return;
1494

    
1495
        /* decode FFT tones */
1496
        init_get_bits (&gb, packet->data, packet->size*8);
1497

    
1498
        if (packet->type >= 32 && packet->type < 48 && !fft_subpackets[packet->type - 16])
1499
            unknown_flag = 1;
1500
        else
1501
            unknown_flag = 0;
1502

    
1503
        type = packet->type;
1504

    
1505
        if ((type >= 17 && type < 24) || (type >= 33 && type < 40)) {
1506
            int duration = q->sub_sampling + 5 - (type & 15);
1507

    
1508
            if (duration >= 0 && duration < 4)
1509
                qdm2_fft_decode_tones(q, duration, &gb, unknown_flag);
1510
        } else if (type == 31) {
1511
            for (j=0; j < 4; j++)
1512
                qdm2_fft_decode_tones(q, j, &gb, unknown_flag);
1513
        } else if (type == 46) {
1514
            for (j=0; j < 6; j++)
1515
                q->fft_level_exp[j] = get_bits(&gb, 6);
1516
            for (j=0; j < 4; j++)
1517
            qdm2_fft_decode_tones(q, j, &gb, unknown_flag);
1518
        }
1519
    } // Loop on B packets
1520

    
1521
    /* calculate maximum indexes for FFT coefficients */
1522
    for (i = 0, j = -1; i < 5; i++)
1523
        if (q->fft_coefs_min_index[i] >= 0) {
1524
            if (j >= 0)
1525
                q->fft_coefs_max_index[j] = q->fft_coefs_min_index[i];
1526
            j = i;
1527
        }
1528
    if (j >= 0)
1529
        q->fft_coefs_max_index[j] = q->fft_coefs_index;
1530
}
1531

    
1532

    
1533
static void qdm2_fft_generate_tone (QDM2Context *q, FFTTone *tone)
1534
{
1535
   float level, f[6];
1536
   int i;
1537
   QDM2Complex c;
1538
   const double iscale = 2.0*M_PI / 512.0;
1539

    
1540
    tone->phase += tone->phase_shift;
1541

    
1542
    /* calculate current level (maximum amplitude) of tone */
1543
    level = fft_tone_envelope_table[tone->duration][tone->time_index] * tone->level;
1544
    c.im = level * sin(tone->phase*iscale);
1545
    c.re = level * cos(tone->phase*iscale);
1546

    
1547
    /* generate FFT coefficients for tone */
1548
    if (tone->duration >= 3 || tone->cutoff >= 3) {
1549
        tone->complex[0].im += c.im;
1550
        tone->complex[0].re += c.re;
1551
        tone->complex[1].im -= c.im;
1552
        tone->complex[1].re -= c.re;
1553
    } else {
1554
        f[1] = -tone->table[4];
1555
        f[0] =  tone->table[3] - tone->table[0];
1556
        f[2] =  1.0 - tone->table[2] - tone->table[3];
1557
        f[3] =  tone->table[1] + tone->table[4] - 1.0;
1558
        f[4] =  tone->table[0] - tone->table[1];
1559
        f[5] =  tone->table[2];
1560
        for (i = 0; i < 2; i++) {
1561
            tone->complex[fft_cutoff_index_table[tone->cutoff][i]].re += c.re * f[i];
1562
            tone->complex[fft_cutoff_index_table[tone->cutoff][i]].im += c.im *((tone->cutoff <= i) ? -f[i] : f[i]);
1563
        }
1564
        for (i = 0; i < 4; i++) {
1565
            tone->complex[i].re += c.re * f[i+2];
1566
            tone->complex[i].im += c.im * f[i+2];
1567
        }
1568
    }
1569

    
1570
    /* copy the tone if it has not yet died out */
1571
    if (++tone->time_index < ((1 << (5 - tone->duration)) - 1)) {
1572
      memcpy(&q->fft_tones[q->fft_tone_end], tone, sizeof(FFTTone));
1573
      q->fft_tone_end = (q->fft_tone_end + 1) % 1000;
1574
    }
1575
}
1576

    
1577

    
1578
static void qdm2_fft_tone_synthesizer (QDM2Context *q, int sub_packet)
1579
{
1580
    int i, j, ch;
1581
    const double iscale = 0.25 * M_PI;
1582

    
1583
    for (ch = 0; ch < q->channels; ch++) {
1584
        memset(q->fft.complex[ch], 0, q->fft_size * sizeof(QDM2Complex));
1585
    }
1586

    
1587

    
1588
    /* apply FFT tones with duration 4 (1 FFT period) */
1589
    if (q->fft_coefs_min_index[4] >= 0)
1590
        for (i = q->fft_coefs_min_index[4]; i < q->fft_coefs_max_index[4]; i++) {
1591
            float level;
1592
            QDM2Complex c;
1593

    
1594
            if (q->fft_coefs[i].sub_packet != sub_packet)
1595
                break;
1596

    
1597
            ch = (q->channels == 1) ? 0 : q->fft_coefs[i].channel;
1598
            level = (q->fft_coefs[i].exp < 0) ? 0.0 : fft_tone_level_table[q->superblocktype_2_3 ? 0 : 1][q->fft_coefs[i].exp & 63];
1599

    
1600
            c.re = level * cos(q->fft_coefs[i].phase * iscale);
1601
            c.im = level * sin(q->fft_coefs[i].phase * iscale);
1602
            q->fft.complex[ch][q->fft_coefs[i].offset + 0].re += c.re;
1603
            q->fft.complex[ch][q->fft_coefs[i].offset + 0].im += c.im;
1604
            q->fft.complex[ch][q->fft_coefs[i].offset + 1].re -= c.re;
1605
            q->fft.complex[ch][q->fft_coefs[i].offset + 1].im -= c.im;
1606
        }
1607

    
1608
    /* generate existing FFT tones */
1609
    for (i = q->fft_tone_end; i != q->fft_tone_start; ) {
1610
        qdm2_fft_generate_tone(q, &q->fft_tones[q->fft_tone_start]);
1611
        q->fft_tone_start = (q->fft_tone_start + 1) % 1000;
1612
    }
1613

    
1614
    /* create and generate new FFT tones with duration 0 (long) to 3 (short) */
1615
    for (i = 0; i < 4; i++)
1616
        if (q->fft_coefs_min_index[i] >= 0) {
1617
            for (j = q->fft_coefs_min_index[i]; j < q->fft_coefs_max_index[i]; j++) {
1618
                int offset, four_i;
1619
                FFTTone tone;
1620

    
1621
                if (q->fft_coefs[j].sub_packet != sub_packet)
1622
                    break;
1623

    
1624
                four_i = (4 - i);
1625
                offset = q->fft_coefs[j].offset >> four_i;
1626
                ch = (q->channels == 1) ? 0 : q->fft_coefs[j].channel;
1627

    
1628
                if (offset < q->frequency_range) {
1629
                    if (offset < 2)
1630
                        tone.cutoff = offset;
1631
                    else
1632
                        tone.cutoff = (offset >= 60) ? 3 : 2;
1633

    
1634
                    tone.level = (q->fft_coefs[j].exp < 0) ? 0.0 : fft_tone_level_table[q->superblocktype_2_3 ? 0 : 1][q->fft_coefs[j].exp & 63];
1635
                    tone.complex = &q->fft.complex[ch][offset];
1636
                    tone.table = fft_tone_sample_table[i][q->fft_coefs[j].offset - (offset << four_i)];
1637
                    tone.phase = 64 * q->fft_coefs[j].phase - (offset << 8) - 128;
1638
                    tone.phase_shift = (2 * q->fft_coefs[j].offset + 1) << (7 - four_i);
1639
                    tone.duration = i;
1640
                    tone.time_index = 0;
1641

    
1642
                    qdm2_fft_generate_tone(q, &tone);
1643
                }
1644
            }
1645
            q->fft_coefs_min_index[i] = j;
1646
        }
1647
}
1648

    
1649

    
1650
static void qdm2_calculate_fft (QDM2Context *q, int channel, int sub_packet)
1651
{
1652
    const float gain = (q->channels == 1 && q->nb_channels == 2) ? 0.5f : 1.0f;
1653
    int i;
1654
    q->fft.complex[channel][0].re *= 2.0f;
1655
    q->fft.complex[channel][0].im = 0.0f;
1656
    ff_rdft_calc(&q->rdft_ctx, (FFTSample *)q->fft.complex[channel]);
1657
    /* add samples to output buffer */
1658
    for (i = 0; i < ((q->fft_frame_size + 15) & ~15); i++)
1659
        q->output_buffer[q->channels * i + channel] += ((float *) q->fft.complex[channel])[i] * gain;
1660
}
1661

    
1662

    
1663
/**
1664
 * @param q        context
1665
 * @param index    subpacket number
1666
 */
1667
static void qdm2_synthesis_filter (QDM2Context *q, int index)
1668
{
1669
    OUT_INT samples[MPA_MAX_CHANNELS * MPA_FRAME_SIZE];
1670
    int i, k, ch, sb_used, sub_sampling, dither_state = 0;
1671

    
1672
    /* copy sb_samples */
1673
    sb_used = QDM2_SB_USED(q->sub_sampling);
1674

    
1675
    for (ch = 0; ch < q->channels; ch++)
1676
        for (i = 0; i < 8; i++)
1677
            for (k=sb_used; k < SBLIMIT; k++)
1678
                q->sb_samples[ch][(8 * index) + i][k] = 0;
1679

    
1680
    for (ch = 0; ch < q->nb_channels; ch++) {
1681
        OUT_INT *samples_ptr = samples + ch;
1682

    
1683
        for (i = 0; i < 8; i++) {
1684
            ff_mpa_synth_filter(q->synth_buf[ch], &(q->synth_buf_offset[ch]),
1685
                ff_mpa_synth_window, &dither_state,
1686
                samples_ptr, q->nb_channels,
1687
                q->sb_samples[ch][(8 * index) + i]);
1688
            samples_ptr += 32 * q->nb_channels;
1689
        }
1690
    }
1691

    
1692
    /* add samples to output buffer */
1693
    sub_sampling = (4 >> q->sub_sampling);
1694

    
1695
    for (ch = 0; ch < q->channels; ch++)
1696
        for (i = 0; i < q->frame_size; i++)
1697
            q->output_buffer[q->channels * i + ch] += (float)(samples[q->nb_channels * sub_sampling * i + ch] >> (sizeof(OUT_INT)*8-16));
1698
}
1699

    
1700

    
1701
/**
1702
 * Init static data (does not depend on specific file)
1703
 *
1704
 * @param q    context
1705
 */
1706
static av_cold void qdm2_init(QDM2Context *q) {
1707
    static int initialized = 0;
1708

    
1709
    if (initialized != 0)
1710
        return;
1711
    initialized = 1;
1712

    
1713
    qdm2_init_vlc();
1714
    ff_mpa_synth_init(ff_mpa_synth_window);
1715
    softclip_table_init();
1716
    rnd_table_init();
1717
    init_noise_samples();
1718

    
1719
    av_log(NULL, AV_LOG_DEBUG, "init done\n");
1720
}
1721

    
1722

    
1723
#if 0
1724
static void dump_context(QDM2Context *q)
1725
{
1726
    int i;
1727
#define PRINT(a,b) av_log(NULL,AV_LOG_DEBUG," %s = %d\n", a, b);
1728
    PRINT("compressed_data",q->compressed_data);
1729
    PRINT("compressed_size",q->compressed_size);
1730
    PRINT("frame_size",q->frame_size);
1731
    PRINT("checksum_size",q->checksum_size);
1732
    PRINT("channels",q->channels);
1733
    PRINT("nb_channels",q->nb_channels);
1734
    PRINT("fft_frame_size",q->fft_frame_size);
1735
    PRINT("fft_size",q->fft_size);
1736
    PRINT("sub_sampling",q->sub_sampling);
1737
    PRINT("fft_order",q->fft_order);
1738
    PRINT("group_order",q->group_order);
1739
    PRINT("group_size",q->group_size);
1740
    PRINT("sub_packet",q->sub_packet);
1741
    PRINT("frequency_range",q->frequency_range);
1742
    PRINT("has_errors",q->has_errors);
1743
    PRINT("fft_tone_end",q->fft_tone_end);
1744
    PRINT("fft_tone_start",q->fft_tone_start);
1745
    PRINT("fft_coefs_index",q->fft_coefs_index);
1746
    PRINT("coeff_per_sb_select",q->coeff_per_sb_select);
1747
    PRINT("cm_table_select",q->cm_table_select);
1748
    PRINT("noise_idx",q->noise_idx);
1749

1750
    for (i = q->fft_tone_start; i < q->fft_tone_end; i++)
1751
    {
1752
    FFTTone *t = &q->fft_tones[i];
1753

1754
    av_log(NULL,AV_LOG_DEBUG,"Tone (%d) dump:\n", i);
1755
    av_log(NULL,AV_LOG_DEBUG,"  level = %f\n", t->level);
1756
//  PRINT(" level", t->level);
1757
    PRINT(" phase", t->phase);
1758
    PRINT(" phase_shift", t->phase_shift);
1759
    PRINT(" duration", t->duration);
1760
    PRINT(" samples_im", t->samples_im);
1761
    PRINT(" samples_re", t->samples_re);
1762
    PRINT(" table", t->table);
1763
    }
1764

1765
}
1766
#endif
1767

    
1768

    
1769
/**
1770
 * Init parameters from codec extradata
1771
 */
1772
static av_cold int qdm2_decode_init(AVCodecContext *avctx)
1773
{
1774
    QDM2Context *s = avctx->priv_data;
1775
    uint8_t *extradata;
1776
    int extradata_size;
1777
    int tmp_val, tmp, size;
1778

    
1779
    /* extradata parsing
1780

1781
    Structure:
1782
    wave {
1783
        frma (QDM2)
1784
        QDCA
1785
        QDCP
1786
    }
1787

1788
    32  size (including this field)
1789
    32  tag (=frma)
1790
    32  type (=QDM2 or QDMC)
1791

1792
    32  size (including this field, in bytes)
1793
    32  tag (=QDCA) // maybe mandatory parameters
1794
    32  unknown (=1)
1795
    32  channels (=2)
1796
    32  samplerate (=44100)
1797
    32  bitrate (=96000)
1798
    32  block size (=4096)
1799
    32  frame size (=256) (for one channel)
1800
    32  packet size (=1300)
1801

1802
    32  size (including this field, in bytes)
1803
    32  tag (=QDCP) // maybe some tuneable parameters
1804
    32  float1 (=1.0)
1805
    32  zero ?
1806
    32  float2 (=1.0)
1807
    32  float3 (=1.0)
1808
    32  unknown (27)
1809
    32  unknown (8)
1810
    32  zero ?
1811
    */
1812

    
1813
    if (!avctx->extradata || (avctx->extradata_size < 48)) {
1814
        av_log(avctx, AV_LOG_ERROR, "extradata missing or truncated\n");
1815
        return -1;
1816
    }
1817

    
1818
    extradata = avctx->extradata;
1819
    extradata_size = avctx->extradata_size;
1820

    
1821
    while (extradata_size > 7) {
1822
        if (!memcmp(extradata, "frmaQDM", 7))
1823
            break;
1824
        extradata++;
1825
        extradata_size--;
1826
    }
1827

    
1828
    if (extradata_size < 12) {
1829
        av_log(avctx, AV_LOG_ERROR, "not enough extradata (%i)\n",
1830
               extradata_size);
1831
        return -1;
1832
    }
1833

    
1834
    if (memcmp(extradata, "frmaQDM", 7)) {
1835
        av_log(avctx, AV_LOG_ERROR, "invalid headers, QDM? not found\n");
1836
        return -1;
1837
    }
1838

    
1839
    if (extradata[7] == 'C') {
1840
//        s->is_qdmc = 1;
1841
        av_log(avctx, AV_LOG_ERROR, "stream is QDMC version 1, which is not supported\n");
1842
        return -1;
1843
    }
1844

    
1845
    extradata += 8;
1846
    extradata_size -= 8;
1847

    
1848
    size = AV_RB32(extradata);
1849

    
1850
    if(size > extradata_size){
1851
        av_log(avctx, AV_LOG_ERROR, "extradata size too small, %i < %i\n",
1852
               extradata_size, size);
1853
        return -1;
1854
    }
1855

    
1856
    extradata += 4;
1857
    av_log(avctx, AV_LOG_DEBUG, "size: %d\n", size);
1858
    if (AV_RB32(extradata) != MKBETAG('Q','D','C','A')) {
1859
        av_log(avctx, AV_LOG_ERROR, "invalid extradata, expecting QDCA\n");
1860
        return -1;
1861
    }
1862

    
1863
    extradata += 8;
1864

    
1865
    avctx->channels = s->nb_channels = s->channels = AV_RB32(extradata);
1866
    extradata += 4;
1867

    
1868
    avctx->sample_rate = AV_RB32(extradata);
1869
    extradata += 4;
1870

    
1871
    avctx->bit_rate = AV_RB32(extradata);
1872
    extradata += 4;
1873

    
1874
    s->group_size = AV_RB32(extradata);
1875
    extradata += 4;
1876

    
1877
    s->fft_size = AV_RB32(extradata);
1878
    extradata += 4;
1879

    
1880
    s->checksum_size = AV_RB32(extradata);
1881

    
1882
    s->fft_order = av_log2(s->fft_size) + 1;
1883
    s->fft_frame_size = 2 * s->fft_size; // complex has two floats
1884

    
1885
    // something like max decodable tones
1886
    s->group_order = av_log2(s->group_size) + 1;
1887
    s->frame_size = s->group_size / 16; // 16 iterations per super block
1888

    
1889
    s->sub_sampling = s->fft_order - 7;
1890
    s->frequency_range = 255 / (1 << (2 - s->sub_sampling));
1891

    
1892
    switch ((s->sub_sampling * 2 + s->channels - 1)) {
1893
        case 0: tmp = 40; break;
1894
        case 1: tmp = 48; break;
1895
        case 2: tmp = 56; break;
1896
        case 3: tmp = 72; break;
1897
        case 4: tmp = 80; break;
1898
        case 5: tmp = 100;break;
1899
        default: tmp=s->sub_sampling; break;
1900
    }
1901
    tmp_val = 0;
1902
    if ((tmp * 1000) < avctx->bit_rate)  tmp_val = 1;
1903
    if ((tmp * 1440) < avctx->bit_rate)  tmp_val = 2;
1904
    if ((tmp * 1760) < avctx->bit_rate)  tmp_val = 3;
1905
    if ((tmp * 2240) < avctx->bit_rate)  tmp_val = 4;
1906
    s->cm_table_select = tmp_val;
1907

    
1908
    if (s->sub_sampling == 0)
1909
        tmp = 7999;
1910
    else
1911
        tmp = ((-(s->sub_sampling -1)) & 8000) + 20000;
1912
    /*
1913
    0: 7999 -> 0
1914
    1: 20000 -> 2
1915
    2: 28000 -> 2
1916
    */
1917
    if (tmp < 8000)
1918
        s->coeff_per_sb_select = 0;
1919
    else if (tmp <= 16000)
1920
        s->coeff_per_sb_select = 1;
1921
    else
1922
        s->coeff_per_sb_select = 2;
1923

    
1924
    // Fail on unknown fft order
1925
    if ((s->fft_order < 7) || (s->fft_order > 9)) {
1926
        av_log(avctx, AV_LOG_ERROR, "Unknown FFT order (%d), contact the developers!\n", s->fft_order);
1927
        return -1;
1928
    }
1929

    
1930
    ff_rdft_init(&s->rdft_ctx, s->fft_order, IRDFT);
1931

    
1932
    qdm2_init(s);
1933

    
1934
    avctx->sample_fmt = SAMPLE_FMT_S16;
1935

    
1936
//    dump_context(s);
1937
    return 0;
1938
}
1939

    
1940

    
1941
static av_cold int qdm2_decode_close(AVCodecContext *avctx)
1942
{
1943
    QDM2Context *s = avctx->priv_data;
1944

    
1945
    ff_rdft_end(&s->rdft_ctx);
1946

    
1947
    return 0;
1948
}
1949

    
1950

    
1951
static void qdm2_decode (QDM2Context *q, const uint8_t *in, int16_t *out)
1952
{
1953
    int ch, i;
1954
    const int frame_size = (q->frame_size * q->channels);
1955

    
1956
    /* select input buffer */
1957
    q->compressed_data = in;
1958
    q->compressed_size = q->checksum_size;
1959

    
1960
//  dump_context(q);
1961

    
1962
    /* copy old block, clear new block of output samples */
1963
    memmove(q->output_buffer, &q->output_buffer[frame_size], frame_size * sizeof(float));
1964
    memset(&q->output_buffer[frame_size], 0, frame_size * sizeof(float));
1965

    
1966
    /* decode block of QDM2 compressed data */
1967
    if (q->sub_packet == 0) {
1968
        q->has_errors = 0; // zero it for a new super block
1969
        av_log(NULL,AV_LOG_DEBUG,"Superblock follows\n");
1970
        qdm2_decode_super_block(q);
1971
    }
1972

    
1973
    /* parse subpackets */
1974
    if (!q->has_errors) {
1975
        if (q->sub_packet == 2)
1976
            qdm2_decode_fft_packets(q);
1977

    
1978
        qdm2_fft_tone_synthesizer(q, q->sub_packet);
1979
    }
1980

    
1981
    /* sound synthesis stage 1 (FFT) */
1982
    for (ch = 0; ch < q->channels; ch++) {
1983
        qdm2_calculate_fft(q, ch, q->sub_packet);
1984

    
1985
        if (!q->has_errors && q->sub_packet_list_C[0].packet != NULL) {
1986
            SAMPLES_NEEDED_2("has errors, and C list is not empty")
1987
            return;
1988
        }
1989
    }
1990

    
1991
    /* sound synthesis stage 2 (MPEG audio like synthesis filter) */
1992
    if (!q->has_errors && q->do_synth_filter)
1993
        qdm2_synthesis_filter(q, q->sub_packet);
1994

    
1995
    q->sub_packet = (q->sub_packet + 1) % 16;
1996

    
1997
    /* clip and convert output float[] to 16bit signed samples */
1998
    for (i = 0; i < frame_size; i++) {
1999
        int value = (int)q->output_buffer[i];
2000

    
2001
        if (value > SOFTCLIP_THRESHOLD)
2002
            value = (value >  HARDCLIP_THRESHOLD) ?  32767 :  softclip_table[ value - SOFTCLIP_THRESHOLD];
2003
        else if (value < -SOFTCLIP_THRESHOLD)
2004
            value = (value < -HARDCLIP_THRESHOLD) ? -32767 : -softclip_table[-value - SOFTCLIP_THRESHOLD];
2005

    
2006
        out[i] = value;
2007
    }
2008
}
2009

    
2010

    
2011
static int qdm2_decode_frame(AVCodecContext *avctx,
2012
            void *data, int *data_size,
2013
            AVPacket *avpkt)
2014
{
2015
    const uint8_t *buf = avpkt->data;
2016
    int buf_size = avpkt->size;
2017
    QDM2Context *s = avctx->priv_data;
2018

    
2019
    if(!buf)
2020
        return 0;
2021
    if(buf_size < s->checksum_size)
2022
        return -1;
2023

    
2024
    *data_size = s->channels * s->frame_size * sizeof(int16_t);
2025

    
2026
    av_log(avctx, AV_LOG_DEBUG, "decode(%d): %p[%d] -> %p[%d]\n",
2027
       buf_size, buf, s->checksum_size, data, *data_size);
2028

    
2029
    qdm2_decode(s, buf, data);
2030

    
2031
    // reading only when next superblock found
2032
    if (s->sub_packet == 0) {
2033
        return s->checksum_size;
2034
    }
2035

    
2036
    return 0;
2037
}
2038

    
2039
AVCodec qdm2_decoder =
2040
{
2041
    .name = "qdm2",
2042
    .type = CODEC_TYPE_AUDIO,
2043
    .id = CODEC_ID_QDM2,
2044
    .priv_data_size = sizeof(QDM2Context),
2045
    .init = qdm2_decode_init,
2046
    .close = qdm2_decode_close,
2047
    .decode = qdm2_decode_frame,
2048
    .long_name = NULL_IF_CONFIG_SMALL("QDesign Music Codec 2"),
2049
};