Coverage Report

Created: 2024-09-06 07:53

/src/ffmpeg/libavcodec/qdm2.c
Line
Count
Source (jump to first uncovered line)
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
27
 * QDM2 decoder
28
 * @author Ewald Snel, Benjamin Larsson, Alex Beregszaszi, Roberto Togni
29
 *
30
 * The decoder is not perfect yet, there are still some distortions
31
 * especially on files encoded with 16 or 8 subbands.
32
 */
33
34
#include <math.h>
35
#include <stddef.h>
36
37
#include "libavutil/channel_layout.h"
38
#include "libavutil/mem_internal.h"
39
#include "libavutil/thread.h"
40
#include "libavutil/tx.h"
41
42
#define BITSTREAM_READER_LE
43
#include "avcodec.h"
44
#include "get_bits.h"
45
#include "bytestream.h"
46
#include "codec_internal.h"
47
#include "decode.h"
48
#include "mpegaudio.h"
49
#include "mpegaudiodsp.h"
50
51
#include "qdm2_tablegen.h"
52
53
47.0k
#define QDM2_LIST_ADD(list, size, packet) \
54
47.0k
do { \
55
47.0k
      if (size > 0) { \
56
17.7k
    list[size - 1].next = &list[size]; \
57
17.7k
      } \
58
47.0k
      list[size].packet = packet; \
59
47.0k
      list[size].next = NULL; \
60
47.0k
      size++; \
61
47.0k
} while(0)
62
63
// Result is 8, 16 or 30
64
1.96M
#define QDM2_SB_USED(sub_sampling) (((sub_sampling) >= 2) ? 30 : 8 << (sub_sampling))
65
66
#define FIX_NOISE_IDX(noise_idx) \
67
1.44M
  if ((noise_idx) >= 3840) \
68
1.44M
    (noise_idx) -= 3840; \
69
70
251M
#define SB_DITHERING_NOISE(sb,noise_idx) (noise_table[(noise_idx)++] * sb_noise_attenuation[(sb)])
71
72
#define SAMPLES_NEEDED \
73
332
     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
878
     av_log (NULL,AV_LOG_INFO,"This file triggers some missing code. Please contact the developers.\nPosition: %s\n",why);
77
78
1.51k
#define QDM2_MAX_FRAME_SIZE 512
79
80
typedef int8_t sb_int8_array[2][30][64];
81
82
/**
83
 * Subpacket
84
 */
85
typedef struct QDM2SubPacket {
86
    int type;            ///< subpacket type
87
    unsigned int size;   ///< subpacket size
88
    const uint8_t *data; ///< pointer to subpacket data (points to input data buffer, it's not a private copy)
89
} QDM2SubPacket;
90
91
/**
92
 * A node in the subpacket list
93
 */
94
typedef struct QDM2SubPNode {
95
    QDM2SubPacket *packet;      ///< packet
96
    struct QDM2SubPNode *next; ///< pointer to next packet in the list, NULL if leaf node
97
} QDM2SubPNode;
98
99
typedef struct FFTTone {
100
    float level;
101
    AVComplexFloat *complex;
102
    const float *table;
103
    int   phase;
104
    int   phase_shift;
105
    int   duration;
106
    short time_index;
107
    short cutoff;
108
} FFTTone;
109
110
typedef struct FFTCoefficient {
111
    int16_t sub_packet;
112
    uint8_t channel;
113
    int16_t offset;
114
    int16_t exp;
115
    uint8_t phase;
116
} FFTCoefficient;
117
118
typedef struct QDM2FFT {
119
    DECLARE_ALIGNED(32, AVComplexFloat, complex)[MPA_MAX_CHANNELS][256 + 1];
120
    DECLARE_ALIGNED(32, AVComplexFloat, temp)[MPA_MAX_CHANNELS][256];
121
} QDM2FFT;
122
123
/**
124
 * QDM2 decoder context
125
 */
126
typedef struct QDM2Context {
127
    /// Parameters from codec header, do not change during playback
128
    int nb_channels;         ///< number of channels
129
    int channels;            ///< number of channels
130
    int group_size;          ///< size of frame group (16 frames per group)
131
    int fft_size;            ///< size of FFT, in complex numbers
132
    int checksum_size;       ///< size of data block, used also for checksum
133
134
    /// Parameters built from header parameters, do not change during playback
135
    int group_order;         ///< order of frame group
136
    int fft_order;           ///< order of FFT (actually fftorder+1)
137
    int frame_size;          ///< size of data frame
138
    int frequency_range;
139
    int sub_sampling;        ///< subsampling: 0=25%, 1=50%, 2=100% */
140
    int coeff_per_sb_select; ///< selector for "num. of coeffs. per subband" tables. Can be 0, 1, 2
141
    int cm_table_select;     ///< selector for "coding method" tables. Can be 0, 1 (from init: 0-4)
142
143
    /// Packets and packet lists
144
    QDM2SubPacket sub_packets[16];      ///< the packets themselves
145
    QDM2SubPNode sub_packet_list_A[16]; ///< list of all packets
146
    QDM2SubPNode sub_packet_list_B[16]; ///< FFT packets B are on list
147
    int sub_packets_B;                  ///< number of packets on 'B' list
148
    QDM2SubPNode sub_packet_list_C[16]; ///< packets with errors?
149
    QDM2SubPNode sub_packet_list_D[16]; ///< DCT packets
150
151
    /// FFT and tones
152
    FFTTone fft_tones[1000];
153
    int fft_tone_start;
154
    int fft_tone_end;
155
    FFTCoefficient fft_coefs[1000];
156
    int fft_coefs_index;
157
    int fft_coefs_min_index[5];
158
    int fft_coefs_max_index[5];
159
    int fft_level_exp[6];
160
    AVTXContext *rdft_ctx;
161
    av_tx_fn rdft_fn;
162
    QDM2FFT fft;
163
164
    /// I/O data
165
    const uint8_t *compressed_data;
166
    int compressed_size;
167
    float output_buffer[QDM2_MAX_FRAME_SIZE * MPA_MAX_CHANNELS * 2];
168
169
    /// Synthesis filter
170
    MPADSPContext mpadsp;
171
    DECLARE_ALIGNED(32, float, synth_buf)[MPA_MAX_CHANNELS][512*2];
172
    int synth_buf_offset[MPA_MAX_CHANNELS];
173
    DECLARE_ALIGNED(32, float, sb_samples)[MPA_MAX_CHANNELS][128][SBLIMIT];
174
    DECLARE_ALIGNED(32, float, samples)[MPA_MAX_CHANNELS * MPA_FRAME_SIZE];
175
176
    /// Mixed temporary data used in decoding
177
    float tone_level[MPA_MAX_CHANNELS][30][64];
178
    int8_t coding_method[MPA_MAX_CHANNELS][30][64];
179
    int8_t quantized_coeffs[MPA_MAX_CHANNELS][10][8];
180
    int8_t tone_level_idx_base[MPA_MAX_CHANNELS][30][8];
181
    int8_t tone_level_idx_hi1[MPA_MAX_CHANNELS][3][8][8];
182
    int8_t tone_level_idx_mid[MPA_MAX_CHANNELS][26][8];
183
    int8_t tone_level_idx_hi2[MPA_MAX_CHANNELS][26];
184
    int8_t tone_level_idx[MPA_MAX_CHANNELS][30][64];
185
    int8_t tone_level_idx_temp[MPA_MAX_CHANNELS][30][64];
186
187
    // Flags
188
    int has_errors;         ///< packet has errors
189
    int superblocktype_2_3; ///< select fft tables and some algorithm based on superblock type
190
    int do_synth_filter;    ///< used to perform or skip synthesis filter
191
192
    int sub_packet;
193
    int noise_idx; ///< index for dithering noise table
194
} QDM2Context;
195
196
static const int switchtable[23] = {
197
    0, 5, 1, 5, 5, 5, 5, 5, 2, 5, 5, 5, 5, 5, 5, 5, 3, 5, 5, 5, 5, 5, 4
198
};
199
200
static int qdm2_get_vlc(GetBitContext *gb, const VLC *vlc, int flag, int depth)
201
3.23M
{
202
3.23M
    int value;
203
204
3.23M
    value = get_vlc2(gb, vlc->table, vlc->bits, depth);
205
206
    /* stage-2, 3 bits exponent escape sequence */
207
3.23M
    if (value < 0)
208
30.3k
        value = get_bits(gb, get_bits(gb, 3) + 1);
209
210
    /* stage-3, optional */
211
3.23M
    if (flag) {
212
1.15M
        int tmp;
213
214
1.15M
        if (value >= 60) {
215
1.66k
            av_log(NULL, AV_LOG_ERROR, "value %d in qdm2_get_vlc too large\n", value);
216
1.66k
            return 0;
217
1.66k
        }
218
219
1.14M
        tmp= vlc_stage3_values[value];
220
221
1.14M
        if ((value & ~3) > 0)
222
176k
            tmp += get_bits(gb, (value >> 2));
223
1.14M
        value = tmp;
224
1.14M
    }
225
226
3.23M
    return value;
227
3.23M
}
228
229
static int qdm2_get_se_vlc(const VLC *vlc, GetBitContext *gb, int depth)
230
320k
{
231
320k
    int value = qdm2_get_vlc(gb, vlc, 0, depth);
232
233
320k
    return (value & 1) ? ((value + 1) >> 1) : -(value >> 1);
234
320k
}
235
236
/**
237
 * QDM2 checksum
238
 *
239
 * @param data      pointer to data to be checksummed
240
 * @param length    data length
241
 * @param value     checksum value
242
 *
243
 * @return          0 if checksum is OK
244
 */
245
static uint16_t qdm2_packet_checksum(const uint8_t *data, int length, int value)
246
11.8k
{
247
11.8k
    int i;
248
249
61.2k
    for (i = 0; i < length; i++)
250
49.4k
        value -= data[i];
251
252
11.8k
    return (uint16_t)(value & 0xffff);
253
11.8k
}
254
255
/**
256
 * Fill a QDM2SubPacket structure with packet type, size, and data pointer.
257
 *
258
 * @param gb            bitreader context
259
 * @param sub_packet    packet under analysis
260
 */
261
static void qdm2_decode_sub_packet_header(GetBitContext *gb,
262
                                          QDM2SubPacket *sub_packet)
263
855k
{
264
855k
    sub_packet->type = get_bits(gb, 8);
265
266
855k
    if (sub_packet->type == 0) {
267
95.3k
        sub_packet->size = 0;
268
95.3k
        sub_packet->data = NULL;
269
760k
    } else {
270
760k
        sub_packet->size = get_bits(gb, 8);
271
272
760k
        if (sub_packet->type & 0x80) {
273
192k
            sub_packet->size <<= 8;
274
192k
            sub_packet->size  |= get_bits(gb, 8);
275
192k
            sub_packet->type  &= 0x7f;
276
192k
        }
277
278
760k
        if (sub_packet->type == 0x7f)
279
82.3k
            sub_packet->type |= (get_bits(gb, 8) << 8);
280
281
        // FIXME: this depends on bitreader-internal data
282
760k
        sub_packet->data = &gb->buffer[get_bits_count(gb) / 8];
283
760k
    }
284
285
855k
    av_log(NULL, AV_LOG_DEBUG, "Subpacket: type=%d size=%d start_offs=%x\n",
286
855k
           sub_packet->type, sub_packet->size, get_bits_count(gb) / 8);
287
855k
}
288
289
/**
290
 * Return node pointer to first packet of requested type in list.
291
 *
292
 * @param list    list of subpackets to be scanned
293
 * @param type    type of searched subpacket
294
 * @return        node pointer for subpacket if found, else NULL
295
 */
296
static QDM2SubPNode *qdm2_search_subpacket_type_in_list(QDM2SubPNode *list,
297
                                                        int type)
298
68.4k
{
299
135k
    while (list && list->packet) {
300
94.6k
        if (list->packet->type == type)
301
27.3k
            return list;
302
67.2k
        list = list->next;
303
67.2k
    }
304
41.1k
    return NULL;
305
68.4k
}
306
307
/**
308
 * Replace 8 elements with their average value.
309
 * Called by qdm2_decode_superblock before starting subblock decoding.
310
 *
311
 * @param q       context
312
 */
313
static void average_quantized_coeffs(QDM2Context *q)
314
721k
{
315
721k
    int i, j, n, ch, sum;
316
317
721k
    n = coeff_per_sb_for_avg[q->coeff_per_sb_select][QDM2_SB_USED(q->sub_sampling) - 1] + 1;
318
319
1.58M
    for (ch = 0; ch < q->nb_channels; ch++)
320
5.83M
        for (i = 0; i < n; i++) {
321
4.96M
            sum = 0;
322
323
44.7M
            for (j = 0; j < 8; j++)
324
39.7M
                sum += q->quantized_coeffs[ch][i][j];
325
326
4.96M
            sum /= 8;
327
4.96M
            if (sum > 0)
328
82.0k
                sum--;
329
330
44.7M
            for (j = 0; j < 8; j++)
331
39.7M
                q->quantized_coeffs[ch][i][j] = sum;
332
4.96M
        }
333
721k
}
334
335
/**
336
 * Build subband samples with noise weighted by q->tone_level.
337
 * Called by synthfilt_build_sb_samples.
338
 *
339
 * @param q     context
340
 * @param sb    subband index
341
 */
342
static void build_sb_samples_from_noise(QDM2Context *q, int sb)
343
1.39M
{
344
1.39M
    int ch, j;
345
346
1.39M
    FIX_NOISE_IDX(q->noise_idx);
347
348
1.39M
    if (!q->nb_channels)
349
0
        return;
350
351
3.29M
    for (ch = 0; ch < q->nb_channels; ch++) {
352
124M
        for (j = 0; j < 64; j++) {
353
122M
            q->sb_samples[ch][j * 2][sb] =
354
122M
                SB_DITHERING_NOISE(sb, q->noise_idx) * q->tone_level[ch][sb][j];
355
122M
            q->sb_samples[ch][j * 2 + 1][sb] =
356
122M
                SB_DITHERING_NOISE(sb, q->noise_idx) * q->tone_level[ch][sb][j];
357
122M
        }
358
1.90M
    }
359
1.39M
}
360
361
/**
362
 * Called while processing data from subpackets 11 and 12.
363
 * Used after making changes to coding_method array.
364
 *
365
 * @param sb               subband index
366
 * @param channels         number of channels
367
 * @param coding_method    q->coding_method[0][0][0]
368
 */
369
static int fix_coding_method_array(int sb, int channels,
370
                                   sb_int8_array coding_method)
371
12.1k
{
372
12.1k
    int j, k;
373
12.1k
    int ch;
374
12.1k
    int run, case_val;
375
376
15.0k
    for (ch = 0; ch < channels; ch++) {
377
86.4k
        for (j = 0; j < 64; ) {
378
83.5k
            if (coding_method[ch][sb][j] < 8)
379
10.6k
                return -1;
380
72.8k
            if ((coding_method[ch][sb][j] - 8) > 22) {
381
0
                run      = 1;
382
0
                case_val = 8;
383
72.8k
            } else {
384
72.8k
                switch (switchtable[coding_method[ch][sb][j] - 8]) {
385
0
                case 0: run  = 10;
386
0
                    case_val = 10;
387
0
                    break;
388
43.1k
                case 1: run  = 1;
389
43.1k
                    case_val = 16;
390
43.1k
                    break;
391
28.4k
                case 2: run  = 5;
392
28.4k
                    case_val = 24;
393
28.4k
                    break;
394
1.18k
                case 3: run  = 3;
395
1.18k
                    case_val = 30;
396
1.18k
                    break;
397
0
                case 4: run  = 1;
398
0
                    case_val = 30;
399
0
                    break;
400
0
                case 5: run  = 1;
401
0
                    case_val = 8;
402
0
                    break;
403
0
                default: run = 1;
404
0
                    case_val = 8;
405
0
                    break;
406
72.8k
                }
407
72.8k
            }
408
262k
            for (k = 0; k < run; k++) {
409
189k
                if (j + k < 128) {
410
189k
                    int sbjk = sb + (j + k) / 64;
411
189k
                    if (sbjk > 29) {
412
332
                        SAMPLES_NEEDED
413
332
                        continue;
414
332
                    }
415
188k
                    if (coding_method[ch][sbjk][(j + k) % 64] > coding_method[ch][sb][j]) {
416
0
                        if (k > 0) {
417
0
                            SAMPLES_NEEDED
418
                            //not debugged, almost never used
419
0
                            memset(&coding_method[ch][sb][j + k], case_val,
420
0
                                   k *sizeof(int8_t));
421
0
                            memset(&coding_method[ch][sb][j + k], case_val,
422
0
                                   3 * sizeof(int8_t));
423
0
                        }
424
0
                    }
425
188k
                }
426
189k
            }
427
72.8k
            j += run;
428
72.8k
        }
429
13.6k
    }
430
1.46k
    return 0;
431
12.1k
}
432
433
/**
434
 * Related to synthesis filter
435
 * Called by process_subpacket_10
436
 *
437
 * @param q       context
438
 * @param flag    1 if called after getting data from subpacket 10, 0 if no subpacket 10
439
 */
440
static void fill_tone_level_array(QDM2Context *q, int flag)
441
67.0k
{
442
67.0k
    int i, sb, ch, sb_used;
443
67.0k
    int tmp, tab;
444
445
168k
    for (ch = 0; ch < q->nb_channels; ch++)
446
3.14M
        for (sb = 0; sb < 30; sb++)
447
27.4M
            for (i = 0; i < 8; i++) {
448
24.3M
                if ((tab=coeff_per_sb_for_dequant[q->coeff_per_sb_select][sb]) < (last_coeff[q->coeff_per_sb_select] - 1))
449
18.7M
                    tmp = q->quantized_coeffs[ch][tab + 1][i] * dequant_table[q->coeff_per_sb_select][tab + 1][sb]+
450
18.7M
                          q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];
451
5.60M
                else
452
5.60M
                    tmp = q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];
453
24.3M
                if(tmp < 0)
454
87.2k
                    tmp += 0xff;
455
24.3M
                q->tone_level_idx_base[ch][sb][i] = (tmp / 256) & 0xff;
456
24.3M
            }
457
458
67.0k
    sb_used = QDM2_SB_USED(q->sub_sampling);
459
460
67.0k
    if ((q->superblocktype_2_3 != 0) && !flag) {
461
234k
        for (sb = 0; sb < sb_used; sb++)
462
516k
            for (ch = 0; ch < q->nb_channels; ch++)
463
19.0M
                for (i = 0; i < 64; i++) {
464
18.7M
                    q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];
465
18.7M
                    if (q->tone_level_idx[ch][sb][i] < 0)
466
431k
                        q->tone_level[ch][sb][i] = 0;
467
18.3M
                    else
468
18.3M
                        q->tone_level[ch][sb][i] = fft_tone_level_table[0][q->tone_level_idx[ch][sb][i] & 0x3f];
469
18.7M
                }
470
56.3k
    } else {
471
56.3k
        tab = q->superblocktype_2_3 ? 0 : 1;
472
1.26M
        for (sb = 0; sb < sb_used; sb++) {
473
1.21M
            if ((sb >= 4) && (sb <= 23)) {
474
1.97M
                for (ch = 0; ch < q->nb_channels; ch++)
475
74.8M
                    for (i = 0; i < 64; i++) {
476
73.6M
                        tmp = q->tone_level_idx_base[ch][sb][i / 8] -
477
73.6M
                              q->tone_level_idx_hi1[ch][sb / 8][i / 8][i % 8] -
478
73.6M
                              q->tone_level_idx_mid[ch][sb - 4][i / 8] -
479
73.6M
                              q->tone_level_idx_hi2[ch][sb - 4];
480
73.6M
                        q->tone_level_idx[ch][sb][i] = tmp & 0xff;
481
73.6M
                        if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
482
62.7M
                            q->tone_level[ch][sb][i] = 0;
483
10.9M
                        else
484
10.9M
                            q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
485
73.6M
                }
486
819k
            } else {
487
394k
                if (sb > 4) {
488
370k
                    for (ch = 0; ch < q->nb_channels; ch++)
489
13.0M
                        for (i = 0; i < 64; i++) {
490
12.8M
                            tmp = q->tone_level_idx_base[ch][sb][i / 8] -
491
12.8M
                                  q->tone_level_idx_hi1[ch][2][i / 8][i % 8] -
492
12.8M
                                  q->tone_level_idx_hi2[ch][sb - 4];
493
12.8M
                            q->tone_level_idx[ch][sb][i] = tmp & 0xff;
494
12.8M
                            if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
495
10.4M
                                q->tone_level[ch][sb][i] = 0;
496
2.47M
                            else
497
2.47M
                                q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
498
12.8M
                    }
499
225k
                } else {
500
573k
                    for (ch = 0; ch < q->nb_channels; ch++)
501
22.6M
                        for (i = 0; i < 64; i++) {
502
22.2M
                            tmp = q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];
503
22.2M
                            if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
504
19.1M
                                q->tone_level[ch][sb][i] = 0;
505
3.16M
                            else
506
3.16M
                                q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
507
22.2M
                        }
508
225k
                }
509
394k
            }
510
1.21M
        }
511
56.3k
    }
512
67.0k
}
513
514
/**
515
 * Related to synthesis filter
516
 * Called by process_subpacket_11
517
 * c is built with data from subpacket 11
518
 * Most of this function is used only if superblock_type_2_3 == 0,
519
 * never seen it in samples.
520
 *
521
 * @param tone_level_idx
522
 * @param tone_level_idx_temp
523
 * @param coding_method        q->coding_method[0][0][0]
524
 * @param nb_channels          number of channels
525
 * @param c                    coming from subpacket 11, passed as 8*c
526
 * @param superblocktype_2_3   flag based on superblock packet type
527
 * @param cm_table_select      q->cm_table_select
528
 */
529
static void fill_coding_method_array(sb_int8_array tone_level_idx,
530
                                     sb_int8_array tone_level_idx_temp,
531
                                     sb_int8_array coding_method,
532
                                     int nb_channels,
533
                                     int c, int superblocktype_2_3,
534
                                     int cm_table_select)
535
1.81k
{
536
1.81k
    int ch, sb, j;
537
1.81k
    int tmp, acc, esp_40, comp;
538
1.81k
    int add1, add2, add3, add4;
539
1.81k
    int64_t multres;
540
541
1.81k
    if (!superblocktype_2_3) {
542
        /* This case is untested, no samples available */
543
196
        avpriv_request_sample(NULL, "!superblocktype_2_3");
544
196
        return;
545
0
        for (ch = 0; ch < nb_channels; ch++) {
546
0
            for (sb = 0; sb < 30; sb++) {
547
0
                for (j = 1; j < 63; j++) {  // The loop only iterates to 63 so the code doesn't overflow the buffer
548
0
                    add1 = tone_level_idx[ch][sb][j] - 10;
549
0
                    if (add1 < 0)
550
0
                        add1 = 0;
551
0
                    add2 = add3 = add4 = 0;
552
0
                    if (sb > 1) {
553
0
                        add2 = tone_level_idx[ch][sb - 2][j] + tone_level_idx_offset_table[sb][0] - 6;
554
0
                        if (add2 < 0)
555
0
                            add2 = 0;
556
0
                    }
557
0
                    if (sb > 0) {
558
0
                        add3 = tone_level_idx[ch][sb - 1][j] + tone_level_idx_offset_table[sb][1] - 6;
559
0
                        if (add3 < 0)
560
0
                            add3 = 0;
561
0
                    }
562
0
                    if (sb < 29) {
563
0
                        add4 = tone_level_idx[ch][sb + 1][j] + tone_level_idx_offset_table[sb][3] - 6;
564
0
                        if (add4 < 0)
565
0
                            add4 = 0;
566
0
                    }
567
0
                    tmp = tone_level_idx[ch][sb][j + 1] * 2 - add4 - add3 - add2 - add1;
568
0
                    if (tmp < 0)
569
0
                        tmp = 0;
570
0
                    tone_level_idx_temp[ch][sb][j + 1] = tmp & 0xff;
571
0
                }
572
0
                tone_level_idx_temp[ch][sb][0] = tone_level_idx_temp[ch][sb][1];
573
0
            }
574
0
        }
575
0
        acc = 0;
576
0
        for (ch = 0; ch < nb_channels; ch++)
577
0
            for (sb = 0; sb < 30; sb++)
578
0
                for (j = 0; j < 64; j++)
579
0
                    acc += tone_level_idx_temp[ch][sb][j];
580
581
0
        multres = 0x66666667LL * (acc * 10);
582
0
        esp_40 = (multres >> 32) / 8 + ((multres & 0xffffffff) >> 31);
583
0
        for (ch = 0;  ch < nb_channels; ch++)
584
0
            for (sb = 0; sb < 30; sb++)
585
0
                for (j = 0; j < 64; j++) {
586
0
                    comp = tone_level_idx_temp[ch][sb][j]* esp_40 * 10;
587
0
                    if (comp < 0)
588
0
                        comp += 0xff;
589
0
                    comp /= 256; // signed shift
590
0
                    switch(sb) {
591
0
                        case 0:
592
0
                            if (comp < 30)
593
0
                                comp = 30;
594
0
                            comp += 15;
595
0
                            break;
596
0
                        case 1:
597
0
                            if (comp < 24)
598
0
                                comp = 24;
599
0
                            comp += 10;
600
0
                            break;
601
0
                        case 2:
602
0
                        case 3:
603
0
                        case 4:
604
0
                            if (comp < 16)
605
0
                                comp = 16;
606
0
                    }
607
0
                    if (comp <= 5)
608
0
                        tmp = 0;
609
0
                    else if (comp <= 10)
610
0
                        tmp = 10;
611
0
                    else if (comp <= 16)
612
0
                        tmp = 16;
613
0
                    else if (comp <= 24)
614
0
                        tmp = -1;
615
0
                    else
616
0
                        tmp = 0;
617
0
                    coding_method[ch][sb][j] = ((tmp & 0xfffa) + 30 )& 0xff;
618
0
                }
619
0
        for (sb = 0; sb < 30; sb++)
620
0
            fix_coding_method_array(sb, nb_channels, coding_method);
621
0
        for (ch = 0; ch < nb_channels; ch++)
622
0
            for (sb = 0; sb < 30; sb++)
623
0
                for (j = 0; j < 64; j++)
624
0
                    if (sb >= 10) {
625
0
                        if (coding_method[ch][sb][j] < 10)
626
0
                            coding_method[ch][sb][j] = 10;
627
0
                    } else {
628
0
                        if (sb >= 2) {
629
0
                            if (coding_method[ch][sb][j] < 16)
630
0
                                coding_method[ch][sb][j] = 16;
631
0
                        } else {
632
0
                            if (coding_method[ch][sb][j] < 30)
633
0
                                coding_method[ch][sb][j] = 30;
634
0
                        }
635
0
                    }
636
1.62k
    } else { // superblocktype_2_3 != 0
637
4.33k
        for (ch = 0; ch < nb_channels; ch++)
638
83.9k
            for (sb = 0; sb < 30; sb++)
639
5.28M
                for (j = 0; j < 64; j++)
640
5.20M
                    coding_method[ch][sb][j] = coding_method_table[cm_table_select][sb];
641
1.62k
    }
642
1.81k
}
643
644
/**
645
 * Called by process_subpacket_11 to process more data from subpacket 11
646
 * with sb 0-8.
647
 * Called by process_subpacket_12 to process data from subpacket 12 with
648
 * sb 8-sb_used.
649
 *
650
 * @param q         context
651
 * @param gb        bitreader context
652
 * @param length    packet length in bits
653
 * @param sb_min    lower subband processed (sb_min included)
654
 * @param sb_max    higher subband processed (sb_max excluded)
655
 */
656
static int synthfilt_build_sb_samples(QDM2Context *q, GetBitContext *gb,
657
                                       int length, int sb_min, int sb_max)
658
134k
{
659
134k
    int sb, j, k, n, ch, run, channels;
660
134k
    int joined_stereo, zero_encoding;
661
134k
    int type34_first;
662
134k
    float type34_div = 0;
663
134k
    float type34_predictor;
664
134k
    float samples[10];
665
134k
    int sign_bits[16] = {0};
666
667
134k
    if (length == 0) {
668
        // If no data use noise
669
1.50M
        for (sb=sb_min; sb < sb_max; sb++)
670
1.37M
            build_sb_samples_from_noise(q, sb);
671
672
129k
        return 0;
673
129k
    }
674
675
47.2k
    for (sb = sb_min; sb < sb_max; sb++) {
676
44.2k
        channels = q->nb_channels;
677
678
44.2k
        if (q->nb_channels <= 1 || sb < 12)
679
19.5k
            joined_stereo = 0;
680
24.7k
        else if (sb >= 24)
681
8.10k
            joined_stereo = 1;
682
16.6k
        else
683
16.6k
            joined_stereo = (get_bits_left(gb) >= 1) ? get_bits1(gb) : 0;
684
685
44.2k
        if (joined_stereo) {
686
12.1k
            if (get_bits_left(gb) >= 16)
687
96.9k
                for (j = 0; j < 16; j++)
688
91.2k
                    sign_bits[j] = get_bits1(gb);
689
690
790k
            for (j = 0; j < 64; j++)
691
777k
                if (q->coding_method[1][sb][j] > q->coding_method[0][sb][j])
692
0
                    q->coding_method[0][sb][j] = q->coding_method[1][sb][j];
693
694
12.1k
            if (fix_coding_method_array(sb, q->nb_channels,
695
12.1k
                                            q->coding_method)) {
696
10.6k
                av_log(NULL, AV_LOG_ERROR, "coding method invalid\n");
697
10.6k
                build_sb_samples_from_noise(q, sb);
698
10.6k
                continue;
699
10.6k
            }
700
1.46k
            channels = 1;
701
1.46k
        }
702
703
89.7k
        for (ch = 0; ch < channels; ch++) {
704
57.7k
            FIX_NOISE_IDX(q->noise_idx);
705
57.7k
            zero_encoding = (get_bits_left(gb) >= 1) ? get_bits1(gb) : 0;
706
57.7k
            type34_predictor = 0.0;
707
57.7k
            type34_first = 1;
708
709
6.12M
            for (j = 0; j < 128; ) {
710
6.07M
                switch (q->coding_method[ch][sb][j / 2]) {
711
0
                    case 8:
712
0
                        if (get_bits_left(gb) >= 10) {
713
0
                            if (zero_encoding) {
714
0
                                for (k = 0; k < 5; k++) {
715
0
                                    if ((j + 2 * k) >= 128)
716
0
                                        break;
717
0
                                    samples[2 * k] = get_bits1(gb) ? dequant_1bit[joined_stereo][2 * get_bits1(gb)] : 0;
718
0
                                }
719
0
                            } else {
720
0
                                n = get_bits(gb, 8);
721
0
                                if (n >= 243) {
722
0
                                    av_log(NULL, AV_LOG_ERROR, "Invalid 8bit codeword\n");
723
0
                                    return AVERROR_INVALIDDATA;
724
0
                                }
725
726
0
                                for (k = 0; k < 5; k++)
727
0
                                    samples[2 * k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];
728
0
                            }
729
0
                            for (k = 0; k < 5; k++)
730
0
                                samples[2 * k + 1] = SB_DITHERING_NOISE(sb,q->noise_idx);
731
0
                        } else {
732
0
                            for (k = 0; k < 10; k++)
733
0
                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
734
0
                        }
735
0
                        run = 10;
736
0
                        break;
737
738
169k
                    case 10:
739
169k
                        if (get_bits_left(gb) >= 1) {
740
22.2k
                            float f = 0.81;
741
742
22.2k
                            if (get_bits1(gb))
743
8.72k
                                f = -f;
744
22.2k
                            f -= noise_samples[((sb + 1) * (j +5 * ch + 1)) & 127] * 9.0 / 40.0;
745
22.2k
                            samples[0] = f;
746
147k
                        } else {
747
147k
                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
748
147k
                        }
749
169k
                        run = 1;
750
169k
                        break;
751
752
178k
                    case 16:
753
178k
                        if (get_bits_left(gb) >= 10) {
754
31.2k
                            if (zero_encoding) {
755
151k
                                for (k = 0; k < 5; k++) {
756
126k
                                    if ((j + k) >= 128)
757
949
                                        break;
758
125k
                                    samples[k] = (get_bits1(gb) == 0) ? 0 : dequant_1bit[joined_stereo][2 * get_bits1(gb)];
759
125k
                                }
760
25.5k
                            } else {
761
5.73k
                                n = get_bits (gb, 8);
762
5.73k
                                if (n >= 243) {
763
234
                                    av_log(NULL, AV_LOG_ERROR, "Invalid 8bit codeword\n");
764
234
                                    return AVERROR_INVALIDDATA;
765
234
                                }
766
767
33.0k
                                for (k = 0; k < 5; k++)
768
27.5k
                                    samples[k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];
769
5.50k
                            }
770
147k
                        } else {
771
886k
                            for (k = 0; k < 5; k++)
772
738k
                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
773
147k
                        }
774
178k
                        run = 5;
775
178k
                        break;
776
777
232k
                    case 24:
778
232k
                        if (get_bits_left(gb) >= 7) {
779
17.6k
                            n = get_bits(gb, 7);
780
17.6k
                            if (n >= 125) {
781
236
                                av_log(NULL, AV_LOG_ERROR, "Invalid 7bit codeword\n");
782
236
                                return AVERROR_INVALIDDATA;
783
236
                            }
784
785
69.7k
                            for (k = 0; k < 3; k++)
786
52.3k
                                samples[k] = (random_dequant_type24[n][k] - 2.0) * 0.5;
787
214k
                        } else {
788
859k
                            for (k = 0; k < 3; k++)
789
644k
                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
790
214k
                        }
791
232k
                        run = 3;
792
232k
                        break;
793
794
213k
                    case 30:
795
213k
                        if (get_bits_left(gb) >= 4) {
796
34.6k
                            unsigned index = qdm2_get_vlc(gb, &vlc_tab_type30, 0, 1);
797
34.6k
                            if (index >= FF_ARRAY_ELEMS(type30_dequant)) {
798
382
                                av_log(NULL, AV_LOG_ERROR, "index %d out of type30_dequant array\n", index);
799
382
                                return AVERROR_INVALIDDATA;
800
382
                            }
801
34.2k
                            samples[0] = type30_dequant[index];
802
34.2k
                        } else
803
179k
                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
804
805
213k
                        run = 1;
806
213k
                        break;
807
808
261k
                    case 34:
809
261k
                        if (get_bits_left(gb) >= 7) {
810
132k
                            if (type34_first) {
811
1.95k
                                type34_div = (float)(1 << get_bits(gb, 2));
812
1.95k
                                samples[0] = ((float)get_bits(gb, 5) - 16.0) / 15.0;
813
1.95k
                                type34_predictor = samples[0];
814
1.95k
                                type34_first = 0;
815
130k
                            } else {
816
130k
                                unsigned index = qdm2_get_vlc(gb, &vlc_tab_type34, 0, 1);
817
130k
                                if (index >= FF_ARRAY_ELEMS(type34_delta)) {
818
718
                                    av_log(NULL, AV_LOG_ERROR, "index %d out of type34_delta array\n", index);
819
718
                                    return AVERROR_INVALIDDATA;
820
718
                                }
821
129k
                                samples[0] = type34_delta[index] / type34_div + type34_predictor;
822
129k
                                type34_predictor = samples[0];
823
129k
                            }
824
132k
                        } else {
825
129k
                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
826
129k
                        }
827
261k
                        run = 1;
828
261k
                        break;
829
830
5.01M
                    default:
831
5.01M
                        samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
832
5.01M
                        run = 1;
833
5.01M
                        break;
834
6.07M
                }
835
836
6.07M
                if (joined_stereo) {
837
257k
                    for (k = 0; k < run && j + k < 128; k++) {
838
185k
                        q->sb_samples[0][j + k][sb] =
839
185k
                            q->tone_level[0][sb][(j + k) / 2] * samples[k];
840
185k
                        if (q->nb_channels == 2) {
841
185k
                            if (sign_bits[(j + k) / 8])
842
1.83k
                                q->sb_samples[1][j + k][sb] =
843
1.83k
                                    q->tone_level[1][sb][(j + k) / 2] * -samples[k];
844
183k
                            else
845
183k
                                q->sb_samples[1][j + k][sb] =
846
183k
                                    q->tone_level[1][sb][(j + k) / 2] * samples[k];
847
185k
                        }
848
185k
                    }
849
5.99M
                } else {
850
13.0M
                    for (k = 0; k < run; k++)
851
7.06M
                        if ((j + k) < 128)
852
7.04M
                            q->sb_samples[ch][j + k][sb] = q->tone_level[ch][sb][(j + k)/2] * samples[k];
853
5.99M
                }
854
855
6.07M
                j += run;
856
6.07M
            } // j loop
857
57.7k
        } // channel loop
858
33.5k
    } // subband loop
859
3.00k
    return 0;
860
4.57k
}
861
862
/**
863
 * Init the first element of a channel in quantized_coeffs with data
864
 * from packet 10 (quantized_coeffs[ch][0]).
865
 * This is similar to process_subpacket_9, but for a single channel
866
 * and for element [0]
867
 * same VLC tables as process_subpacket_9 are used.
868
 *
869
 * @param quantized_coeffs    pointer to quantized_coeffs[ch][0]
870
 * @param gb        bitreader context
871
 */
872
static int init_quantized_coeffs_elem0(int8_t *quantized_coeffs,
873
                                        GetBitContext *gb)
874
16.2k
{
875
16.2k
    int i, k, run, level, diff;
876
877
16.2k
    if (get_bits_left(gb) < 16)
878
2.68k
        return -1;
879
13.5k
    level = qdm2_get_vlc(gb, &vlc_tab_level, 0, 2);
880
881
13.5k
    quantized_coeffs[0] = level;
882
883
49.8k
    for (i = 0; i < 7; ) {
884
45.0k
        if (get_bits_left(gb) < 16)
885
550
            return -1;
886
44.5k
        run = qdm2_get_vlc(gb, &vlc_tab_run, 0, 1) + 1;
887
888
44.5k
        if (i + run >= 8)
889
7.75k
            return -1;
890
891
36.7k
        if (get_bits_left(gb) < 16)
892
393
            return -1;
893
36.3k
        diff = qdm2_get_se_vlc(&vlc_tab_diff, gb, 2);
894
895
94.8k
        for (k = 1; k <= run; k++)
896
58.5k
            quantized_coeffs[i + k] = (level + ((k * diff) / run));
897
898
36.3k
        level += diff;
899
36.3k
        i += run;
900
36.3k
    }
901
4.83k
    return 0;
902
13.5k
}
903
904
/**
905
 * Related to synthesis filter, process data from packet 10
906
 * Init part of quantized_coeffs via function init_quantized_coeffs_elem0
907
 * Init tone_level_idx_hi1, tone_level_idx_hi2, tone_level_idx_mid with
908
 * data from packet 10
909
 *
910
 * @param q         context
911
 * @param gb        bitreader context
912
 */
913
static void init_tone_level_dequantization(QDM2Context *q, GetBitContext *gb)
914
10.5k
{
915
10.5k
    int sb, j, k, n, ch;
916
917
23.0k
    for (ch = 0; ch < q->nb_channels; ch++) {
918
16.2k
        init_quantized_coeffs_elem0(q->quantized_coeffs[ch][0], gb);
919
920
16.2k
        if (get_bits_left(gb) < 16) {
921
3.71k
            memset(q->quantized_coeffs[ch][0], 0, 8);
922
3.71k
            break;
923
3.71k
        }
924
16.2k
    }
925
926
10.5k
    n = q->sub_sampling + 1;
927
928
37.0k
    for (sb = 0; sb < n; sb++)
929
70.0k
        for (ch = 0; ch < q->nb_channels; ch++)
930
257k
            for (j = 0; j < 8; j++) {
931
232k
                if (get_bits_left(gb) < 1)
932
18.8k
                    break;
933
214k
                if (get_bits1(gb)) {
934
632k
                    for (k=0; k < 8; k++) {
935
565k
                        if (get_bits_left(gb) < 16)
936
21.4k
                            break;
937
544k
                        q->tone_level_idx_hi1[ch][sb][j][k] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_hi1, 0, 2);
938
544k
                    }
939
126k
                } else {
940
1.13M
                    for (k=0; k < 8; k++)
941
1.00M
                        q->tone_level_idx_hi1[ch][sb][j][k] = 0;
942
126k
                }
943
214k
            }
944
945
10.5k
    n = QDM2_SB_USED(q->sub_sampling) - 4;
946
947
217k
    for (sb = 0; sb < n; sb++)
948
262k
        for (ch = 0; ch < q->nb_channels; ch++) {
949
228k
            if (get_bits_left(gb) < 16)
950
172k
                break;
951
55.9k
            q->tone_level_idx_hi2[ch][sb] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_hi2, 0, 2);
952
55.9k
            if (sb > 19)
953
5.89k
                q->tone_level_idx_hi2[ch][sb] -= 16;
954
50.0k
            else
955
450k
                for (j = 0; j < 8; j++)
956
400k
                    q->tone_level_idx_mid[ch][sb][j] = -16;
957
55.9k
        }
958
959
10.5k
    n = QDM2_SB_USED(q->sub_sampling) - 5;
960
961
206k
    for (sb = 0; sb < n; sb++)
962
518k
        for (ch = 0; ch < q->nb_channels; ch++)
963
473k
            for (j = 0; j < 8; j++) {
964
454k
                if (get_bits_left(gb) < 16)
965
303k
                    break;
966
151k
                q->tone_level_idx_mid[ch][sb][j] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_mid, 0, 2) - 32;
967
151k
            }
968
10.5k
}
969
970
/**
971
 * Process subpacket 9, init quantized_coeffs with data from it
972
 *
973
 * @param q       context
974
 * @param node    pointer to node with packet
975
 */
976
static int process_subpacket_9(QDM2Context *q, QDM2SubPNode *node)
977
11.2k
{
978
11.2k
    GetBitContext gb;
979
11.2k
    int i, j, k, n, ch, run, level, diff;
980
981
11.2k
    init_get_bits(&gb, node->packet->data, node->packet->size * 8);
982
983
11.2k
    n = coeff_per_sb_for_avg[q->coeff_per_sb_select][QDM2_SB_USED(q->sub_sampling) - 1] + 1;
984
985
39.2k
    for (i = 1; i < n; i++)
986
74.4k
        for (ch = 0; ch < q->nb_channels; ch++) {
987
46.4k
            level = qdm2_get_vlc(&gb, &vlc_tab_level, 0, 2);
988
46.4k
            q->quantized_coeffs[ch][i][0] = level;
989
990
323k
            for (j = 0; j < (8 - 1); ) {
991
284k
                run  = qdm2_get_vlc(&gb, &vlc_tab_run, 0, 1) + 1;
992
284k
                diff = qdm2_get_se_vlc(&vlc_tab_diff, &gb, 2);
993
994
284k
                if (j + run >= 8)
995
7.29k
                    return -1;
996
997
564k
                for (k = 1; k <= run; k++)
998
287k
                    q->quantized_coeffs[ch][i][j + k] = (level + ((k * diff) / run));
999
1000
276k
                level += diff;
1001
276k
                j     += run;
1002
276k
            }
1003
46.4k
        }
1004
1005
9.24k
    for (ch = 0; ch < q->nb_channels; ch++)
1006
47.6k
        for (i = 0; i < 8; i++)
1007
42.3k
            q->quantized_coeffs[ch][0][i] = 0;
1008
1009
3.94k
    return 0;
1010
11.2k
}
1011
1012
/**
1013
 * Process subpacket 10 if not null, else
1014
 *
1015
 * @param q         context
1016
 * @param node      pointer to node with packet
1017
 */
1018
static void process_subpacket_10(QDM2Context *q, QDM2SubPNode *node)
1019
67.0k
{
1020
67.0k
    GetBitContext gb;
1021
1022
67.0k
    if (node) {
1023
10.5k
        init_get_bits(&gb, node->packet->data, node->packet->size * 8);
1024
10.5k
        init_tone_level_dequantization(q, &gb);
1025
10.5k
        fill_tone_level_array(q, 1);
1026
56.5k
    } else {
1027
56.5k
        fill_tone_level_array(q, 0);
1028
56.5k
    }
1029
67.0k
}
1030
1031
/**
1032
 * Process subpacket 11
1033
 *
1034
 * @param q         context
1035
 * @param node      pointer to node with packet
1036
 */
1037
static void process_subpacket_11(QDM2Context *q, QDM2SubPNode *node)
1038
67.0k
{
1039
67.0k
    GetBitContext gb;
1040
67.0k
    int length = 0;
1041
1042
67.0k
    if (node) {
1043
2.43k
        length = node->packet->size * 8;
1044
2.43k
        init_get_bits(&gb, node->packet->data, length);
1045
2.43k
    }
1046
1047
67.0k
    if (length >= 32) {
1048
2.19k
        int c = get_bits(&gb, 13);
1049
1050
2.19k
        if (c > 3)
1051
1.81k
            fill_coding_method_array(q->tone_level_idx,
1052
1.81k
                                     q->tone_level_idx_temp, q->coding_method,
1053
1.81k
                                     q->nb_channels, 8 * c,
1054
1.81k
                                     q->superblocktype_2_3, q->cm_table_select);
1055
2.19k
    }
1056
1057
67.0k
    synthfilt_build_sb_samples(q, &gb, length, 0, 8);
1058
67.0k
}
1059
1060
/**
1061
 * Process subpacket 12
1062
 *
1063
 * @param q         context
1064
 * @param node      pointer to node with packet
1065
 */
1066
static void process_subpacket_12(QDM2Context *q, QDM2SubPNode *node)
1067
67.0k
{
1068
67.0k
    GetBitContext gb;
1069
67.0k
    int length = 0;
1070
1071
67.0k
    if (node) {
1072
2.33k
        length = node->packet->size * 8;
1073
2.33k
        init_get_bits(&gb, node->packet->data, length);
1074
2.33k
    }
1075
1076
67.0k
    synthfilt_build_sb_samples(q, &gb, length, 8, QDM2_SB_USED(q->sub_sampling));
1077
67.0k
}
1078
1079
/**
1080
 * Process new subpackets for synthesis filter
1081
 *
1082
 * @param q       context
1083
 * @param list    list with synthesis filter packets (list D)
1084
 */
1085
static void process_synthesis_subpackets(QDM2Context *q, QDM2SubPNode *list)
1086
17.1k
{
1087
17.1k
    QDM2SubPNode *nodes[4];
1088
1089
17.1k
    nodes[0] = qdm2_search_subpacket_type_in_list(list, 9);
1090
17.1k
    if (nodes[0])
1091
11.2k
        process_subpacket_9(q, nodes[0]);
1092
1093
17.1k
    nodes[1] = qdm2_search_subpacket_type_in_list(list, 10);
1094
17.1k
    if (nodes[1])
1095
10.5k
        process_subpacket_10(q, nodes[1]);
1096
6.60k
    else
1097
6.60k
        process_subpacket_10(q, NULL);
1098
1099
17.1k
    nodes[2] = qdm2_search_subpacket_type_in_list(list, 11);
1100
17.1k
    if (nodes[0] && nodes[1] && nodes[2])
1101
2.43k
        process_subpacket_11(q, nodes[2]);
1102
14.6k
    else
1103
14.6k
        process_subpacket_11(q, NULL);
1104
1105
17.1k
    nodes[3] = qdm2_search_subpacket_type_in_list(list, 12);
1106
17.1k
    if (nodes[0] && nodes[1] && nodes[3])
1107
2.33k
        process_subpacket_12(q, nodes[3]);
1108
14.7k
    else
1109
14.7k
        process_subpacket_12(q, NULL);
1110
17.1k
}
1111
1112
/**
1113
 * Decode superblock, fill packet lists.
1114
 *
1115
 * @param q    context
1116
 */
1117
static void qdm2_decode_super_block(QDM2Context *q)
1118
721k
{
1119
721k
    GetBitContext gb;
1120
721k
    QDM2SubPacket header, *packet;
1121
721k
    int i, packet_bytes, sub_packet_size, sub_packets_D;
1122
721k
    unsigned int next_index = 0;
1123
1124
721k
    memset(q->tone_level_idx_hi1, 0, sizeof(q->tone_level_idx_hi1));
1125
721k
    memset(q->tone_level_idx_mid, 0, sizeof(q->tone_level_idx_mid));
1126
721k
    memset(q->tone_level_idx_hi2, 0, sizeof(q->tone_level_idx_hi2));
1127
1128
721k
    q->sub_packets_B = 0;
1129
721k
    sub_packets_D    = 0;
1130
1131
721k
    average_quantized_coeffs(q); // average elements in quantized_coeffs[max_ch][10][8]
1132
1133
721k
    init_get_bits(&gb, q->compressed_data, q->compressed_size * 8);
1134
721k
    qdm2_decode_sub_packet_header(&gb, &header);
1135
1136
721k
    if (header.type < 2 || header.type >= 8) {
1137
611k
        q->has_errors = 1;
1138
611k
        av_log(NULL, AV_LOG_ERROR, "bad superblock type\n");
1139
611k
        return;
1140
611k
    }
1141
1142
110k
    q->superblocktype_2_3 = (header.type == 2 || header.type == 3);
1143
110k
    packet_bytes          = (q->compressed_size - get_bits_count(&gb) / 8);
1144
1145
110k
    init_get_bits(&gb, header.data, header.size * 8);
1146
1147
110k
    if (header.type == 2 || header.type == 4 || header.type == 5) {
1148
11.8k
        int csum = 257 * get_bits(&gb, 8);
1149
11.8k
        csum += 2 * get_bits(&gb, 8);
1150
1151
11.8k
        csum = qdm2_packet_checksum(q->compressed_data, q->checksum_size, csum);
1152
1153
11.8k
        if (csum != 0) {
1154
11.4k
            q->has_errors = 1;
1155
11.4k
            av_log(NULL, AV_LOG_ERROR, "bad packet checksum\n");
1156
11.4k
            return;
1157
11.4k
        }
1158
11.8k
    }
1159
1160
99.0k
    q->sub_packet_list_B[0].packet = NULL;
1161
99.0k
    q->sub_packet_list_D[0].packet = NULL;
1162
1163
693k
    for (i = 0; i < 6; i++)
1164
594k
        if (--q->fft_level_exp[i] < 0)
1165
571k
            q->fft_level_exp[i] = 0;
1166
1167
171k
    for (i = 0; packet_bytes > 0; i++) {
1168
148k
        int j;
1169
1170
148k
        if (i >= FF_ARRAY_ELEMS(q->sub_packet_list_A)) {
1171
262
            SAMPLES_NEEDED_2("too many packet bytes");
1172
262
            return;
1173
262
        }
1174
1175
147k
        q->sub_packet_list_A[i].next = NULL;
1176
1177
147k
        if (i > 0) {
1178
60.2k
            q->sub_packet_list_A[i - 1].next = &q->sub_packet_list_A[i];
1179
1180
            /* seek to next block */
1181
60.2k
            init_get_bits(&gb, header.data, header.size * 8);
1182
60.2k
            skip_bits(&gb, next_index * 8);
1183
1184
60.2k
            if (next_index >= header.size)
1185
14.1k
                break;
1186
60.2k
        }
1187
1188
        /* decode subpacket */
1189
133k
        packet = &q->sub_packets[i];
1190
133k
        qdm2_decode_sub_packet_header(&gb, packet);
1191
133k
        next_index      = packet->size + get_bits_count(&gb) / 8;
1192
133k
        sub_packet_size = ((packet->size > 0xff) ? 1 : 0) + packet->size + 2;
1193
1194
133k
        if (packet->type == 0)
1195
4.02k
            break;
1196
1197
129k
        if (sub_packet_size > packet_bytes) {
1198
66.5k
            if (packet->type != 10 && packet->type != 11 && packet->type != 12)
1199
56.9k
                break;
1200
9.55k
            packet->size += packet_bytes - sub_packet_size;
1201
9.55k
        }
1202
1203
72.7k
        packet_bytes -= sub_packet_size;
1204
1205
        /* add subpacket to 'all subpackets' list */
1206
72.7k
        q->sub_packet_list_A[i].packet = packet;
1207
1208
        /* add subpacket to related list */
1209
72.7k
        if (packet->type == 8) {
1210
414
            SAMPLES_NEEDED_2("packet type 8");
1211
414
            return;
1212
72.3k
        } else if (packet->type >= 9 && packet->type <= 12) {
1213
            /* packets for MPEG Audio like Synthesis Filter */
1214
28.1k
            QDM2_LIST_ADD(q->sub_packet_list_D, sub_packets_D, packet);
1215
44.1k
        } else if (packet->type == 13) {
1216
6.74k
            for (j = 0; j < 6; j++)
1217
5.77k
                q->fft_level_exp[j] = get_bits(&gb, 6);
1218
43.1k
        } else if (packet->type == 14) {
1219
24.5k
            for (j = 0; j < 6; j++)
1220
21.0k
                q->fft_level_exp[j] = qdm2_get_vlc(&gb, &fft_level_exp_vlc, 0, 2);
1221
39.6k
        } else if (packet->type == 15) {
1222
202
            SAMPLES_NEEDED_2("packet type 15")
1223
202
            return;
1224
39.4k
        } else if (packet->type >= 16 && packet->type < 48 &&
1225
39.4k
                   !fft_subpackets[packet->type - 16]) {
1226
            /* packets for FFT */
1227
18.8k
            QDM2_LIST_ADD(q->sub_packet_list_B, q->sub_packets_B, packet);
1228
18.8k
        }
1229
72.7k
    } // Packet bytes loop
1230
1231
98.2k
    if (q->sub_packet_list_D[0].packet) {
1232
17.1k
        process_synthesis_subpackets(q, q->sub_packet_list_D);
1233
17.1k
        q->do_synth_filter = 1;
1234
81.1k
    } else if (q->do_synth_filter) {
1235
49.9k
        process_subpacket_10(q, NULL);
1236
49.9k
        process_subpacket_11(q, NULL);
1237
49.9k
        process_subpacket_12(q, NULL);
1238
49.9k
    }
1239
98.2k
}
1240
1241
static void qdm2_fft_init_coefficient(QDM2Context *q, int sub_packet,
1242
                                      int offset, int duration, int channel,
1243
                                      int exp, int phase)
1244
302k
{
1245
302k
    if (q->fft_coefs_min_index[duration] < 0)
1246
12.9k
        q->fft_coefs_min_index[duration] = q->fft_coefs_index;
1247
1248
302k
    q->fft_coefs[q->fft_coefs_index].sub_packet =
1249
302k
        ((sub_packet >= 16) ? (sub_packet - 16) : sub_packet);
1250
302k
    q->fft_coefs[q->fft_coefs_index].channel = channel;
1251
302k
    q->fft_coefs[q->fft_coefs_index].offset  = offset;
1252
302k
    q->fft_coefs[q->fft_coefs_index].exp     = exp;
1253
302k
    q->fft_coefs[q->fft_coefs_index].phase   = phase;
1254
302k
    q->fft_coefs_index++;
1255
302k
}
1256
1257
static void qdm2_fft_decode_tones(QDM2Context *q, int duration,
1258
                                  GetBitContext *gb, int b)
1259
32.7k
{
1260
32.7k
    int channel, stereo, phase, exp;
1261
32.7k
    int local_int_4, local_int_8, stereo_phase, local_int_10;
1262
32.7k
    int local_int_14, stereo_exp, local_int_20, local_int_28;
1263
32.7k
    int n, offset;
1264
1265
32.7k
    local_int_4  = 0;
1266
32.7k
    local_int_28 = 0;
1267
32.7k
    local_int_20 = 2;
1268
32.7k
    local_int_8  = (4 - duration);
1269
32.7k
    local_int_10 = 1 << (q->group_order - duration - 1);
1270
32.7k
    offset       = 1;
1271
1272
244k
    while (get_bits_left(gb)>0) {
1273
218k
        if (q->superblocktype_2_3) {
1274
1.13M
            while ((n = qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2)) < 2) {
1275
933k
                if (get_bits_left(gb)<0) {
1276
551
                    if(local_int_4 < q->group_size)
1277
302
                        av_log(NULL, AV_LOG_ERROR, "overread in qdm2_fft_decode_tones()\n");
1278
551
                    return;
1279
551
                }
1280
933k
                offset = 1;
1281
933k
                if (n == 0) {
1282
931k
                    local_int_4  += local_int_10;
1283
931k
                    local_int_28 += (1 << local_int_8);
1284
931k
                } else {
1285
1.78k
                    local_int_4  += 8 * local_int_10;
1286
1.78k
                    local_int_28 += (8 << local_int_8);
1287
1.78k
                }
1288
933k
            }
1289
204k
            offset += (n - 2);
1290
204k
        } else {
1291
13.6k
            if (local_int_10 <= 2) {
1292
451
                av_log(NULL, AV_LOG_ERROR, "qdm2_fft_decode_tones() stuck\n");
1293
451
                return;
1294
451
            }
1295
13.2k
            offset += qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2);
1296
59.2k
            while (offset >= (local_int_10 - 1)) {
1297
46.0k
                offset       += (1 - (local_int_10 - 1));
1298
46.0k
                local_int_4  += local_int_10;
1299
46.0k
                local_int_28 += (1 << local_int_8);
1300
46.0k
            }
1301
13.2k
        }
1302
1303
217k
        if (local_int_4 >= q->group_size)
1304
5.46k
            return;
1305
1306
211k
        local_int_14 = (offset >> local_int_8);
1307
211k
        if (local_int_14 >= FF_ARRAY_ELEMS(fft_level_index_table))
1308
280
            return;
1309
1310
211k
        if (q->nb_channels > 1) {
1311
149k
            channel = get_bits1(gb);
1312
149k
            stereo  = get_bits1(gb);
1313
149k
        } else {
1314
62.2k
            channel = 0;
1315
62.2k
            stereo  = 0;
1316
62.2k
        }
1317
1318
211k
        exp  = qdm2_get_vlc(gb, (b ? &fft_level_exp_vlc : &fft_level_exp_alt_vlc), 0, 2);
1319
211k
        exp += q->fft_level_exp[fft_level_index_table[local_int_14]];
1320
211k
        exp  = (exp < 0) ? 0 : exp;
1321
1322
211k
        phase        = get_bits(gb, 3);
1323
211k
        stereo_exp   = 0;
1324
211k
        stereo_phase = 0;
1325
1326
211k
        if (stereo) {
1327
112k
            stereo_exp   = (exp - qdm2_get_vlc(gb, &fft_stereo_exp_vlc, 0, 1));
1328
112k
            stereo_phase = (phase - qdm2_get_vlc(gb, &fft_stereo_phase_vlc, 0, 1));
1329
112k
            if (stereo_phase < 0)
1330
51.0k
                stereo_phase += 8;
1331
112k
        }
1332
1333
211k
        if (q->frequency_range > (local_int_14 + 1)) {
1334
198k
            int sub_packet = (local_int_20 + local_int_28);
1335
1336
198k
            if (q->fft_coefs_index + stereo >= FF_ARRAY_ELEMS(q->fft_coefs))
1337
196
                return;
1338
1339
197k
            qdm2_fft_init_coefficient(q, sub_packet, offset, duration,
1340
197k
                                      channel, exp, phase);
1341
197k
            if (stereo)
1342
105k
                qdm2_fft_init_coefficient(q, sub_packet, offset, duration,
1343
105k
                                          1 - channel,
1344
105k
                                          stereo_exp, stereo_phase);
1345
197k
        }
1346
211k
        offset++;
1347
211k
    }
1348
32.7k
}
1349
1350
static void qdm2_decode_fft_packets(QDM2Context *q)
1351
99.0k
{
1352
99.0k
    int i, j, min, max, value, type, unknown_flag;
1353
99.0k
    GetBitContext gb;
1354
1355
99.0k
    if (!q->sub_packet_list_B[0].packet)
1356
87.4k
        return;
1357
1358
    /* reset minimum indexes for FFT coefficients */
1359
11.6k
    q->fft_coefs_index = 0;
1360
69.6k
    for (i = 0; i < 5; i++)
1361
58.0k
        q->fft_coefs_min_index[i] = -1;
1362
1363
    /* process subpackets ordered by type, largest type first */
1364
29.8k
    for (i = 0, max = 256; i < q->sub_packets_B; i++) {
1365
18.7k
        QDM2SubPacket *packet = NULL;
1366
1367
        /* find subpacket with largest type less than max */
1368
59.8k
        for (j = 0, min = 0; j < q->sub_packets_B; j++) {
1369
41.1k
            value = q->sub_packet_list_B[j].packet->type;
1370
41.1k
            if (value > min && value < max) {
1371
22.2k
                min    = value;
1372
22.2k
                packet = q->sub_packet_list_B[j].packet;
1373
22.2k
            }
1374
41.1k
        }
1375
1376
18.7k
        max = min;
1377
1378
        /* check for errors (?) */
1379
18.7k
        if (!packet)
1380
522
            return;
1381
1382
18.2k
        if (i == 0 &&
1383
18.2k
            (packet->type < 16 || packet->type >= 48 ||
1384
11.6k
             fft_subpackets[packet->type - 16]))
1385
0
            return;
1386
1387
        /* decode FFT tones */
1388
18.2k
        init_get_bits(&gb, packet->data, packet->size * 8);
1389
1390
18.2k
        if (packet->type >= 32 && packet->type < 48 && !fft_subpackets[packet->type - 16])
1391
6.36k
            unknown_flag = 1;
1392
11.8k
        else
1393
11.8k
            unknown_flag = 0;
1394
1395
18.2k
        type = packet->type;
1396
1397
18.2k
        if ((type >= 17 && type < 24) || (type >= 33 && type < 40)) {
1398
10.4k
            int duration = q->sub_sampling + 5 - (type & 15);
1399
1400
10.4k
            if (duration >= 0 && duration < 4)
1401
9.46k
                qdm2_fft_decode_tones(q, duration, &gb, unknown_flag);
1402
10.4k
        } else if (type == 31) {
1403
16.2k
            for (j = 0; j < 4; j++)
1404
12.9k
                qdm2_fft_decode_tones(q, j, &gb, unknown_flag);
1405
4.54k
        } else if (type == 46) {
1406
17.9k
            for (j = 0; j < 6; j++)
1407
15.4k
                q->fft_level_exp[j] = get_bits(&gb, 6);
1408
12.8k
            for (j = 0; j < 4; j++)
1409
10.2k
                qdm2_fft_decode_tones(q, j, &gb, unknown_flag);
1410
2.57k
        }
1411
18.2k
    } // Loop on B packets
1412
1413
    /* calculate maximum indexes for FFT coefficients */
1414
66.4k
    for (i = 0, j = -1; i < 5; i++)
1415
55.4k
        if (q->fft_coefs_min_index[i] >= 0) {
1416
12.2k
            if (j >= 0)
1417
3.80k
                q->fft_coefs_max_index[j] = q->fft_coefs_min_index[i];
1418
12.2k
            j = i;
1419
12.2k
        }
1420
11.0k
    if (j >= 0)
1421
8.48k
        q->fft_coefs_max_index[j] = q->fft_coefs_index;
1422
11.0k
}
1423
1424
static void qdm2_fft_generate_tone(QDM2Context *q, FFTTone *tone)
1425
4.36M
{
1426
4.36M
    float level, f[6];
1427
4.36M
    int i;
1428
4.36M
    AVComplexFloat c;
1429
4.36M
    const double iscale = 2.0 * M_PI / 512.0;
1430
1431
4.36M
    tone->phase += tone->phase_shift;
1432
1433
    /* calculate current level (maximum amplitude) of tone */
1434
4.36M
    level = fft_tone_envelope_table[tone->duration][tone->time_index] * tone->level;
1435
4.36M
    c.im  = level * sin(tone->phase * iscale);
1436
4.36M
    c.re  = level * cos(tone->phase * iscale);
1437
1438
    /* generate FFT coefficients for tone */
1439
4.36M
    if (tone->duration >= 3 || tone->cutoff >= 3) {
1440
1.13M
        tone->complex[0].im += c.im;
1441
1.13M
        tone->complex[0].re += c.re;
1442
1.13M
        tone->complex[1].im -= c.im;
1443
1.13M
        tone->complex[1].re -= c.re;
1444
3.23M
    } else {
1445
3.23M
        f[1] = -tone->table[4];
1446
3.23M
        f[0] = tone->table[3] - tone->table[0];
1447
3.23M
        f[2] = 1.0 - tone->table[2] - tone->table[3];
1448
3.23M
        f[3] = tone->table[1] + tone->table[4] - 1.0;
1449
3.23M
        f[4] = tone->table[0] - tone->table[1];
1450
3.23M
        f[5] = tone->table[2];
1451
9.70M
        for (i = 0; i < 2; i++) {
1452
6.46M
            tone->complex[fft_cutoff_index_table[tone->cutoff][i]].re +=
1453
6.46M
                c.re * f[i];
1454
6.46M
            tone->complex[fft_cutoff_index_table[tone->cutoff][i]].im +=
1455
6.46M
                c.im * ((tone->cutoff <= i) ? -f[i] : f[i]);
1456
6.46M
        }
1457
16.1M
        for (i = 0; i < 4; i++) {
1458
12.9M
            tone->complex[i].re += c.re * f[i + 2];
1459
12.9M
            tone->complex[i].im += c.im * f[i + 2];
1460
12.9M
        }
1461
3.23M
    }
1462
1463
    /* copy the tone if it has not yet died out */
1464
4.36M
    if (++tone->time_index < ((1 << (5 - tone->duration)) - 1)) {
1465
4.21M
        memcpy(&q->fft_tones[q->fft_tone_end], tone, sizeof(FFTTone));
1466
4.21M
        q->fft_tone_end = (q->fft_tone_end + 1) % 1000;
1467
4.21M
    }
1468
4.36M
}
1469
1470
static void qdm2_fft_tone_synthesizer(QDM2Context *q, int sub_packet)
1471
1.58M
{
1472
1.58M
    int i, j, ch;
1473
1.58M
    const double iscale = 0.25 * M_PI;
1474
1475
3.96M
    for (ch = 0; ch < q->channels; ch++) {
1476
2.37M
        memset(q->fft.complex[ch], 0, q->fft_size * sizeof(AVComplexFloat));
1477
2.37M
    }
1478
1479
1480
    /* apply FFT tones with duration 4 (1 FFT period) */
1481
1.58M
    if (q->fft_coefs_min_index[4] >= 0)
1482
1.11M
        for (i = q->fft_coefs_min_index[4]; i < q->fft_coefs_max_index[4]; i++) {
1483
0
            float level;
1484
0
            AVComplexFloat c;
1485
1486
0
            if (q->fft_coefs[i].sub_packet != sub_packet)
1487
0
                break;
1488
1489
0
            ch = (q->channels == 1) ? 0 : q->fft_coefs[i].channel;
1490
0
            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];
1491
1492
0
            c.re = level * cos(q->fft_coefs[i].phase * iscale);
1493
0
            c.im = level * sin(q->fft_coefs[i].phase * iscale);
1494
0
            q->fft.complex[ch][q->fft_coefs[i].offset + 0].re += c.re;
1495
0
            q->fft.complex[ch][q->fft_coefs[i].offset + 0].im += c.im;
1496
0
            q->fft.complex[ch][q->fft_coefs[i].offset + 1].re -= c.re;
1497
0
            q->fft.complex[ch][q->fft_coefs[i].offset + 1].im -= c.im;
1498
0
        }
1499
1500
    /* generate existing FFT tones */
1501
5.66M
    for (i = q->fft_tone_end; i != q->fft_tone_start; ) {
1502
4.08M
        qdm2_fft_generate_tone(q, &q->fft_tones[q->fft_tone_start]);
1503
4.08M
        q->fft_tone_start = (q->fft_tone_start + 1) % 1000;
1504
4.08M
    }
1505
1506
    /* create and generate new FFT tones with duration 0 (long) to 3 (short) */
1507
7.92M
    for (i = 0; i < 4; i++)
1508
6.34M
        if (q->fft_coefs_min_index[i] >= 0) {
1509
5.06M
            for (j = q->fft_coefs_min_index[i]; j < q->fft_coefs_max_index[i]; j++) {
1510
345k
                int offset, four_i;
1511
345k
                FFTTone tone;
1512
1513
345k
                if (q->fft_coefs[j].sub_packet != sub_packet)
1514
58.6k
                    break;
1515
1516
286k
                four_i = (4 - i);
1517
286k
                offset = q->fft_coefs[j].offset >> four_i;
1518
286k
                ch = (q->channels == 1) ? 0 : q->fft_coefs[j].channel;
1519
1520
286k
                if (offset < q->frequency_range) {
1521
285k
                    if (offset < 2)
1522
22.2k
                        tone.cutoff = offset;
1523
263k
                    else
1524
263k
                        tone.cutoff = (offset >= 60) ? 3 : 2;
1525
1526
285k
                    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];
1527
285k
                    tone.complex = &q->fft.complex[ch][offset];
1528
285k
                    tone.table = fft_tone_sample_table[i][q->fft_coefs[j].offset - (offset << four_i)];
1529
285k
                    tone.phase = 64 * q->fft_coefs[j].phase - (offset << 8) - 128;
1530
285k
                    tone.phase_shift = (2 * q->fft_coefs[j].offset + 1) << (7 - four_i);
1531
285k
                    tone.duration = i;
1532
285k
                    tone.time_index = 0;
1533
1534
285k
                    qdm2_fft_generate_tone(q, &tone);
1535
285k
                }
1536
286k
            }
1537
4.77M
            q->fft_coefs_min_index[i] = j;
1538
4.77M
        }
1539
1.58M
}
1540
1541
static void qdm2_calculate_fft(QDM2Context *q, int channel, int sub_packet)
1542
13.8M
{
1543
13.8M
    const float gain = (q->channels == 1 && q->nb_channels == 2) ? 0.5f : 1.0f;
1544
13.8M
    float *out       = q->output_buffer + channel;
1545
1546
13.8M
    q->fft.complex[channel][0].re *= 2.0f;
1547
13.8M
    q->fft.complex[channel][0].im  = 0.0f;
1548
13.8M
    q->fft.complex[channel][q->fft_size].re = 0.0f;
1549
13.8M
    q->fft.complex[channel][q->fft_size].im = 0.0f;
1550
1551
13.8M
    q->rdft_fn(q->rdft_ctx, q->fft.temp[channel], q->fft.complex[channel],
1552
13.8M
               sizeof(AVComplexFloat));
1553
1554
    /* add samples to output buffer */
1555
2.01G
    for (int i = 0; i < FFALIGN(q->fft_size, 8); i++) {
1556
1.99G
        out[0]           += q->fft.temp[channel][i].re * gain;
1557
1.99G
        out[q->channels] += q->fft.temp[channel][i].im * gain;
1558
1.99G
        out              += 2 * q->channels;
1559
1.99G
    }
1560
13.8M
}
1561
1562
/**
1563
 * @param q        context
1564
 * @param index    subpacket number
1565
 */
1566
static void qdm2_synthesis_filter(QDM2Context *q, int index)
1567
1.08M
{
1568
1.08M
    int i, k, ch, sb_used, sub_sampling, dither_state = 0;
1569
1570
    /* copy sb_samples */
1571
1.08M
    sb_used = QDM2_SB_USED(q->sub_sampling);
1572
1573
2.71M
    for (ch = 0; ch < q->channels; ch++)
1574
14.7M
        for (i = 0; i < 8; i++)
1575
175M
            for (k = sb_used; k < SBLIMIT; k++)
1576
162M
                q->sb_samples[ch][(8 * index) + i][k] = 0;
1577
1578
2.71M
    for (ch = 0; ch < q->nb_channels; ch++) {
1579
1.63M
        float *samples_ptr = q->samples + ch;
1580
1581
14.7M
        for (i = 0; i < 8; i++) {
1582
13.0M
            ff_mpa_synth_filter_float(&q->mpadsp,
1583
13.0M
                                      q->synth_buf[ch], &(q->synth_buf_offset[ch]),
1584
13.0M
                                      ff_mpa_synth_window_float, &dither_state,
1585
13.0M
                                      samples_ptr, q->nb_channels,
1586
13.0M
                                      q->sb_samples[ch][(8 * index) + i]);
1587
13.0M
            samples_ptr += 32 * q->nb_channels;
1588
13.0M
        }
1589
1.63M
    }
1590
1591
    /* add samples to output buffer */
1592
1.08M
    sub_sampling = (4 >> q->sub_sampling);
1593
1594
2.71M
    for (ch = 0; ch < q->channels; ch++)
1595
106M
        for (i = 0; i < q->frame_size; i++)
1596
104M
            q->output_buffer[q->channels * i + ch] += (1 << 23) * q->samples[q->nb_channels * sub_sampling * i + ch];
1597
1.08M
}
1598
1599
/**
1600
 * Init static data (does not depend on specific file)
1601
 */
1602
1
static av_cold void qdm2_init_static_data(void) {
1603
1
    qdm2_init_vlc();
1604
1
    softclip_table_init();
1605
1
    rnd_table_init();
1606
1
    init_noise_samples();
1607
1608
1
    ff_mpa_synth_init_float();
1609
1
}
1610
1611
/**
1612
 * Init parameters from codec extradata
1613
 */
1614
static av_cold int qdm2_decode_init(AVCodecContext *avctx)
1615
1.99k
{
1616
1.99k
    static AVOnce init_static_once = AV_ONCE_INIT;
1617
1.99k
    QDM2Context *s = avctx->priv_data;
1618
1.99k
    int ret, tmp_val, tmp, size;
1619
1.99k
    float scale = 1.0f / 2.0f;
1620
1.99k
    GetByteContext gb;
1621
1622
    /* extradata parsing
1623
1624
    Structure:
1625
    wave {
1626
        frma (QDM2)
1627
        QDCA
1628
        QDCP
1629
    }
1630
1631
    32  size (including this field)
1632
    32  tag (=frma)
1633
    32  type (=QDM2 or QDMC)
1634
1635
    32  size (including this field, in bytes)
1636
    32  tag (=QDCA) // maybe mandatory parameters
1637
    32  unknown (=1)
1638
    32  channels (=2)
1639
    32  samplerate (=44100)
1640
    32  bitrate (=96000)
1641
    32  block size (=4096)
1642
    32  frame size (=256) (for one channel)
1643
    32  packet size (=1300)
1644
1645
    32  size (including this field, in bytes)
1646
    32  tag (=QDCP) // maybe some tuneable parameters
1647
    32  float1 (=1.0)
1648
    32  zero ?
1649
    32  float2 (=1.0)
1650
    32  float3 (=1.0)
1651
    32  unknown (27)
1652
    32  unknown (8)
1653
    32  zero ?
1654
    */
1655
1656
1.99k
    if (!avctx->extradata || (avctx->extradata_size < 48)) {
1657
213
        av_log(avctx, AV_LOG_ERROR, "extradata missing or truncated\n");
1658
213
        return AVERROR_INVALIDDATA;
1659
213
    }
1660
1661
1.77k
    bytestream2_init(&gb, avctx->extradata, avctx->extradata_size);
1662
1663
1.79M
    while (bytestream2_get_bytes_left(&gb) > 8) {
1664
1.79M
        if (bytestream2_peek_be64(&gb) == (((uint64_t)MKBETAG('f','r','m','a') << 32) |
1665
1.79M
                                            (uint64_t)MKBETAG('Q','D','M','2')))
1666
1.71k
            break;
1667
1.78M
        bytestream2_skip(&gb, 1);
1668
1.78M
    }
1669
1670
1.77k
    if (bytestream2_get_bytes_left(&gb) < 12) {
1671
64
        av_log(avctx, AV_LOG_ERROR, "not enough extradata (%i)\n",
1672
64
               bytestream2_get_bytes_left(&gb));
1673
64
        return AVERROR_INVALIDDATA;
1674
64
    }
1675
1676
1.71k
    bytestream2_skip(&gb, 8);
1677
1.71k
    size = bytestream2_get_be32(&gb);
1678
1679
1.71k
    if (size > bytestream2_get_bytes_left(&gb)) {
1680
32
        av_log(avctx, AV_LOG_ERROR, "extradata size too small, %i < %i\n",
1681
32
               bytestream2_get_bytes_left(&gb), size);
1682
32
        return AVERROR_INVALIDDATA;
1683
32
    }
1684
1685
1.68k
    av_log(avctx, AV_LOG_DEBUG, "size: %d\n", size);
1686
1.68k
    if (bytestream2_get_be32(&gb) != MKBETAG('Q','D','C','A')) {
1687
52
        av_log(avctx, AV_LOG_ERROR, "invalid extradata, expecting QDCA\n");
1688
52
        return AVERROR_INVALIDDATA;
1689
52
    }
1690
1691
1.63k
    bytestream2_skip(&gb, 4);
1692
1693
1.63k
    s->nb_channels = s->channels = bytestream2_get_be32(&gb);
1694
1.63k
    if (s->channels <= 0 || s->channels > MPA_MAX_CHANNELS) {
1695
43
        av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
1696
43
        return AVERROR_INVALIDDATA;
1697
43
    }
1698
1.58k
    av_channel_layout_uninit(&avctx->ch_layout);
1699
1.58k
    av_channel_layout_default(&avctx->ch_layout, s->channels);
1700
1701
1.58k
    avctx->sample_rate = bytestream2_get_be32(&gb);
1702
1.58k
    avctx->bit_rate = bytestream2_get_be32(&gb);
1703
1.58k
    s->group_size = bytestream2_get_be32(&gb);
1704
1.58k
    s->fft_size = bytestream2_get_be32(&gb);
1705
1.58k
    s->checksum_size = bytestream2_get_be32(&gb);
1706
1.58k
    if (s->checksum_size >= 1U << 28 || s->checksum_size <= 1) {
1707
16
        av_log(avctx, AV_LOG_ERROR, "data block size invalid (%u)\n", s->checksum_size);
1708
16
        return AVERROR_INVALIDDATA;
1709
16
    }
1710
1711
1.57k
    s->fft_order = av_log2(s->fft_size) + 1;
1712
1713
    // Fail on unknown fft order
1714
1.57k
    if ((s->fft_order < 7) || (s->fft_order > 9)) {
1715
54
        avpriv_request_sample(avctx, "Unknown FFT order %d", s->fft_order);
1716
54
        return AVERROR_PATCHWELCOME;
1717
54
    }
1718
1719
    // something like max decodable tones
1720
1.51k
    s->group_order = av_log2(s->group_size) + 1;
1721
1.51k
    s->frame_size = s->group_size / 16; // 16 iterations per super block
1722
1723
1.51k
    if (s->frame_size > QDM2_MAX_FRAME_SIZE)
1724
3
        return AVERROR_INVALIDDATA;
1725
1726
1.51k
    s->sub_sampling = s->fft_order - 7;
1727
1.51k
    s->frequency_range = 255 / (1 << (2 - s->sub_sampling));
1728
1729
1.51k
    if (s->frame_size * 4 >> s->sub_sampling > MPA_FRAME_SIZE) {
1730
1
        avpriv_request_sample(avctx, "large frames");
1731
1
        return AVERROR_PATCHWELCOME;
1732
1
    }
1733
1734
1.51k
    switch ((s->sub_sampling * 2 + s->channels - 1)) {
1735
68
        case 0: tmp = 40; break;
1736
46
        case 1: tmp = 48; break;
1737
373
        case 2: tmp = 56; break;
1738
496
        case 3: tmp = 72; break;
1739
232
        case 4: tmp = 80; break;
1740
298
        case 5: tmp = 100;break;
1741
0
        default: tmp=s->sub_sampling; break;
1742
1.51k
    }
1743
1.51k
    tmp_val = 0;
1744
1.51k
    if ((tmp * 1000) < avctx->bit_rate)  tmp_val = 1;
1745
1.51k
    if ((tmp * 1440) < avctx->bit_rate)  tmp_val = 2;
1746
1.51k
    if ((tmp * 1760) < avctx->bit_rate)  tmp_val = 3;
1747
1.51k
    if ((tmp * 2240) < avctx->bit_rate)  tmp_val = 4;
1748
1.51k
    s->cm_table_select = tmp_val;
1749
1750
1.51k
    if (avctx->bit_rate <= 8000)
1751
343
        s->coeff_per_sb_select = 0;
1752
1.17k
    else if (avctx->bit_rate < 16000)
1753
38
        s->coeff_per_sb_select = 1;
1754
1.13k
    else
1755
1.13k
        s->coeff_per_sb_select = 2;
1756
1757
1.51k
    if (s->fft_size != (1 << (s->fft_order - 1))) {
1758
10
        av_log(avctx, AV_LOG_ERROR, "FFT size %d not power of 2.\n", s->fft_size);
1759
10
        return AVERROR_INVALIDDATA;
1760
10
    }
1761
1762
1.50k
    ret = av_tx_init(&s->rdft_ctx, &s->rdft_fn, AV_TX_FLOAT_RDFT, 1, 2*s->fft_size, &scale, 0);
1763
1.50k
    if (ret < 0)
1764
0
        return ret;
1765
1766
1.50k
    ff_mpadsp_init(&s->mpadsp);
1767
1768
1.50k
    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
1769
1770
1.50k
    ff_thread_once(&init_static_once, qdm2_init_static_data);
1771
1772
1.50k
    return 0;
1773
1.50k
}
1774
1775
static av_cold int qdm2_decode_close(AVCodecContext *avctx)
1776
1.50k
{
1777
1.50k
    QDM2Context *s = avctx->priv_data;
1778
1779
1.50k
    av_tx_uninit(&s->rdft_ctx);
1780
1781
1.50k
    return 0;
1782
1.50k
}
1783
1784
static int qdm2_decode(QDM2Context *q, const uint8_t *in, int16_t *out)
1785
11.5M
{
1786
11.5M
    int ch, i;
1787
11.5M
    const int frame_size = (q->frame_size * q->channels);
1788
1789
11.5M
    if((unsigned)frame_size > FF_ARRAY_ELEMS(q->output_buffer)/2)
1790
0
        return -1;
1791
1792
    /* select input buffer */
1793
11.5M
    q->compressed_data = in;
1794
11.5M
    q->compressed_size = q->checksum_size;
1795
1796
    /* copy old block, clear new block of output samples */
1797
11.5M
    memmove(q->output_buffer, &q->output_buffer[frame_size], frame_size * sizeof(float));
1798
11.5M
    memset(&q->output_buffer[frame_size], 0, frame_size * sizeof(float));
1799
1800
    /* decode block of QDM2 compressed data */
1801
11.5M
    if (q->sub_packet == 0) {
1802
721k
        q->has_errors = 0; // zero it for a new super block
1803
721k
        av_log(NULL,AV_LOG_DEBUG,"Superblock follows\n");
1804
721k
        qdm2_decode_super_block(q);
1805
721k
    }
1806
1807
    /* parse subpackets */
1808
11.5M
    if (!q->has_errors) {
1809
1.58M
        if (q->sub_packet == 2)
1810
99.0k
            qdm2_decode_fft_packets(q);
1811
1812
1.58M
        qdm2_fft_tone_synthesizer(q, q->sub_packet);
1813
1.58M
    }
1814
1815
    /* sound synthesis stage 1 (FFT) */
1816
25.4M
    for (ch = 0; ch < q->channels; ch++) {
1817
13.8M
        qdm2_calculate_fft(q, ch, q->sub_packet);
1818
1819
13.8M
        if (!q->has_errors && q->sub_packet_list_C[0].packet) {
1820
0
            SAMPLES_NEEDED_2("has errors, and C list is not empty")
1821
0
            return -1;
1822
0
        }
1823
13.8M
    }
1824
1825
    /* sound synthesis stage 2 (MPEG audio like synthesis filter) */
1826
11.5M
    if (!q->has_errors && q->do_synth_filter)
1827
1.08M
        qdm2_synthesis_filter(q, q->sub_packet);
1828
1829
11.5M
    q->sub_packet = (q->sub_packet + 1) % 16;
1830
1831
    /* clip and convert output float[] to 16-bit signed samples */
1832
1.89G
    for (i = 0; i < frame_size; i++) {
1833
1.87G
        int value = (int)q->output_buffer[i];
1834
1835
1.87G
        if (value > SOFTCLIP_THRESHOLD)
1836
597k
            value = (value >  HARDCLIP_THRESHOLD) ?  32767 :  softclip_table[ value - SOFTCLIP_THRESHOLD];
1837
1.87G
        else if (value < -SOFTCLIP_THRESHOLD)
1838
755k
            value = (value < -HARDCLIP_THRESHOLD) ? -32767 : -softclip_table[-value - SOFTCLIP_THRESHOLD];
1839
1840
1.87G
        out[i] = value;
1841
1.87G
    }
1842
1843
11.5M
    return 0;
1844
11.5M
}
1845
1846
static int qdm2_decode_frame(AVCodecContext *avctx, AVFrame *frame,
1847
                             int *got_frame_ptr, AVPacket *avpkt)
1848
892k
{
1849
892k
    const uint8_t *buf = avpkt->data;
1850
892k
    int buf_size = avpkt->size;
1851
892k
    QDM2Context *s = avctx->priv_data;
1852
892k
    int16_t *out;
1853
892k
    int i, ret;
1854
1855
892k
    if(!buf)
1856
0
        return 0;
1857
892k
    if(buf_size < s->checksum_size)
1858
165k
        return -1;
1859
1860
    /* get output buffer */
1861
727k
    frame->nb_samples = 16 * s->frame_size;
1862
727k
    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
1863
5.53k
        return ret;
1864
721k
    out = (int16_t *)frame->data[0];
1865
1866
12.2M
    for (i = 0; i < 16; i++) {
1867
11.5M
        if ((ret = qdm2_decode(s, buf, out)) < 0)
1868
0
            return ret;
1869
11.5M
        out += s->channels * s->frame_size;
1870
11.5M
    }
1871
1872
721k
    *got_frame_ptr = 1;
1873
1874
721k
    return s->checksum_size;
1875
721k
}
1876
1877
const FFCodec ff_qdm2_decoder = {
1878
    .p.name           = "qdm2",
1879
    CODEC_LONG_NAME("QDesign Music Codec 2"),
1880
    .p.type           = AVMEDIA_TYPE_AUDIO,
1881
    .p.id             = AV_CODEC_ID_QDM2,
1882
    .priv_data_size   = sizeof(QDM2Context),
1883
    .init             = qdm2_decode_init,
1884
    .close            = qdm2_decode_close,
1885
    FF_CODEC_DECODE_CB(qdm2_decode_frame),
1886
    .p.capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_CHANNEL_CONF,
1887
};