Coverage Report

Created: 2026-05-23 07:06

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