Statistics
| Branch: | Revision:

ffmpeg / libavcodec / qdm2.c @ 72415b2a

History | View | Annotate | Download (67 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 "fft.h"
42
#include "mpegaudio.h"
43

    
44
#include "qdm2data.h"
45
#include "qdm2_tablegen.h"
46

    
47
#undef NDEBUG
48
#include <assert.h>
49

    
50

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

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

    
64
#define FIX_NOISE_IDX(noise_idx) \
65
  if ((noise_idx) >= 3840) \
66
    (noise_idx) -= 3840; \
67

    
68
#define SB_DITHERING_NOISE(sb,noise_idx) (noise_table[(noise_idx)++] * sb_noise_attenuation[(sb)])
69

    
70
#define BITS_LEFT(length,gb) ((length) - get_bits_count ((gb)))
71

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

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

    
78

    
79
typedef int8_t sb_int8_array[2][30][64];
80

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

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

    
98
typedef struct {
99
    float re;
100
    float im;
101
} QDM2Complex;
102

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

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

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

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

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

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

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

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

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

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

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

    
193
    int sub_packet;
194
    int noise_idx; ///< index for dithering noise table
195
} QDM2Context;
196

    
197

    
198
static uint8_t empty_buffer[FF_INPUT_BUFFER_PADDING_SIZE];
199

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

    
214
static const uint16_t qdm2_vlc_offs[] = {
215
    0,260,566,598,894,1166,1230,1294,1678,1950,2214,2278,2310,2570,2834,3124,3448,3838,
216
};
217

    
218
static av_cold void qdm2_init_vlc(void)
219
{
220
    static int vlcs_initialized = 0;
221
    static VLC_TYPE qdm2_table[3838][2];
222

    
223
    if (!vlcs_initialized) {
224

    
225
        vlc_tab_level.table = &qdm2_table[qdm2_vlc_offs[0]];
226
        vlc_tab_level.table_allocated = qdm2_vlc_offs[1] - qdm2_vlc_offs[0];
227
        init_vlc (&vlc_tab_level, 8, 24,
228
            vlc_tab_level_huffbits, 1, 1,
229
            vlc_tab_level_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
230

    
231
        vlc_tab_diff.table = &qdm2_table[qdm2_vlc_offs[1]];
232
        vlc_tab_diff.table_allocated = qdm2_vlc_offs[2] - qdm2_vlc_offs[1];
233
        init_vlc (&vlc_tab_diff, 8, 37,
234
            vlc_tab_diff_huffbits, 1, 1,
235
            vlc_tab_diff_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
236

    
237
        vlc_tab_run.table = &qdm2_table[qdm2_vlc_offs[2]];
238
        vlc_tab_run.table_allocated = qdm2_vlc_offs[3] - qdm2_vlc_offs[2];
239
        init_vlc (&vlc_tab_run, 5, 6,
240
            vlc_tab_run_huffbits, 1, 1,
241
            vlc_tab_run_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
242

    
243
        fft_level_exp_alt_vlc.table = &qdm2_table[qdm2_vlc_offs[3]];
244
        fft_level_exp_alt_vlc.table_allocated = qdm2_vlc_offs[4] - qdm2_vlc_offs[3];
245
        init_vlc (&fft_level_exp_alt_vlc, 8, 28,
246
            fft_level_exp_alt_huffbits, 1, 1,
247
            fft_level_exp_alt_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
248

    
249

    
250
        fft_level_exp_vlc.table = &qdm2_table[qdm2_vlc_offs[4]];
251
        fft_level_exp_vlc.table_allocated = qdm2_vlc_offs[5] - qdm2_vlc_offs[4];
252
        init_vlc (&fft_level_exp_vlc, 8, 20,
253
            fft_level_exp_huffbits, 1, 1,
254
            fft_level_exp_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
255

    
256
        fft_stereo_exp_vlc.table = &qdm2_table[qdm2_vlc_offs[5]];
257
        fft_stereo_exp_vlc.table_allocated = qdm2_vlc_offs[6] - qdm2_vlc_offs[5];
258
        init_vlc (&fft_stereo_exp_vlc, 6, 7,
259
            fft_stereo_exp_huffbits, 1, 1,
260
            fft_stereo_exp_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
261

    
262
        fft_stereo_phase_vlc.table = &qdm2_table[qdm2_vlc_offs[6]];
263
        fft_stereo_phase_vlc.table_allocated = qdm2_vlc_offs[7] - qdm2_vlc_offs[6];
264
        init_vlc (&fft_stereo_phase_vlc, 6, 9,
265
            fft_stereo_phase_huffbits, 1, 1,
266
            fft_stereo_phase_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
267

    
268
        vlc_tab_tone_level_idx_hi1.table = &qdm2_table[qdm2_vlc_offs[7]];
269
        vlc_tab_tone_level_idx_hi1.table_allocated = qdm2_vlc_offs[8] - qdm2_vlc_offs[7];
270
        init_vlc (&vlc_tab_tone_level_idx_hi1, 8, 20,
271
            vlc_tab_tone_level_idx_hi1_huffbits, 1, 1,
272
            vlc_tab_tone_level_idx_hi1_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
273

    
274
        vlc_tab_tone_level_idx_mid.table = &qdm2_table[qdm2_vlc_offs[8]];
275
        vlc_tab_tone_level_idx_mid.table_allocated = qdm2_vlc_offs[9] - qdm2_vlc_offs[8];
276
        init_vlc (&vlc_tab_tone_level_idx_mid, 8, 24,
277
            vlc_tab_tone_level_idx_mid_huffbits, 1, 1,
278
            vlc_tab_tone_level_idx_mid_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
279

    
280
        vlc_tab_tone_level_idx_hi2.table = &qdm2_table[qdm2_vlc_offs[9]];
281
        vlc_tab_tone_level_idx_hi2.table_allocated = qdm2_vlc_offs[10] - qdm2_vlc_offs[9];
282
        init_vlc (&vlc_tab_tone_level_idx_hi2, 8, 24,
283
            vlc_tab_tone_level_idx_hi2_huffbits, 1, 1,
284
            vlc_tab_tone_level_idx_hi2_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
285

    
286
        vlc_tab_type30.table = &qdm2_table[qdm2_vlc_offs[10]];
287
        vlc_tab_type30.table_allocated = qdm2_vlc_offs[11] - qdm2_vlc_offs[10];
288
        init_vlc (&vlc_tab_type30, 6, 9,
289
            vlc_tab_type30_huffbits, 1, 1,
290
            vlc_tab_type30_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
291

    
292
        vlc_tab_type34.table = &qdm2_table[qdm2_vlc_offs[11]];
293
        vlc_tab_type34.table_allocated = qdm2_vlc_offs[12] - qdm2_vlc_offs[11];
294
        init_vlc (&vlc_tab_type34, 5, 10,
295
            vlc_tab_type34_huffbits, 1, 1,
296
            vlc_tab_type34_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
297

    
298
        vlc_tab_fft_tone_offset[0].table = &qdm2_table[qdm2_vlc_offs[12]];
299
        vlc_tab_fft_tone_offset[0].table_allocated = qdm2_vlc_offs[13] - qdm2_vlc_offs[12];
300
        init_vlc (&vlc_tab_fft_tone_offset[0], 8, 23,
301
            vlc_tab_fft_tone_offset_0_huffbits, 1, 1,
302
            vlc_tab_fft_tone_offset_0_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
303

    
304
        vlc_tab_fft_tone_offset[1].table = &qdm2_table[qdm2_vlc_offs[13]];
305
        vlc_tab_fft_tone_offset[1].table_allocated = qdm2_vlc_offs[14] - qdm2_vlc_offs[13];
306
        init_vlc (&vlc_tab_fft_tone_offset[1], 8, 28,
307
            vlc_tab_fft_tone_offset_1_huffbits, 1, 1,
308
            vlc_tab_fft_tone_offset_1_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
309

    
310
        vlc_tab_fft_tone_offset[2].table = &qdm2_table[qdm2_vlc_offs[14]];
311
        vlc_tab_fft_tone_offset[2].table_allocated = qdm2_vlc_offs[15] - qdm2_vlc_offs[14];
312
        init_vlc (&vlc_tab_fft_tone_offset[2], 8, 32,
313
            vlc_tab_fft_tone_offset_2_huffbits, 1, 1,
314
            vlc_tab_fft_tone_offset_2_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
315

    
316
        vlc_tab_fft_tone_offset[3].table = &qdm2_table[qdm2_vlc_offs[15]];
317
        vlc_tab_fft_tone_offset[3].table_allocated = qdm2_vlc_offs[16] - qdm2_vlc_offs[15];
318
        init_vlc (&vlc_tab_fft_tone_offset[3], 8, 35,
319
            vlc_tab_fft_tone_offset_3_huffbits, 1, 1,
320
            vlc_tab_fft_tone_offset_3_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
321

    
322
        vlc_tab_fft_tone_offset[4].table = &qdm2_table[qdm2_vlc_offs[16]];
323
        vlc_tab_fft_tone_offset[4].table_allocated = qdm2_vlc_offs[17] - qdm2_vlc_offs[16];
324
        init_vlc (&vlc_tab_fft_tone_offset[4], 8, 38,
325
            vlc_tab_fft_tone_offset_4_huffbits, 1, 1,
326
            vlc_tab_fft_tone_offset_4_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
327

    
328
        vlcs_initialized=1;
329
    }
330
}
331

    
332

    
333
/* for floating point to fixed point conversion */
334
static const float f2i_scale = (float) (1 << (FRAC_BITS - 15));
335

    
336

    
337
static int qdm2_get_vlc (GetBitContext *gb, VLC *vlc, int flag, int depth)
338
{
339
    int value;
340

    
341
    value = get_vlc2(gb, vlc->table, vlc->bits, depth);
342

    
343
    /* stage-2, 3 bits exponent escape sequence */
344
    if (value-- == 0)
345
        value = get_bits (gb, get_bits (gb, 3) + 1);
346

    
347
    /* stage-3, optional */
348
    if (flag) {
349
        int tmp = vlc_stage3_values[value];
350

    
351
        if ((value & ~3) > 0)
352
            tmp += get_bits (gb, (value >> 2));
353
        value = tmp;
354
    }
355

    
356
    return value;
357
}
358

    
359

    
360
static int qdm2_get_se_vlc (VLC *vlc, GetBitContext *gb, int depth)
361
{
362
    int value = qdm2_get_vlc (gb, vlc, 0, depth);
363

    
364
    return (value & 1) ? ((value + 1) >> 1) : -(value >> 1);
365
}
366

    
367

    
368
/**
369
 * QDM2 checksum
370
 *
371
 * @param data      pointer to data to be checksum'ed
372
 * @param length    data length
373
 * @param value     checksum value
374
 *
375
 * @return          0 if checksum is OK
376
 */
377
static uint16_t qdm2_packet_checksum (const uint8_t *data, int length, int value) {
378
    int i;
379

    
380
    for (i=0; i < length; i++)
381
        value -= data[i];
382

    
383
    return (uint16_t)(value & 0xffff);
384
}
385

    
386

    
387
/**
388
 * Fills a QDM2SubPacket structure with packet type, size, and data pointer.
389
 *
390
 * @param gb            bitreader context
391
 * @param sub_packet    packet under analysis
392
 */
393
static void qdm2_decode_sub_packet_header (GetBitContext *gb, QDM2SubPacket *sub_packet)
394
{
395
    sub_packet->type = get_bits (gb, 8);
396

    
397
    if (sub_packet->type == 0) {
398
        sub_packet->size = 0;
399
        sub_packet->data = NULL;
400
    } else {
401
        sub_packet->size = get_bits (gb, 8);
402

    
403
      if (sub_packet->type & 0x80) {
404
          sub_packet->size <<= 8;
405
          sub_packet->size  |= get_bits (gb, 8);
406
          sub_packet->type  &= 0x7f;
407
      }
408

    
409
      if (sub_packet->type == 0x7f)
410
          sub_packet->type |= (get_bits (gb, 8) << 8);
411

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

    
415
    av_log(NULL,AV_LOG_DEBUG,"Subpacket: type=%d size=%d start_offs=%x\n",
416
        sub_packet->type, sub_packet->size, get_bits_count(gb) / 8);
417
}
418

    
419

    
420
/**
421
 * Return node pointer to first packet of requested type in list.
422
 *
423
 * @param list    list of subpackets to be scanned
424
 * @param type    type of searched subpacket
425
 * @return        node pointer for subpacket if found, else NULL
426
 */
427
static QDM2SubPNode* qdm2_search_subpacket_type_in_list (QDM2SubPNode *list, int type)
428
{
429
    while (list != NULL && list->packet != NULL) {
430
        if (list->packet->type == type)
431
            return list;
432
        list = list->next;
433
    }
434
    return NULL;
435
}
436

    
437

    
438
/**
439
 * Replaces 8 elements with their average value.
440
 * Called by qdm2_decode_superblock before starting subblock decoding.
441
 *
442
 * @param q       context
443
 */
444
static void average_quantized_coeffs (QDM2Context *q)
445
{
446
    int i, j, n, ch, sum;
447

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

    
450
    for (ch = 0; ch < q->nb_channels; ch++)
451
        for (i = 0; i < n; i++) {
452
            sum = 0;
453

    
454
            for (j = 0; j < 8; j++)
455
                sum += q->quantized_coeffs[ch][i][j];
456

    
457
            sum /= 8;
458
            if (sum > 0)
459
                sum--;
460

    
461
            for (j=0; j < 8; j++)
462
                q->quantized_coeffs[ch][i][j] = sum;
463
        }
464
}
465

    
466

    
467
/**
468
 * Build subband samples with noise weighted by q->tone_level.
469
 * Called by synthfilt_build_sb_samples.
470
 *
471
 * @param q     context
472
 * @param sb    subband index
473
 */
474
static void build_sb_samples_from_noise (QDM2Context *q, int sb)
475
{
476
    int ch, j;
477

    
478
    FIX_NOISE_IDX(q->noise_idx);
479

    
480
    if (!q->nb_channels)
481
        return;
482

    
483
    for (ch = 0; ch < q->nb_channels; ch++)
484
        for (j = 0; j < 64; j++) {
485
            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);
486
            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);
487
        }
488
}
489

    
490

    
491
/**
492
 * Called while processing data from subpackets 11 and 12.
493
 * Used after making changes to coding_method array.
494
 *
495
 * @param sb               subband index
496
 * @param channels         number of channels
497
 * @param coding_method    q->coding_method[0][0][0]
498
 */
499
static void fix_coding_method_array (int sb, int channels, sb_int8_array coding_method)
500
{
501
    int j,k;
502
    int ch;
503
    int run, case_val;
504
    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};
505

    
506
    for (ch = 0; ch < channels; ch++) {
507
        for (j = 0; j < 64; ) {
508
            if((coding_method[ch][sb][j] - 8) > 22) {
509
                run = 1;
510
                case_val = 8;
511
            } else {
512
                switch (switchtable[coding_method[ch][sb][j]-8]) {
513
                    case 0: run = 10; case_val = 10; break;
514
                    case 1: run = 1; case_val = 16; break;
515
                    case 2: run = 5; case_val = 24; break;
516
                    case 3: run = 3; case_val = 30; break;
517
                    case 4: run = 1; case_val = 30; break;
518
                    case 5: run = 1; case_val = 8; break;
519
                    default: run = 1; case_val = 8; break;
520
                }
521
            }
522
            for (k = 0; k < run; k++)
523
                if (j + k < 128)
524
                    if (coding_method[ch][sb + (j + k) / 64][(j + k) % 64] > coding_method[ch][sb][j])
525
                        if (k > 0) {
526
                           SAMPLES_NEEDED
527
                            //not debugged, almost never used
528
                            memset(&coding_method[ch][sb][j + k], case_val, k * sizeof(int8_t));
529
                            memset(&coding_method[ch][sb][j + k], case_val, 3 * sizeof(int8_t));
530
                        }
531
            j += run;
532
        }
533
    }
534
}
535

    
536

    
537
/**
538
 * Related to synthesis filter
539
 * Called by process_subpacket_10
540
 *
541
 * @param q       context
542
 * @param flag    1 if called after getting data from subpacket 10, 0 if no subpacket 10
543
 */
544
static void fill_tone_level_array (QDM2Context *q, int flag)
545
{
546
    int i, sb, ch, sb_used;
547
    int tmp, tab;
548

    
549
    // This should never happen
550
    if (q->nb_channels <= 0)
551
        return;
552

    
553
    for (ch = 0; ch < q->nb_channels; ch++)
554
        for (sb = 0; sb < 30; sb++)
555
            for (i = 0; i < 8; i++) {
556
                if ((tab=coeff_per_sb_for_dequant[q->coeff_per_sb_select][sb]) < (last_coeff[q->coeff_per_sb_select] - 1))
557
                    tmp = q->quantized_coeffs[ch][tab + 1][i] * dequant_table[q->coeff_per_sb_select][tab + 1][sb]+
558
                          q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];
559
                else
560
                    tmp = q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];
561
                if(tmp < 0)
562
                    tmp += 0xff;
563
                q->tone_level_idx_base[ch][sb][i] = (tmp / 256) & 0xff;
564
            }
565

    
566
    sb_used = QDM2_SB_USED(q->sub_sampling);
567

    
568
    if ((q->superblocktype_2_3 != 0) && !flag) {
569
        for (sb = 0; sb < sb_used; sb++)
570
            for (ch = 0; ch < q->nb_channels; ch++)
571
                for (i = 0; i < 64; i++) {
572
                    q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];
573
                    if (q->tone_level_idx[ch][sb][i] < 0)
574
                        q->tone_level[ch][sb][i] = 0;
575
                    else
576
                        q->tone_level[ch][sb][i] = fft_tone_level_table[0][q->tone_level_idx[ch][sb][i] & 0x3f];
577
                }
578
    } else {
579
        tab = q->superblocktype_2_3 ? 0 : 1;
580
        for (sb = 0; sb < sb_used; sb++) {
581
            if ((sb >= 4) && (sb <= 23)) {
582
                for (ch = 0; ch < q->nb_channels; ch++)
583
                    for (i = 0; i < 64; i++) {
584
                        tmp = q->tone_level_idx_base[ch][sb][i / 8] -
585
                              q->tone_level_idx_hi1[ch][sb / 8][i / 8][i % 8] -
586
                              q->tone_level_idx_mid[ch][sb - 4][i / 8] -
587
                              q->tone_level_idx_hi2[ch][sb - 4];
588
                        q->tone_level_idx[ch][sb][i] = tmp & 0xff;
589
                        if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
590
                            q->tone_level[ch][sb][i] = 0;
591
                        else
592
                            q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
593
                }
594
            } else {
595
                if (sb > 4) {
596
                    for (ch = 0; ch < q->nb_channels; ch++)
597
                        for (i = 0; i < 64; i++) {
598
                            tmp = q->tone_level_idx_base[ch][sb][i / 8] -
599
                                  q->tone_level_idx_hi1[ch][2][i / 8][i % 8] -
600
                                  q->tone_level_idx_hi2[ch][sb - 4];
601
                            q->tone_level_idx[ch][sb][i] = tmp & 0xff;
602
                            if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
603
                                q->tone_level[ch][sb][i] = 0;
604
                            else
605
                                q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
606
                    }
607
                } else {
608
                    for (ch = 0; ch < q->nb_channels; ch++)
609
                        for (i = 0; i < 64; i++) {
610
                            tmp = q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];
611
                            if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
612
                                q->tone_level[ch][sb][i] = 0;
613
                            else
614
                                q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
615
                        }
616
                }
617
            }
618
        }
619
    }
620

    
621
    return;
622
}
623

    
624

    
625
/**
626
 * Related to synthesis filter
627
 * Called by process_subpacket_11
628
 * c is built with data from subpacket 11
629
 * Most of this function is used only if superblock_type_2_3 == 0, never seen it in samples
630
 *
631
 * @param tone_level_idx
632
 * @param tone_level_idx_temp
633
 * @param coding_method        q->coding_method[0][0][0]
634
 * @param nb_channels          number of channels
635
 * @param c                    coming from subpacket 11, passed as 8*c
636
 * @param superblocktype_2_3   flag based on superblock packet type
637
 * @param cm_table_select      q->cm_table_select
638
 */
639
static void fill_coding_method_array (sb_int8_array tone_level_idx, sb_int8_array tone_level_idx_temp,
640
                sb_int8_array coding_method, int nb_channels,
641
                int c, int superblocktype_2_3, int cm_table_select)
642
{
643
    int ch, sb, j;
644
    int tmp, acc, esp_40, comp;
645
    int add1, add2, add3, add4;
646
    int64_t multres;
647

    
648
    // This should never happen
649
    if (nb_channels <= 0)
650
        return;
651

    
652
    if (!superblocktype_2_3) {
653
        /* This case is untested, no samples available */
654
        SAMPLES_NEEDED
655
        for (ch = 0; ch < nb_channels; ch++)
656
            for (sb = 0; sb < 30; sb++) {
657
                for (j = 1; j < 63; j++) {  // The loop only iterates to 63 so the code doesn't overflow the buffer
658
                    add1 = tone_level_idx[ch][sb][j] - 10;
659
                    if (add1 < 0)
660
                        add1 = 0;
661
                    add2 = add3 = add4 = 0;
662
                    if (sb > 1) {
663
                        add2 = tone_level_idx[ch][sb - 2][j] + tone_level_idx_offset_table[sb][0] - 6;
664
                        if (add2 < 0)
665
                            add2 = 0;
666
                    }
667
                    if (sb > 0) {
668
                        add3 = tone_level_idx[ch][sb - 1][j] + tone_level_idx_offset_table[sb][1] - 6;
669
                        if (add3 < 0)
670
                            add3 = 0;
671
                    }
672
                    if (sb < 29) {
673
                        add4 = tone_level_idx[ch][sb + 1][j] + tone_level_idx_offset_table[sb][3] - 6;
674
                        if (add4 < 0)
675
                            add4 = 0;
676
                    }
677
                    tmp = tone_level_idx[ch][sb][j + 1] * 2 - add4 - add3 - add2 - add1;
678
                    if (tmp < 0)
679
                        tmp = 0;
680
                    tone_level_idx_temp[ch][sb][j + 1] = tmp & 0xff;
681
                }
682
                tone_level_idx_temp[ch][sb][0] = tone_level_idx_temp[ch][sb][1];
683
            }
684
            acc = 0;
685
            for (ch = 0; ch < nb_channels; ch++)
686
                for (sb = 0; sb < 30; sb++)
687
                    for (j = 0; j < 64; j++)
688
                        acc += tone_level_idx_temp[ch][sb][j];
689

    
690
            multres = 0x66666667 * (acc * 10);
691
            esp_40 = (multres >> 32) / 8 + ((multres & 0xffffffff) >> 31);
692
            for (ch = 0;  ch < nb_channels; ch++)
693
                for (sb = 0; sb < 30; sb++)
694
                    for (j = 0; j < 64; j++) {
695
                        comp = tone_level_idx_temp[ch][sb][j]* esp_40 * 10;
696
                        if (comp < 0)
697
                            comp += 0xff;
698
                        comp /= 256; // signed shift
699
                        switch(sb) {
700
                            case 0:
701
                                if (comp < 30)
702
                                    comp = 30;
703
                                comp += 15;
704
                                break;
705
                            case 1:
706
                                if (comp < 24)
707
                                    comp = 24;
708
                                comp += 10;
709
                                break;
710
                            case 2:
711
                            case 3:
712
                            case 4:
713
                                if (comp < 16)
714
                                    comp = 16;
715
                        }
716
                        if (comp <= 5)
717
                            tmp = 0;
718
                        else if (comp <= 10)
719
                            tmp = 10;
720
                        else if (comp <= 16)
721
                            tmp = 16;
722
                        else if (comp <= 24)
723
                            tmp = -1;
724
                        else
725
                            tmp = 0;
726
                        coding_method[ch][sb][j] = ((tmp & 0xfffa) + 30 )& 0xff;
727
                    }
728
            for (sb = 0; sb < 30; sb++)
729
                fix_coding_method_array(sb, nb_channels, coding_method);
730
            for (ch = 0; ch < nb_channels; ch++)
731
                for (sb = 0; sb < 30; sb++)
732
                    for (j = 0; j < 64; j++)
733
                        if (sb >= 10) {
734
                            if (coding_method[ch][sb][j] < 10)
735
                                coding_method[ch][sb][j] = 10;
736
                        } else {
737
                            if (sb >= 2) {
738
                                if (coding_method[ch][sb][j] < 16)
739
                                    coding_method[ch][sb][j] = 16;
740
                            } else {
741
                                if (coding_method[ch][sb][j] < 30)
742
                                    coding_method[ch][sb][j] = 30;
743
                            }
744
                        }
745
    } else { // superblocktype_2_3 != 0
746
        for (ch = 0; ch < nb_channels; ch++)
747
            for (sb = 0; sb < 30; sb++)
748
                for (j = 0; j < 64; j++)
749
                    coding_method[ch][sb][j] = coding_method_table[cm_table_select][sb];
750
    }
751

    
752
    return;
753
}
754

    
755

    
756
/**
757
 *
758
 * Called by process_subpacket_11 to process more data from subpacket 11 with sb 0-8
759
 * Called by process_subpacket_12 to process data from subpacket 12 with sb 8-sb_used
760
 *
761
 * @param q         context
762
 * @param gb        bitreader context
763
 * @param length    packet length in bits
764
 * @param sb_min    lower subband processed (sb_min included)
765
 * @param sb_max    higher subband processed (sb_max excluded)
766
 */
767
static void synthfilt_build_sb_samples (QDM2Context *q, GetBitContext *gb, int length, int sb_min, int sb_max)
768
{
769
    int sb, j, k, n, ch, run, channels;
770
    int joined_stereo, zero_encoding, chs;
771
    int type34_first;
772
    float type34_div = 0;
773
    float type34_predictor;
774
    float samples[10], sign_bits[16];
775

    
776
    if (length == 0) {
777
        // If no data use noise
778
        for (sb=sb_min; sb < sb_max; sb++)
779
            build_sb_samples_from_noise (q, sb);
780

    
781
        return;
782
    }
783

    
784
    for (sb = sb_min; sb < sb_max; sb++) {
785
        FIX_NOISE_IDX(q->noise_idx);
786

    
787
        channels = q->nb_channels;
788

    
789
        if (q->nb_channels <= 1 || sb < 12)
790
            joined_stereo = 0;
791
        else if (sb >= 24)
792
            joined_stereo = 1;
793
        else
794
            joined_stereo = (BITS_LEFT(length,gb) >= 1) ? get_bits1 (gb) : 0;
795

    
796
        if (joined_stereo) {
797
            if (BITS_LEFT(length,gb) >= 16)
798
                for (j = 0; j < 16; j++)
799
                    sign_bits[j] = get_bits1 (gb);
800

    
801
            for (j = 0; j < 64; j++)
802
                if (q->coding_method[1][sb][j] > q->coding_method[0][sb][j])
803
                    q->coding_method[0][sb][j] = q->coding_method[1][sb][j];
804

    
805
            fix_coding_method_array(sb, q->nb_channels, q->coding_method);
806
            channels = 1;
807
        }
808

    
809
        for (ch = 0; ch < channels; ch++) {
810
            zero_encoding = (BITS_LEFT(length,gb) >= 1) ? get_bits1(gb) : 0;
811
            type34_predictor = 0.0;
812
            type34_first = 1;
813

    
814
            for (j = 0; j < 128; ) {
815
                switch (q->coding_method[ch][sb][j / 2]) {
816
                    case 8:
817
                        if (BITS_LEFT(length,gb) >= 10) {
818
                            if (zero_encoding) {
819
                                for (k = 0; k < 5; k++) {
820
                                    if ((j + 2 * k) >= 128)
821
                                        break;
822
                                    samples[2 * k] = get_bits1(gb) ? dequant_1bit[joined_stereo][2 * get_bits1(gb)] : 0;
823
                                }
824
                            } else {
825
                                n = get_bits(gb, 8);
826
                                for (k = 0; k < 5; k++)
827
                                    samples[2 * k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];
828
                            }
829
                            for (k = 0; k < 5; k++)
830
                                samples[2 * k + 1] = SB_DITHERING_NOISE(sb,q->noise_idx);
831
                        } else {
832
                            for (k = 0; k < 10; k++)
833
                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
834
                        }
835
                        run = 10;
836
                        break;
837

    
838
                    case 10:
839
                        if (BITS_LEFT(length,gb) >= 1) {
840
                            float f = 0.81;
841

    
842
                            if (get_bits1(gb))
843
                                f = -f;
844
                            f -= noise_samples[((sb + 1) * (j +5 * ch + 1)) & 127] * 9.0 / 40.0;
845
                            samples[0] = f;
846
                        } else {
847
                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
848
                        }
849
                        run = 1;
850
                        break;
851

    
852
                    case 16:
853
                        if (BITS_LEFT(length,gb) >= 10) {
854
                            if (zero_encoding) {
855
                                for (k = 0; k < 5; k++) {
856
                                    if ((j + k) >= 128)
857
                                        break;
858
                                    samples[k] = (get_bits1(gb) == 0) ? 0 : dequant_1bit[joined_stereo][2 * get_bits1(gb)];
859
                                }
860
                            } else {
861
                                n = get_bits (gb, 8);
862
                                for (k = 0; k < 5; k++)
863
                                    samples[k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];
864
                            }
865
                        } else {
866
                            for (k = 0; k < 5; k++)
867
                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
868
                        }
869
                        run = 5;
870
                        break;
871

    
872
                    case 24:
873
                        if (BITS_LEFT(length,gb) >= 7) {
874
                            n = get_bits(gb, 7);
875
                            for (k = 0; k < 3; k++)
876
                                samples[k] = (random_dequant_type24[n][k] - 2.0) * 0.5;
877
                        } else {
878
                            for (k = 0; k < 3; k++)
879
                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
880
                        }
881
                        run = 3;
882
                        break;
883

    
884
                    case 30:
885
                        if (BITS_LEFT(length,gb) >= 4)
886
                            samples[0] = type30_dequant[qdm2_get_vlc(gb, &vlc_tab_type30, 0, 1)];
887
                        else
888
                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
889

    
890
                        run = 1;
891
                        break;
892

    
893
                    case 34:
894
                        if (BITS_LEFT(length,gb) >= 7) {
895
                            if (type34_first) {
896
                                type34_div = (float)(1 << get_bits(gb, 2));
897
                                samples[0] = ((float)get_bits(gb, 5) - 16.0) / 15.0;
898
                                type34_predictor = samples[0];
899
                                type34_first = 0;
900
                            } else {
901
                                samples[0] = type34_delta[qdm2_get_vlc(gb, &vlc_tab_type34, 0, 1)] / type34_div + type34_predictor;
902
                                type34_predictor = samples[0];
903
                            }
904
                        } else {
905
                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
906
                        }
907
                        run = 1;
908
                        break;
909

    
910
                    default:
911
                        samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
912
                        run = 1;
913
                        break;
914
                }
915

    
916
                if (joined_stereo) {
917
                    float tmp[10][MPA_MAX_CHANNELS];
918

    
919
                    for (k = 0; k < run; k++) {
920
                        tmp[k][0] = samples[k];
921
                        tmp[k][1] = (sign_bits[(j + k) / 8]) ? -samples[k] : samples[k];
922
                    }
923
                    for (chs = 0; chs < q->nb_channels; chs++)
924
                        for (k = 0; k < run; k++)
925
                            if ((j + k) < 128)
926
                                q->sb_samples[chs][j + k][sb] = (int32_t)(f2i_scale * q->tone_level[chs][sb][((j + k)/2)] * tmp[k][chs] + .5);
927
                } else {
928
                    for (k = 0; k < run; k++)
929
                        if ((j + k) < 128)
930
                            q->sb_samples[ch][j + k][sb] = (int32_t)(f2i_scale * q->tone_level[ch][sb][(j + k)/2] * samples[k] + .5);
931
                }
932

    
933
                j += run;
934
            } // j loop
935
        } // channel loop
936
    } // subband loop
937
}
938

    
939

    
940
/**
941
 * Init the first element of a channel in quantized_coeffs with data from packet 10 (quantized_coeffs[ch][0]).
942
 * This is similar to process_subpacket_9, but for a single channel and for element [0]
943
 * same VLC tables as process_subpacket_9 are used.
944
 *
945
 * @param q         context
946
 * @param quantized_coeffs    pointer to quantized_coeffs[ch][0]
947
 * @param gb        bitreader context
948
 * @param length    packet length in bits
949
 */
950
static void init_quantized_coeffs_elem0 (int8_t *quantized_coeffs, GetBitContext *gb, int length)
951
{
952
    int i, k, run, level, diff;
953

    
954
    if (BITS_LEFT(length,gb) < 16)
955
        return;
956
    level = qdm2_get_vlc(gb, &vlc_tab_level, 0, 2);
957

    
958
    quantized_coeffs[0] = level;
959

    
960
    for (i = 0; i < 7; ) {
961
        if (BITS_LEFT(length,gb) < 16)
962
            break;
963
        run = qdm2_get_vlc(gb, &vlc_tab_run, 0, 1) + 1;
964

    
965
        if (BITS_LEFT(length,gb) < 16)
966
            break;
967
        diff = qdm2_get_se_vlc(&vlc_tab_diff, gb, 2);
968

    
969
        for (k = 1; k <= run; k++)
970
            quantized_coeffs[i + k] = (level + ((k * diff) / run));
971

    
972
        level += diff;
973
        i += run;
974
    }
975
}
976

    
977

    
978
/**
979
 * Related to synthesis filter, process data from packet 10
980
 * Init part of quantized_coeffs via function init_quantized_coeffs_elem0
981
 * Init tone_level_idx_hi1, tone_level_idx_hi2, tone_level_idx_mid with data from packet 10
982
 *
983
 * @param q         context
984
 * @param gb        bitreader context
985
 * @param length    packet length in bits
986
 */
987
static void init_tone_level_dequantization (QDM2Context *q, GetBitContext *gb, int length)
988
{
989
    int sb, j, k, n, ch;
990

    
991
    for (ch = 0; ch < q->nb_channels; ch++) {
992
        init_quantized_coeffs_elem0(q->quantized_coeffs[ch][0], gb, length);
993

    
994
        if (BITS_LEFT(length,gb) < 16) {
995
            memset(q->quantized_coeffs[ch][0], 0, 8);
996
            break;
997
        }
998
    }
999

    
1000
    n = q->sub_sampling + 1;
1001

    
1002
    for (sb = 0; sb < n; sb++)
1003
        for (ch = 0; ch < q->nb_channels; ch++)
1004
            for (j = 0; j < 8; j++) {
1005
                if (BITS_LEFT(length,gb) < 1)
1006
                    break;
1007
                if (get_bits1(gb)) {
1008
                    for (k=0; k < 8; k++) {
1009
                        if (BITS_LEFT(length,gb) < 16)
1010
                            break;
1011
                        q->tone_level_idx_hi1[ch][sb][j][k] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_hi1, 0, 2);
1012
                    }
1013
                } else {
1014
                    for (k=0; k < 8; k++)
1015
                        q->tone_level_idx_hi1[ch][sb][j][k] = 0;
1016
                }
1017
            }
1018

    
1019
    n = QDM2_SB_USED(q->sub_sampling) - 4;
1020

    
1021
    for (sb = 0; sb < n; sb++)
1022
        for (ch = 0; ch < q->nb_channels; ch++) {
1023
            if (BITS_LEFT(length,gb) < 16)
1024
                break;
1025
            q->tone_level_idx_hi2[ch][sb] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_hi2, 0, 2);
1026
            if (sb > 19)
1027
                q->tone_level_idx_hi2[ch][sb] -= 16;
1028
            else
1029
                for (j = 0; j < 8; j++)
1030
                    q->tone_level_idx_mid[ch][sb][j] = -16;
1031
        }
1032

    
1033
    n = QDM2_SB_USED(q->sub_sampling) - 5;
1034

    
1035
    for (sb = 0; sb < n; sb++)
1036
        for (ch = 0; ch < q->nb_channels; ch++)
1037
            for (j = 0; j < 8; j++) {
1038
                if (BITS_LEFT(length,gb) < 16)
1039
                    break;
1040
                q->tone_level_idx_mid[ch][sb][j] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_mid, 0, 2) - 32;
1041
            }
1042
}
1043

    
1044
/**
1045
 * Process subpacket 9, init quantized_coeffs with data from it
1046
 *
1047
 * @param q       context
1048
 * @param node    pointer to node with packet
1049
 */
1050
static void process_subpacket_9 (QDM2Context *q, QDM2SubPNode *node)
1051
{
1052
    GetBitContext gb;
1053
    int i, j, k, n, ch, run, level, diff;
1054

    
1055
    init_get_bits(&gb, node->packet->data, node->packet->size*8);
1056

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

    
1059
    for (i = 1; i < n; i++)
1060
        for (ch=0; ch < q->nb_channels; ch++) {
1061
            level = qdm2_get_vlc(&gb, &vlc_tab_level, 0, 2);
1062
            q->quantized_coeffs[ch][i][0] = level;
1063

    
1064
            for (j = 0; j < (8 - 1); ) {
1065
                run = qdm2_get_vlc(&gb, &vlc_tab_run, 0, 1) + 1;
1066
                diff = qdm2_get_se_vlc(&vlc_tab_diff, &gb, 2);
1067

    
1068
                for (k = 1; k <= run; k++)
1069
                    q->quantized_coeffs[ch][i][j + k] = (level + ((k*diff) / run));
1070

    
1071
                level += diff;
1072
                j += run;
1073
            }
1074
        }
1075

    
1076
    for (ch = 0; ch < q->nb_channels; ch++)
1077
        for (i = 0; i < 8; i++)
1078
            q->quantized_coeffs[ch][0][i] = 0;
1079
}
1080

    
1081

    
1082
/**
1083
 * Process subpacket 10 if not null, else
1084
 *
1085
 * @param q         context
1086
 * @param node      pointer to node with packet
1087
 * @param length    packet length in bits
1088
 */
1089
static void process_subpacket_10 (QDM2Context *q, QDM2SubPNode *node, int length)
1090
{
1091
    GetBitContext gb;
1092

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

    
1095
    if (length != 0) {
1096
        init_tone_level_dequantization(q, &gb, length);
1097
        fill_tone_level_array(q, 1);
1098
    } else {
1099
        fill_tone_level_array(q, 0);
1100
    }
1101
}
1102

    
1103

    
1104
/**
1105
 * Process subpacket 11
1106
 *
1107
 * @param q         context
1108
 * @param node      pointer to node with packet
1109
 * @param length    packet length in bit
1110
 */
1111
static void process_subpacket_11 (QDM2Context *q, QDM2SubPNode *node, int length)
1112
{
1113
    GetBitContext gb;
1114

    
1115
    init_get_bits(&gb, ((node == NULL) ? empty_buffer : node->packet->data), ((node == NULL) ? 0 : node->packet->size*8));
1116
    if (length >= 32) {
1117
        int c = get_bits (&gb, 13);
1118

    
1119
        if (c > 3)
1120
            fill_coding_method_array (q->tone_level_idx, q->tone_level_idx_temp, q->coding_method,
1121
                                      q->nb_channels, 8*c, q->superblocktype_2_3, q->cm_table_select);
1122
    }
1123

    
1124
    synthfilt_build_sb_samples(q, &gb, length, 0, 8);
1125
}
1126

    
1127

    
1128
/**
1129
 * Process subpacket 12
1130
 *
1131
 * @param q         context
1132
 * @param node      pointer to node with packet
1133
 * @param length    packet length in bits
1134
 */
1135
static void process_subpacket_12 (QDM2Context *q, QDM2SubPNode *node, int length)
1136
{
1137
    GetBitContext gb;
1138

    
1139
    init_get_bits(&gb, ((node == NULL) ? empty_buffer : node->packet->data), ((node == NULL) ? 0 : node->packet->size*8));
1140
    synthfilt_build_sb_samples(q, &gb, length, 8, QDM2_SB_USED(q->sub_sampling));
1141
}
1142

    
1143
/*
1144
 * Process new subpackets for synthesis filter
1145
 *
1146
 * @param q       context
1147
 * @param list    list with synthesis filter packets (list D)
1148
 */
1149
static void process_synthesis_subpackets (QDM2Context *q, QDM2SubPNode *list)
1150
{
1151
    QDM2SubPNode *nodes[4];
1152

    
1153
    nodes[0] = qdm2_search_subpacket_type_in_list(list, 9);
1154
    if (nodes[0] != NULL)
1155
        process_subpacket_9(q, nodes[0]);
1156

    
1157
    nodes[1] = qdm2_search_subpacket_type_in_list(list, 10);
1158
    if (nodes[1] != NULL)
1159
        process_subpacket_10(q, nodes[1], nodes[1]->packet->size << 3);
1160
    else
1161
        process_subpacket_10(q, NULL, 0);
1162

    
1163
    nodes[2] = qdm2_search_subpacket_type_in_list(list, 11);
1164
    if (nodes[0] != NULL && nodes[1] != NULL && nodes[2] != NULL)
1165
        process_subpacket_11(q, nodes[2], (nodes[2]->packet->size << 3));
1166
    else
1167
        process_subpacket_11(q, NULL, 0);
1168

    
1169
    nodes[3] = qdm2_search_subpacket_type_in_list(list, 12);
1170
    if (nodes[0] != NULL && nodes[1] != NULL && nodes[3] != NULL)
1171
        process_subpacket_12(q, nodes[3], (nodes[3]->packet->size << 3));
1172
    else
1173
        process_subpacket_12(q, NULL, 0);
1174
}
1175

    
1176

    
1177
/*
1178
 * Decode superblock, fill packet lists.
1179
 *
1180
 * @param q    context
1181
 */
1182
static void qdm2_decode_super_block (QDM2Context *q)
1183
{
1184
    GetBitContext gb;
1185
    QDM2SubPacket header, *packet;
1186
    int i, packet_bytes, sub_packet_size, sub_packets_D;
1187
    unsigned int next_index = 0;
1188

    
1189
    memset(q->tone_level_idx_hi1, 0, sizeof(q->tone_level_idx_hi1));
1190
    memset(q->tone_level_idx_mid, 0, sizeof(q->tone_level_idx_mid));
1191
    memset(q->tone_level_idx_hi2, 0, sizeof(q->tone_level_idx_hi2));
1192

    
1193
    q->sub_packets_B = 0;
1194
    sub_packets_D = 0;
1195

    
1196
    average_quantized_coeffs(q); // average elements in quantized_coeffs[max_ch][10][8]
1197

    
1198
    init_get_bits(&gb, q->compressed_data, q->compressed_size*8);
1199
    qdm2_decode_sub_packet_header(&gb, &header);
1200

    
1201
    if (header.type < 2 || header.type >= 8) {
1202
        q->has_errors = 1;
1203
        av_log(NULL,AV_LOG_ERROR,"bad superblock type\n");
1204
        return;
1205
    }
1206

    
1207
    q->superblocktype_2_3 = (header.type == 2 || header.type == 3);
1208
    packet_bytes = (q->compressed_size - get_bits_count(&gb) / 8);
1209

    
1210
    init_get_bits(&gb, header.data, header.size*8);
1211

    
1212
    if (header.type == 2 || header.type == 4 || header.type == 5) {
1213
        int csum = 257 * get_bits(&gb, 8) + 2 * get_bits(&gb, 8);
1214

    
1215
        csum = qdm2_packet_checksum(q->compressed_data, q->checksum_size, csum);
1216

    
1217
        if (csum != 0) {
1218
            q->has_errors = 1;
1219
            av_log(NULL,AV_LOG_ERROR,"bad packet checksum\n");
1220
            return;
1221
        }
1222
    }
1223

    
1224
    q->sub_packet_list_B[0].packet = NULL;
1225
    q->sub_packet_list_D[0].packet = NULL;
1226

    
1227
    for (i = 0; i < 6; i++)
1228
        if (--q->fft_level_exp[i] < 0)
1229
            q->fft_level_exp[i] = 0;
1230

    
1231
    for (i = 0; packet_bytes > 0; i++) {
1232
        int j;
1233

    
1234
        q->sub_packet_list_A[i].next = NULL;
1235

    
1236
        if (i > 0) {
1237
            q->sub_packet_list_A[i - 1].next = &q->sub_packet_list_A[i];
1238

    
1239
            /* seek to next block */
1240
            init_get_bits(&gb, header.data, header.size*8);
1241
            skip_bits(&gb, next_index*8);
1242

    
1243
            if (next_index >= header.size)
1244
                break;
1245
        }
1246

    
1247
        /* decode subpacket */
1248
        packet = &q->sub_packets[i];
1249
        qdm2_decode_sub_packet_header(&gb, packet);
1250
        next_index = packet->size + get_bits_count(&gb) / 8;
1251
        sub_packet_size = ((packet->size > 0xff) ? 1 : 0) + packet->size + 2;
1252

    
1253
        if (packet->type == 0)
1254
            break;
1255

    
1256
        if (sub_packet_size > packet_bytes) {
1257
            if (packet->type != 10 && packet->type != 11 && packet->type != 12)
1258
                break;
1259
            packet->size += packet_bytes - sub_packet_size;
1260
        }
1261

    
1262
        packet_bytes -= sub_packet_size;
1263

    
1264
        /* add subpacket to 'all subpackets' list */
1265
        q->sub_packet_list_A[i].packet = packet;
1266

    
1267
        /* add subpacket to related list */
1268
        if (packet->type == 8) {
1269
            SAMPLES_NEEDED_2("packet type 8");
1270
            return;
1271
        } else if (packet->type >= 9 && packet->type <= 12) {
1272
            /* packets for MPEG Audio like Synthesis Filter */
1273
            QDM2_LIST_ADD(q->sub_packet_list_D, sub_packets_D, packet);
1274
        } else if (packet->type == 13) {
1275
            for (j = 0; j < 6; j++)
1276
                q->fft_level_exp[j] = get_bits(&gb, 6);
1277
        } else if (packet->type == 14) {
1278
            for (j = 0; j < 6; j++)
1279
                q->fft_level_exp[j] = qdm2_get_vlc(&gb, &fft_level_exp_vlc, 0, 2);
1280
        } else if (packet->type == 15) {
1281
            SAMPLES_NEEDED_2("packet type 15")
1282
            return;
1283
        } else if (packet->type >= 16 && packet->type < 48 && !fft_subpackets[packet->type - 16]) {
1284
            /* packets for FFT */
1285
            QDM2_LIST_ADD(q->sub_packet_list_B, q->sub_packets_B, packet);
1286
        }
1287
    } // Packet bytes loop
1288

    
1289
/* **************************************************************** */
1290
    if (q->sub_packet_list_D[0].packet != NULL) {
1291
        process_synthesis_subpackets(q, q->sub_packet_list_D);
1292
        q->do_synth_filter = 1;
1293
    } else if (q->do_synth_filter) {
1294
        process_subpacket_10(q, NULL, 0);
1295
        process_subpacket_11(q, NULL, 0);
1296
        process_subpacket_12(q, NULL, 0);
1297
    }
1298
/* **************************************************************** */
1299
}
1300

    
1301

    
1302
static void qdm2_fft_init_coefficient (QDM2Context *q, int sub_packet,
1303
                       int offset, int duration, int channel,
1304
                       int exp, int phase)
1305
{
1306
    if (q->fft_coefs_min_index[duration] < 0)
1307
        q->fft_coefs_min_index[duration] = q->fft_coefs_index;
1308

    
1309
    q->fft_coefs[q->fft_coefs_index].sub_packet = ((sub_packet >= 16) ? (sub_packet - 16) : sub_packet);
1310
    q->fft_coefs[q->fft_coefs_index].channel = channel;
1311
    q->fft_coefs[q->fft_coefs_index].offset = offset;
1312
    q->fft_coefs[q->fft_coefs_index].exp = exp;
1313
    q->fft_coefs[q->fft_coefs_index].phase = phase;
1314
    q->fft_coefs_index++;
1315
}
1316

    
1317

    
1318
static void qdm2_fft_decode_tones (QDM2Context *q, int duration, GetBitContext *gb, int b)
1319
{
1320
    int channel, stereo, phase, exp;
1321
    int local_int_4,  local_int_8,  stereo_phase,  local_int_10;
1322
    int local_int_14, stereo_exp, local_int_20, local_int_28;
1323
    int n, offset;
1324

    
1325
    local_int_4 = 0;
1326
    local_int_28 = 0;
1327
    local_int_20 = 2;
1328
    local_int_8 = (4 - duration);
1329
    local_int_10 = 1 << (q->group_order - duration - 1);
1330
    offset = 1;
1331

    
1332
    while (1) {
1333
        if (q->superblocktype_2_3) {
1334
            while ((n = qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2)) < 2) {
1335
                offset = 1;
1336
                if (n == 0) {
1337
                    local_int_4 += local_int_10;
1338
                    local_int_28 += (1 << local_int_8);
1339
                } else {
1340
                    local_int_4 += 8*local_int_10;
1341
                    local_int_28 += (8 << local_int_8);
1342
                }
1343
            }
1344
            offset += (n - 2);
1345
        } else {
1346
            offset += qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2);
1347
            while (offset >= (local_int_10 - 1)) {
1348
                offset += (1 - (local_int_10 - 1));
1349
                local_int_4  += local_int_10;
1350
                local_int_28 += (1 << local_int_8);
1351
            }
1352
        }
1353

    
1354
        if (local_int_4 >= q->group_size)
1355
            return;
1356

    
1357
        local_int_14 = (offset >> local_int_8);
1358

    
1359
        if (q->nb_channels > 1) {
1360
            channel = get_bits1(gb);
1361
            stereo = get_bits1(gb);
1362
        } else {
1363
            channel = 0;
1364
            stereo = 0;
1365
        }
1366

    
1367
        exp = qdm2_get_vlc(gb, (b ? &fft_level_exp_vlc : &fft_level_exp_alt_vlc), 0, 2);
1368
        exp += q->fft_level_exp[fft_level_index_table[local_int_14]];
1369
        exp = (exp < 0) ? 0 : exp;
1370

    
1371
        phase = get_bits(gb, 3);
1372
        stereo_exp = 0;
1373
        stereo_phase = 0;
1374

    
1375
        if (stereo) {
1376
            stereo_exp = (exp - qdm2_get_vlc(gb, &fft_stereo_exp_vlc, 0, 1));
1377
            stereo_phase = (phase - qdm2_get_vlc(gb, &fft_stereo_phase_vlc, 0, 1));
1378
            if (stereo_phase < 0)
1379
                stereo_phase += 8;
1380
        }
1381

    
1382
        if (q->frequency_range > (local_int_14 + 1)) {
1383
            int sub_packet = (local_int_20 + local_int_28);
1384

    
1385
            qdm2_fft_init_coefficient(q, sub_packet, offset, duration, channel, exp, phase);
1386
            if (stereo)
1387
                qdm2_fft_init_coefficient(q, sub_packet, offset, duration, (1 - channel), stereo_exp, stereo_phase);
1388
        }
1389

    
1390
        offset++;
1391
    }
1392
}
1393

    
1394

    
1395
static void qdm2_decode_fft_packets (QDM2Context *q)
1396
{
1397
    int i, j, min, max, value, type, unknown_flag;
1398
    GetBitContext gb;
1399

    
1400
    if (q->sub_packet_list_B[0].packet == NULL)
1401
        return;
1402

    
1403
    /* reset minimum indexes for FFT coefficients */
1404
    q->fft_coefs_index = 0;
1405
    for (i=0; i < 5; i++)
1406
        q->fft_coefs_min_index[i] = -1;
1407

    
1408
    /* process subpackets ordered by type, largest type first */
1409
    for (i = 0, max = 256; i < q->sub_packets_B; i++) {
1410
        QDM2SubPacket *packet= NULL;
1411

    
1412
        /* find subpacket with largest type less than max */
1413
        for (j = 0, min = 0; j < q->sub_packets_B; j++) {
1414
            value = q->sub_packet_list_B[j].packet->type;
1415
            if (value > min && value < max) {
1416
                min = value;
1417
                packet = q->sub_packet_list_B[j].packet;
1418
            }
1419
        }
1420

    
1421
        max = min;
1422

    
1423
        /* check for errors (?) */
1424
        if (!packet)
1425
            return;
1426

    
1427
        if (i == 0 && (packet->type < 16 || packet->type >= 48 || fft_subpackets[packet->type - 16]))
1428
            return;
1429

    
1430
        /* decode FFT tones */
1431
        init_get_bits (&gb, packet->data, packet->size*8);
1432

    
1433
        if (packet->type >= 32 && packet->type < 48 && !fft_subpackets[packet->type - 16])
1434
            unknown_flag = 1;
1435
        else
1436
            unknown_flag = 0;
1437

    
1438
        type = packet->type;
1439

    
1440
        if ((type >= 17 && type < 24) || (type >= 33 && type < 40)) {
1441
            int duration = q->sub_sampling + 5 - (type & 15);
1442

    
1443
            if (duration >= 0 && duration < 4)
1444
                qdm2_fft_decode_tones(q, duration, &gb, unknown_flag);
1445
        } else if (type == 31) {
1446
            for (j=0; j < 4; j++)
1447
                qdm2_fft_decode_tones(q, j, &gb, unknown_flag);
1448
        } else if (type == 46) {
1449
            for (j=0; j < 6; j++)
1450
                q->fft_level_exp[j] = get_bits(&gb, 6);
1451
            for (j=0; j < 4; j++)
1452
            qdm2_fft_decode_tones(q, j, &gb, unknown_flag);
1453
        }
1454
    } // Loop on B packets
1455

    
1456
    /* calculate maximum indexes for FFT coefficients */
1457
    for (i = 0, j = -1; i < 5; i++)
1458
        if (q->fft_coefs_min_index[i] >= 0) {
1459
            if (j >= 0)
1460
                q->fft_coefs_max_index[j] = q->fft_coefs_min_index[i];
1461
            j = i;
1462
        }
1463
    if (j >= 0)
1464
        q->fft_coefs_max_index[j] = q->fft_coefs_index;
1465
}
1466

    
1467

    
1468
static void qdm2_fft_generate_tone (QDM2Context *q, FFTTone *tone)
1469
{
1470
   float level, f[6];
1471
   int i;
1472
   QDM2Complex c;
1473
   const double iscale = 2.0*M_PI / 512.0;
1474

    
1475
    tone->phase += tone->phase_shift;
1476

    
1477
    /* calculate current level (maximum amplitude) of tone */
1478
    level = fft_tone_envelope_table[tone->duration][tone->time_index] * tone->level;
1479
    c.im = level * sin(tone->phase*iscale);
1480
    c.re = level * cos(tone->phase*iscale);
1481

    
1482
    /* generate FFT coefficients for tone */
1483
    if (tone->duration >= 3 || tone->cutoff >= 3) {
1484
        tone->complex[0].im += c.im;
1485
        tone->complex[0].re += c.re;
1486
        tone->complex[1].im -= c.im;
1487
        tone->complex[1].re -= c.re;
1488
    } else {
1489
        f[1] = -tone->table[4];
1490
        f[0] =  tone->table[3] - tone->table[0];
1491
        f[2] =  1.0 - tone->table[2] - tone->table[3];
1492
        f[3] =  tone->table[1] + tone->table[4] - 1.0;
1493
        f[4] =  tone->table[0] - tone->table[1];
1494
        f[5] =  tone->table[2];
1495
        for (i = 0; i < 2; i++) {
1496
            tone->complex[fft_cutoff_index_table[tone->cutoff][i]].re += c.re * f[i];
1497
            tone->complex[fft_cutoff_index_table[tone->cutoff][i]].im += c.im *((tone->cutoff <= i) ? -f[i] : f[i]);
1498
        }
1499
        for (i = 0; i < 4; i++) {
1500
            tone->complex[i].re += c.re * f[i+2];
1501
            tone->complex[i].im += c.im * f[i+2];
1502
        }
1503
    }
1504

    
1505
    /* copy the tone if it has not yet died out */
1506
    if (++tone->time_index < ((1 << (5 - tone->duration)) - 1)) {
1507
      memcpy(&q->fft_tones[q->fft_tone_end], tone, sizeof(FFTTone));
1508
      q->fft_tone_end = (q->fft_tone_end + 1) % 1000;
1509
    }
1510
}
1511

    
1512

    
1513
static void qdm2_fft_tone_synthesizer (QDM2Context *q, int sub_packet)
1514
{
1515
    int i, j, ch;
1516
    const double iscale = 0.25 * M_PI;
1517

    
1518
    for (ch = 0; ch < q->channels; ch++) {
1519
        memset(q->fft.complex[ch], 0, q->fft_size * sizeof(QDM2Complex));
1520
    }
1521

    
1522

    
1523
    /* apply FFT tones with duration 4 (1 FFT period) */
1524
    if (q->fft_coefs_min_index[4] >= 0)
1525
        for (i = q->fft_coefs_min_index[4]; i < q->fft_coefs_max_index[4]; i++) {
1526
            float level;
1527
            QDM2Complex c;
1528

    
1529
            if (q->fft_coefs[i].sub_packet != sub_packet)
1530
                break;
1531

    
1532
            ch = (q->channels == 1) ? 0 : q->fft_coefs[i].channel;
1533
            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];
1534

    
1535
            c.re = level * cos(q->fft_coefs[i].phase * iscale);
1536
            c.im = level * sin(q->fft_coefs[i].phase * iscale);
1537
            q->fft.complex[ch][q->fft_coefs[i].offset + 0].re += c.re;
1538
            q->fft.complex[ch][q->fft_coefs[i].offset + 0].im += c.im;
1539
            q->fft.complex[ch][q->fft_coefs[i].offset + 1].re -= c.re;
1540
            q->fft.complex[ch][q->fft_coefs[i].offset + 1].im -= c.im;
1541
        }
1542

    
1543
    /* generate existing FFT tones */
1544
    for (i = q->fft_tone_end; i != q->fft_tone_start; ) {
1545
        qdm2_fft_generate_tone(q, &q->fft_tones[q->fft_tone_start]);
1546
        q->fft_tone_start = (q->fft_tone_start + 1) % 1000;
1547
    }
1548

    
1549
    /* create and generate new FFT tones with duration 0 (long) to 3 (short) */
1550
    for (i = 0; i < 4; i++)
1551
        if (q->fft_coefs_min_index[i] >= 0) {
1552
            for (j = q->fft_coefs_min_index[i]; j < q->fft_coefs_max_index[i]; j++) {
1553
                int offset, four_i;
1554
                FFTTone tone;
1555

    
1556
                if (q->fft_coefs[j].sub_packet != sub_packet)
1557
                    break;
1558

    
1559
                four_i = (4 - i);
1560
                offset = q->fft_coefs[j].offset >> four_i;
1561
                ch = (q->channels == 1) ? 0 : q->fft_coefs[j].channel;
1562

    
1563
                if (offset < q->frequency_range) {
1564
                    if (offset < 2)
1565
                        tone.cutoff = offset;
1566
                    else
1567
                        tone.cutoff = (offset >= 60) ? 3 : 2;
1568

    
1569
                    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];
1570
                    tone.complex = &q->fft.complex[ch][offset];
1571
                    tone.table = fft_tone_sample_table[i][q->fft_coefs[j].offset - (offset << four_i)];
1572
                    tone.phase = 64 * q->fft_coefs[j].phase - (offset << 8) - 128;
1573
                    tone.phase_shift = (2 * q->fft_coefs[j].offset + 1) << (7 - four_i);
1574
                    tone.duration = i;
1575
                    tone.time_index = 0;
1576

    
1577
                    qdm2_fft_generate_tone(q, &tone);
1578
                }
1579
            }
1580
            q->fft_coefs_min_index[i] = j;
1581
        }
1582
}
1583

    
1584

    
1585
static void qdm2_calculate_fft (QDM2Context *q, int channel, int sub_packet)
1586
{
1587
    const float gain = (q->channels == 1 && q->nb_channels == 2) ? 0.5f : 1.0f;
1588
    int i;
1589
    q->fft.complex[channel][0].re *= 2.0f;
1590
    q->fft.complex[channel][0].im = 0.0f;
1591
    ff_rdft_calc(&q->rdft_ctx, (FFTSample *)q->fft.complex[channel]);
1592
    /* add samples to output buffer */
1593
    for (i = 0; i < ((q->fft_frame_size + 15) & ~15); i++)
1594
        q->output_buffer[q->channels * i + channel] += ((float *) q->fft.complex[channel])[i] * gain;
1595
}
1596

    
1597

    
1598
/**
1599
 * @param q        context
1600
 * @param index    subpacket number
1601
 */
1602
static void qdm2_synthesis_filter (QDM2Context *q, int index)
1603
{
1604
    OUT_INT samples[MPA_MAX_CHANNELS * MPA_FRAME_SIZE];
1605
    int i, k, ch, sb_used, sub_sampling, dither_state = 0;
1606

    
1607
    /* copy sb_samples */
1608
    sb_used = QDM2_SB_USED(q->sub_sampling);
1609

    
1610
    for (ch = 0; ch < q->channels; ch++)
1611
        for (i = 0; i < 8; i++)
1612
            for (k=sb_used; k < SBLIMIT; k++)
1613
                q->sb_samples[ch][(8 * index) + i][k] = 0;
1614

    
1615
    for (ch = 0; ch < q->nb_channels; ch++) {
1616
        OUT_INT *samples_ptr = samples + ch;
1617

    
1618
        for (i = 0; i < 8; i++) {
1619
            ff_mpa_synth_filter(q->synth_buf[ch], &(q->synth_buf_offset[ch]),
1620
                ff_mpa_synth_window, &dither_state,
1621
                samples_ptr, q->nb_channels,
1622
                q->sb_samples[ch][(8 * index) + i]);
1623
            samples_ptr += 32 * q->nb_channels;
1624
        }
1625
    }
1626

    
1627
    /* add samples to output buffer */
1628
    sub_sampling = (4 >> q->sub_sampling);
1629

    
1630
    for (ch = 0; ch < q->channels; ch++)
1631
        for (i = 0; i < q->frame_size; i++)
1632
            q->output_buffer[q->channels * i + ch] += (float)(samples[q->nb_channels * sub_sampling * i + ch] >> (sizeof(OUT_INT)*8-16));
1633
}
1634

    
1635

    
1636
/**
1637
 * Init static data (does not depend on specific file)
1638
 *
1639
 * @param q    context
1640
 */
1641
static av_cold void qdm2_init(QDM2Context *q) {
1642
    static int initialized = 0;
1643

    
1644
    if (initialized != 0)
1645
        return;
1646
    initialized = 1;
1647

    
1648
    qdm2_init_vlc();
1649
    ff_mpa_synth_init(ff_mpa_synth_window);
1650
    softclip_table_init();
1651
    rnd_table_init();
1652
    init_noise_samples();
1653

    
1654
    av_log(NULL, AV_LOG_DEBUG, "init done\n");
1655
}
1656

    
1657

    
1658
#if 0
1659
static void dump_context(QDM2Context *q)
1660
{
1661
    int i;
1662
#define PRINT(a,b) av_log(NULL,AV_LOG_DEBUG," %s = %d\n", a, b);
1663
    PRINT("compressed_data",q->compressed_data);
1664
    PRINT("compressed_size",q->compressed_size);
1665
    PRINT("frame_size",q->frame_size);
1666
    PRINT("checksum_size",q->checksum_size);
1667
    PRINT("channels",q->channels);
1668
    PRINT("nb_channels",q->nb_channels);
1669
    PRINT("fft_frame_size",q->fft_frame_size);
1670
    PRINT("fft_size",q->fft_size);
1671
    PRINT("sub_sampling",q->sub_sampling);
1672
    PRINT("fft_order",q->fft_order);
1673
    PRINT("group_order",q->group_order);
1674
    PRINT("group_size",q->group_size);
1675
    PRINT("sub_packet",q->sub_packet);
1676
    PRINT("frequency_range",q->frequency_range);
1677
    PRINT("has_errors",q->has_errors);
1678
    PRINT("fft_tone_end",q->fft_tone_end);
1679
    PRINT("fft_tone_start",q->fft_tone_start);
1680
    PRINT("fft_coefs_index",q->fft_coefs_index);
1681
    PRINT("coeff_per_sb_select",q->coeff_per_sb_select);
1682
    PRINT("cm_table_select",q->cm_table_select);
1683
    PRINT("noise_idx",q->noise_idx);
1684

1685
    for (i = q->fft_tone_start; i < q->fft_tone_end; i++)
1686
    {
1687
    FFTTone *t = &q->fft_tones[i];
1688

1689
    av_log(NULL,AV_LOG_DEBUG,"Tone (%d) dump:\n", i);
1690
    av_log(NULL,AV_LOG_DEBUG,"  level = %f\n", t->level);
1691
//  PRINT(" level", t->level);
1692
    PRINT(" phase", t->phase);
1693
    PRINT(" phase_shift", t->phase_shift);
1694
    PRINT(" duration", t->duration);
1695
    PRINT(" samples_im", t->samples_im);
1696
    PRINT(" samples_re", t->samples_re);
1697
    PRINT(" table", t->table);
1698
    }
1699

1700
}
1701
#endif
1702

    
1703

    
1704
/**
1705
 * Init parameters from codec extradata
1706
 */
1707
static av_cold int qdm2_decode_init(AVCodecContext *avctx)
1708
{
1709
    QDM2Context *s = avctx->priv_data;
1710
    uint8_t *extradata;
1711
    int extradata_size;
1712
    int tmp_val, tmp, size;
1713

    
1714
    /* extradata parsing
1715

1716
    Structure:
1717
    wave {
1718
        frma (QDM2)
1719
        QDCA
1720
        QDCP
1721
    }
1722

1723
    32  size (including this field)
1724
    32  tag (=frma)
1725
    32  type (=QDM2 or QDMC)
1726

1727
    32  size (including this field, in bytes)
1728
    32  tag (=QDCA) // maybe mandatory parameters
1729
    32  unknown (=1)
1730
    32  channels (=2)
1731
    32  samplerate (=44100)
1732
    32  bitrate (=96000)
1733
    32  block size (=4096)
1734
    32  frame size (=256) (for one channel)
1735
    32  packet size (=1300)
1736

1737
    32  size (including this field, in bytes)
1738
    32  tag (=QDCP) // maybe some tuneable parameters
1739
    32  float1 (=1.0)
1740
    32  zero ?
1741
    32  float2 (=1.0)
1742
    32  float3 (=1.0)
1743
    32  unknown (27)
1744
    32  unknown (8)
1745
    32  zero ?
1746
    */
1747

    
1748
    if (!avctx->extradata || (avctx->extradata_size < 48)) {
1749
        av_log(avctx, AV_LOG_ERROR, "extradata missing or truncated\n");
1750
        return -1;
1751
    }
1752

    
1753
    extradata = avctx->extradata;
1754
    extradata_size = avctx->extradata_size;
1755

    
1756
    while (extradata_size > 7) {
1757
        if (!memcmp(extradata, "frmaQDM", 7))
1758
            break;
1759
        extradata++;
1760
        extradata_size--;
1761
    }
1762

    
1763
    if (extradata_size < 12) {
1764
        av_log(avctx, AV_LOG_ERROR, "not enough extradata (%i)\n",
1765
               extradata_size);
1766
        return -1;
1767
    }
1768

    
1769
    if (memcmp(extradata, "frmaQDM", 7)) {
1770
        av_log(avctx, AV_LOG_ERROR, "invalid headers, QDM? not found\n");
1771
        return -1;
1772
    }
1773

    
1774
    if (extradata[7] == 'C') {
1775
//        s->is_qdmc = 1;
1776
        av_log(avctx, AV_LOG_ERROR, "stream is QDMC version 1, which is not supported\n");
1777
        return -1;
1778
    }
1779

    
1780
    extradata += 8;
1781
    extradata_size -= 8;
1782

    
1783
    size = AV_RB32(extradata);
1784

    
1785
    if(size > extradata_size){
1786
        av_log(avctx, AV_LOG_ERROR, "extradata size too small, %i < %i\n",
1787
               extradata_size, size);
1788
        return -1;
1789
    }
1790

    
1791
    extradata += 4;
1792
    av_log(avctx, AV_LOG_DEBUG, "size: %d\n", size);
1793
    if (AV_RB32(extradata) != MKBETAG('Q','D','C','A')) {
1794
        av_log(avctx, AV_LOG_ERROR, "invalid extradata, expecting QDCA\n");
1795
        return -1;
1796
    }
1797

    
1798
    extradata += 8;
1799

    
1800
    avctx->channels = s->nb_channels = s->channels = AV_RB32(extradata);
1801
    extradata += 4;
1802

    
1803
    avctx->sample_rate = AV_RB32(extradata);
1804
    extradata += 4;
1805

    
1806
    avctx->bit_rate = AV_RB32(extradata);
1807
    extradata += 4;
1808

    
1809
    s->group_size = AV_RB32(extradata);
1810
    extradata += 4;
1811

    
1812
    s->fft_size = AV_RB32(extradata);
1813
    extradata += 4;
1814

    
1815
    s->checksum_size = AV_RB32(extradata);
1816

    
1817
    s->fft_order = av_log2(s->fft_size) + 1;
1818
    s->fft_frame_size = 2 * s->fft_size; // complex has two floats
1819

    
1820
    // something like max decodable tones
1821
    s->group_order = av_log2(s->group_size) + 1;
1822
    s->frame_size = s->group_size / 16; // 16 iterations per super block
1823

    
1824
    s->sub_sampling = s->fft_order - 7;
1825
    s->frequency_range = 255 / (1 << (2 - s->sub_sampling));
1826

    
1827
    switch ((s->sub_sampling * 2 + s->channels - 1)) {
1828
        case 0: tmp = 40; break;
1829
        case 1: tmp = 48; break;
1830
        case 2: tmp = 56; break;
1831
        case 3: tmp = 72; break;
1832
        case 4: tmp = 80; break;
1833
        case 5: tmp = 100;break;
1834
        default: tmp=s->sub_sampling; break;
1835
    }
1836
    tmp_val = 0;
1837
    if ((tmp * 1000) < avctx->bit_rate)  tmp_val = 1;
1838
    if ((tmp * 1440) < avctx->bit_rate)  tmp_val = 2;
1839
    if ((tmp * 1760) < avctx->bit_rate)  tmp_val = 3;
1840
    if ((tmp * 2240) < avctx->bit_rate)  tmp_val = 4;
1841
    s->cm_table_select = tmp_val;
1842

    
1843
    if (s->sub_sampling == 0)
1844
        tmp = 7999;
1845
    else
1846
        tmp = ((-(s->sub_sampling -1)) & 8000) + 20000;
1847
    /*
1848
    0: 7999 -> 0
1849
    1: 20000 -> 2
1850
    2: 28000 -> 2
1851
    */
1852
    if (tmp < 8000)
1853
        s->coeff_per_sb_select = 0;
1854
    else if (tmp <= 16000)
1855
        s->coeff_per_sb_select = 1;
1856
    else
1857
        s->coeff_per_sb_select = 2;
1858

    
1859
    // Fail on unknown fft order
1860
    if ((s->fft_order < 7) || (s->fft_order > 9)) {
1861
        av_log(avctx, AV_LOG_ERROR, "Unknown FFT order (%d), contact the developers!\n", s->fft_order);
1862
        return -1;
1863
    }
1864

    
1865
    ff_rdft_init(&s->rdft_ctx, s->fft_order, IDFT_C2R);
1866

    
1867
    qdm2_init(s);
1868

    
1869
    avctx->sample_fmt = SAMPLE_FMT_S16;
1870

    
1871
//    dump_context(s);
1872
    return 0;
1873
}
1874

    
1875

    
1876
static av_cold int qdm2_decode_close(AVCodecContext *avctx)
1877
{
1878
    QDM2Context *s = avctx->priv_data;
1879

    
1880
    ff_rdft_end(&s->rdft_ctx);
1881

    
1882
    return 0;
1883
}
1884

    
1885

    
1886
static void qdm2_decode (QDM2Context *q, const uint8_t *in, int16_t *out)
1887
{
1888
    int ch, i;
1889
    const int frame_size = (q->frame_size * q->channels);
1890

    
1891
    /* select input buffer */
1892
    q->compressed_data = in;
1893
    q->compressed_size = q->checksum_size;
1894

    
1895
//  dump_context(q);
1896

    
1897
    /* copy old block, clear new block of output samples */
1898
    memmove(q->output_buffer, &q->output_buffer[frame_size], frame_size * sizeof(float));
1899
    memset(&q->output_buffer[frame_size], 0, frame_size * sizeof(float));
1900

    
1901
    /* decode block of QDM2 compressed data */
1902
    if (q->sub_packet == 0) {
1903
        q->has_errors = 0; // zero it for a new super block
1904
        av_log(NULL,AV_LOG_DEBUG,"Superblock follows\n");
1905
        qdm2_decode_super_block(q);
1906
    }
1907

    
1908
    /* parse subpackets */
1909
    if (!q->has_errors) {
1910
        if (q->sub_packet == 2)
1911
            qdm2_decode_fft_packets(q);
1912

    
1913
        qdm2_fft_tone_synthesizer(q, q->sub_packet);
1914
    }
1915

    
1916
    /* sound synthesis stage 1 (FFT) */
1917
    for (ch = 0; ch < q->channels; ch++) {
1918
        qdm2_calculate_fft(q, ch, q->sub_packet);
1919

    
1920
        if (!q->has_errors && q->sub_packet_list_C[0].packet != NULL) {
1921
            SAMPLES_NEEDED_2("has errors, and C list is not empty")
1922
            return;
1923
        }
1924
    }
1925

    
1926
    /* sound synthesis stage 2 (MPEG audio like synthesis filter) */
1927
    if (!q->has_errors && q->do_synth_filter)
1928
        qdm2_synthesis_filter(q, q->sub_packet);
1929

    
1930
    q->sub_packet = (q->sub_packet + 1) % 16;
1931

    
1932
    /* clip and convert output float[] to 16bit signed samples */
1933
    for (i = 0; i < frame_size; i++) {
1934
        int value = (int)q->output_buffer[i];
1935

    
1936
        if (value > SOFTCLIP_THRESHOLD)
1937
            value = (value >  HARDCLIP_THRESHOLD) ?  32767 :  softclip_table[ value - SOFTCLIP_THRESHOLD];
1938
        else if (value < -SOFTCLIP_THRESHOLD)
1939
            value = (value < -HARDCLIP_THRESHOLD) ? -32767 : -softclip_table[-value - SOFTCLIP_THRESHOLD];
1940

    
1941
        out[i] = value;
1942
    }
1943
}
1944

    
1945

    
1946
static int qdm2_decode_frame(AVCodecContext *avctx,
1947
            void *data, int *data_size,
1948
            AVPacket *avpkt)
1949
{
1950
    const uint8_t *buf = avpkt->data;
1951
    int buf_size = avpkt->size;
1952
    QDM2Context *s = avctx->priv_data;
1953

    
1954
    if(!buf)
1955
        return 0;
1956
    if(buf_size < s->checksum_size)
1957
        return -1;
1958

    
1959
    *data_size = s->channels * s->frame_size * sizeof(int16_t);
1960

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

    
1964
    qdm2_decode(s, buf, data);
1965

    
1966
    // reading only when next superblock found
1967
    if (s->sub_packet == 0) {
1968
        return s->checksum_size;
1969
    }
1970

    
1971
    return 0;
1972
}
1973

    
1974
AVCodec qdm2_decoder =
1975
{
1976
    .name = "qdm2",
1977
    .type = AVMEDIA_TYPE_AUDIO,
1978
    .id = CODEC_ID_QDM2,
1979
    .priv_data_size = sizeof(QDM2Context),
1980
    .init = qdm2_decode_init,
1981
    .close = qdm2_decode_close,
1982
    .decode = qdm2_decode_frame,
1983
    .long_name = NULL_IF_CONFIG_SMALL("QDesign Music Codec 2"),
1984
};