vlc: Add header #include when the types are used
[libav.git] / libavcodec / qdm2.c
CommitLineData
3135258e
RT
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 *
2912e87a 8 * This file is part of Libav.
b78e7197 9 *
2912e87a 10 * Libav is free software; you can redistribute it and/or
3135258e
RT
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
b78e7197 13 * version 2.1 of the License, or (at your option) any later version.
3135258e 14 *
2912e87a 15 * Libav is distributed in the hope that it will be useful,
3135258e
RT
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
2912e87a 21 * License along with Libav; if not, write to the Free Software
5509bffa 22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
3135258e
RT
23 */
24
25/**
ba87f080 26 * @file
3135258e
RT
27 * QDM2 decoder
28 * @author Ewald Snel, Benjamin Larsson, Alex Beregszaszi, Roberto Togni
ec679eb4 29 *
1c7a8c17
DB
30 * The decoder is not perfect yet, there are still some distortions
31 * especially on files encoded with 16 or 8 subbands.
3135258e
RT
32 */
33
34#include <math.h>
35#include <stddef.h>
36#include <stdio.h>
37
a903f8f0 38#include "libavutil/channel_layout.h"
b6686629
DB
39
40#define BITSTREAM_READER_LE
3135258e 41#include "avcodec.h"
0b5a26e8 42#include "bitstream.h"
594d4d5d 43#include "internal.h"
3135258e 44#include "mpegaudio.h"
b6686629
DB
45#include "mpegaudiodsp.h"
46#include "rdft.h"
73fc82f3 47#include "vlc.h"
3135258e
RT
48
49#include "qdm2data.h"
062777b3 50#include "qdm2_tablegen.h"
3135258e 51
3135258e 52
3135258e
RT
53#define QDM2_LIST_ADD(list, size, packet) \
54do { \
55 if (size > 0) { \
56 list[size - 1].next = &list[size]; \
57 } \
58 list[size].packet = packet; \
59 list[size].next = NULL; \
60 size++; \
61} while(0)
62
63// Result is 8, 16 or 30
64#define QDM2_SB_USED(sub_sampling) (((sub_sampling) >= 2) ? 30 : 8 << (sub_sampling))
65
66#define FIX_NOISE_IDX(noise_idx) \
67 if ((noise_idx) >= 3840) \
68 (noise_idx) -= 3840; \
69
70#define SB_DITHERING_NOISE(sb,noise_idx) (noise_table[(noise_idx)++] * sb_noise_attenuation[(sb)])
71
3135258e
RT
72#define SAMPLES_NEEDED \
73 av_log (NULL,AV_LOG_INFO,"This file triggers some untested code. Please contact the developers.\n");
74
75#define SAMPLES_NEEDED_2(why) \
76 av_log (NULL,AV_LOG_INFO,"This file triggers some missing code. Please contact the developers.\nPosition: %s\n",why);
77
291d74a4 78#define QDM2_MAX_FRAME_SIZE 512
3135258e
RT
79
80typedef int8_t sb_int8_array[2][30][64];
81
82/**
83 * Subpacket
84 */
7f9f771e 85typedef struct QDM2SubPacket {
3135258e
RT
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/**
1c7a8c17 92 * A node in the subpacket list
3135258e 93 */
621d7fe9 94typedef struct QDM2SubPNode {
3135258e 95 QDM2SubPacket *packet; ///< packet
621d7fe9 96 struct QDM2SubPNode *next; ///< pointer to next packet in the list, NULL if leaf node
3135258e
RT
97} QDM2SubPNode;
98
7f9f771e 99typedef struct QDM2Complex {
63cae55d
AC
100 float re;
101 float im;
102} QDM2Complex;
103
7f9f771e 104typedef struct FFTTone {
3135258e 105 float level;
63cae55d 106 QDM2Complex *complex;
0942f55c 107 const float *table;
3135258e
RT
108 int phase;
109 int phase_shift;
110 int duration;
111 short time_index;
112 short cutoff;
113} FFTTone;
114
7f9f771e 115typedef struct FFTCoefficient {
3135258e
RT
116 int16_t sub_packet;
117 uint8_t channel;
118 int16_t offset;
119 int16_t exp;
120 uint8_t phase;
121} FFTCoefficient;
122
7f9f771e 123typedef struct QDM2FFT {
9d35fa52 124 DECLARE_ALIGNED(32, QDM2Complex, complex)[MPA_MAX_CHANNELS][256];
3135258e
RT
125} QDM2FFT;
126
127/**
128 * QDM2 decoder context
129 */
7f9f771e 130typedef struct QDM2Context {
3135258e
RT
131 /// Parameters from codec header, do not change during playback
132 int nb_channels; ///< number of channels
133 int channels; ///< number of channels
134 int group_size; ///< size of frame group (16 frames per group)
135 int fft_size; ///< size of FFT, in complex numbers
136 int checksum_size; ///< size of data block, used also for checksum
137
138 /// Parameters built from header parameters, do not change during playback
139 int group_order; ///< order of frame group
140 int fft_order; ///< order of FFT (actually fftorder+1)
3135258e
RT
141 int frame_size; ///< size of data frame
142 int frequency_range;
143 int sub_sampling; ///< subsampling: 0=25%, 1=50%, 2=100% */
144 int coeff_per_sb_select; ///< selector for "num. of coeffs. per subband" tables. Can be 0, 1, 2
145 int cm_table_select; ///< selector for "coding method" tables. Can be 0, 1 (from init: 0-4)
146
147 /// Packets and packet lists
148 QDM2SubPacket sub_packets[16]; ///< the packets themselves
149 QDM2SubPNode sub_packet_list_A[16]; ///< list of all packets
150 QDM2SubPNode sub_packet_list_B[16]; ///< FFT packets B are on list
151 int sub_packets_B; ///< number of packets on 'B' list
152 QDM2SubPNode sub_packet_list_C[16]; ///< packets with errors?
153 QDM2SubPNode sub_packet_list_D[16]; ///< DCT packets
154
155 /// FFT and tones
156 FFTTone fft_tones[1000];
157 int fft_tone_start;
158 int fft_tone_end;
159 FFTCoefficient fft_coefs[1000];
160 int fft_coefs_index;
161 int fft_coefs_min_index[5];
162 int fft_coefs_max_index[5];
163 int fft_level_exp[6];
63cae55d 164 RDFTContext rdft_ctx;
3135258e
RT
165 QDM2FFT fft;
166
167 /// I/O data
0942f55c 168 const uint8_t *compressed_data;
3135258e 169 int compressed_size;
291d74a4 170 float output_buffer[QDM2_MAX_FRAME_SIZE * 2];
3135258e
RT
171
172 /// Synthesis filter
c4f5c2d6 173 MPADSPContext mpadsp;
984ece75 174 DECLARE_ALIGNED(32, float, synth_buf)[MPA_MAX_CHANNELS][512*2];
3135258e 175 int synth_buf_offset[MPA_MAX_CHANNELS];
984ece75 176 DECLARE_ALIGNED(32, float, sb_samples)[MPA_MAX_CHANNELS][128][SBLIMIT];
3a07f5a4 177 DECLARE_ALIGNED(32, float, samples)[MPA_MAX_CHANNELS * MPA_FRAME_SIZE];
3135258e
RT
178
179 /// Mixed temporary data used in decoding
180 float tone_level[MPA_MAX_CHANNELS][30][64];
181 int8_t coding_method[MPA_MAX_CHANNELS][30][64];
182 int8_t quantized_coeffs[MPA_MAX_CHANNELS][10][8];
183 int8_t tone_level_idx_base[MPA_MAX_CHANNELS][30][8];
184 int8_t tone_level_idx_hi1[MPA_MAX_CHANNELS][3][8][8];
185 int8_t tone_level_idx_mid[MPA_MAX_CHANNELS][26][8];
186 int8_t tone_level_idx_hi2[MPA_MAX_CHANNELS][26];
187 int8_t tone_level_idx[MPA_MAX_CHANNELS][30][64];
188 int8_t tone_level_idx_temp[MPA_MAX_CHANNELS][30][64];
189
190 // Flags
1c7a8c17 191 int has_errors; ///< packet has errors
3135258e
RT
192 int superblocktype_2_3; ///< select fft tables and some algorithm based on superblock type
193 int do_synth_filter; ///< used to perform or skip synthesis filter
194
195 int sub_packet;
1c7a8c17 196 int noise_idx; ///< index for dithering noise table
3135258e
RT
197} QDM2Context;
198
199
3135258e
RT
200static VLC vlc_tab_level;
201static VLC vlc_tab_diff;
202static VLC vlc_tab_run;
203static VLC fft_level_exp_alt_vlc;
204static VLC fft_level_exp_vlc;
205static VLC fft_stereo_exp_vlc;
206static VLC fft_stereo_phase_vlc;
207static VLC vlc_tab_tone_level_idx_hi1;
208static VLC vlc_tab_tone_level_idx_mid;
209static VLC vlc_tab_tone_level_idx_hi2;
210static VLC vlc_tab_type30;
211static VLC vlc_tab_type34;
212static VLC vlc_tab_fft_tone_offset[5];
213
8d9f1265
BL
214static const uint16_t qdm2_vlc_offs[] = {
215 0,260,566,598,894,1166,1230,1294,1678,1950,2214,2278,2310,2570,2834,3124,3448,3838,
216};
3135258e 217
76efedea
LB
218static const int switchtable[23] = {
219 0, 5, 1, 5, 5, 5, 5, 5, 2, 5, 5, 5, 5, 5, 5, 5, 3, 5, 5, 5, 5, 5, 4
220};
221
5ef251e5 222static av_cold void qdm2_init_vlc(void)
3135258e 223{
8d9f1265
BL
224 static VLC_TYPE qdm2_table[3838][2];
225
f054e309
LB
226 vlc_tab_level.table = &qdm2_table[qdm2_vlc_offs[0]];
227 vlc_tab_level.table_allocated = qdm2_vlc_offs[1] - qdm2_vlc_offs[0];
228 init_vlc(&vlc_tab_level, 8, 24,
229 vlc_tab_level_huffbits, 1, 1,
230 vlc_tab_level_huffcodes, 2, 2,
231 INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
232
233 vlc_tab_diff.table = &qdm2_table[qdm2_vlc_offs[1]];
234 vlc_tab_diff.table_allocated = qdm2_vlc_offs[2] - qdm2_vlc_offs[1];
235 init_vlc(&vlc_tab_diff, 8, 37,
236 vlc_tab_diff_huffbits, 1, 1,
237 vlc_tab_diff_huffcodes, 2, 2,
238 INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
239
240 vlc_tab_run.table = &qdm2_table[qdm2_vlc_offs[2]];
241 vlc_tab_run.table_allocated = qdm2_vlc_offs[3] - qdm2_vlc_offs[2];
242 init_vlc(&vlc_tab_run, 5, 6,
243 vlc_tab_run_huffbits, 1, 1,
244 vlc_tab_run_huffcodes, 1, 1,
245 INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
246
247 fft_level_exp_alt_vlc.table = &qdm2_table[qdm2_vlc_offs[3]];
248 fft_level_exp_alt_vlc.table_allocated = qdm2_vlc_offs[4] -
249 qdm2_vlc_offs[3];
250 init_vlc(&fft_level_exp_alt_vlc, 8, 28,
251 fft_level_exp_alt_huffbits, 1, 1,
252 fft_level_exp_alt_huffcodes, 2, 2,
253 INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
254
255 fft_level_exp_vlc.table = &qdm2_table[qdm2_vlc_offs[4]];
256 fft_level_exp_vlc.table_allocated = qdm2_vlc_offs[5] - qdm2_vlc_offs[4];
257 init_vlc(&fft_level_exp_vlc, 8, 20,
258 fft_level_exp_huffbits, 1, 1,
259 fft_level_exp_huffcodes, 2, 2,
260 INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
261
262 fft_stereo_exp_vlc.table = &qdm2_table[qdm2_vlc_offs[5]];
263 fft_stereo_exp_vlc.table_allocated = qdm2_vlc_offs[6] -
264 qdm2_vlc_offs[5];
265 init_vlc(&fft_stereo_exp_vlc, 6, 7,
266 fft_stereo_exp_huffbits, 1, 1,
267 fft_stereo_exp_huffcodes, 1, 1,
268 INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
269
270 fft_stereo_phase_vlc.table = &qdm2_table[qdm2_vlc_offs[6]];
271 fft_stereo_phase_vlc.table_allocated = qdm2_vlc_offs[7] -
272 qdm2_vlc_offs[6];
273 init_vlc(&fft_stereo_phase_vlc, 6, 9,
274 fft_stereo_phase_huffbits, 1, 1,
275 fft_stereo_phase_huffcodes, 1, 1,
276 INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
277
278 vlc_tab_tone_level_idx_hi1.table =
279 &qdm2_table[qdm2_vlc_offs[7]];
280 vlc_tab_tone_level_idx_hi1.table_allocated = qdm2_vlc_offs[8] -
281 qdm2_vlc_offs[7];
282 init_vlc(&vlc_tab_tone_level_idx_hi1, 8, 20,
283 vlc_tab_tone_level_idx_hi1_huffbits, 1, 1,
284 vlc_tab_tone_level_idx_hi1_huffcodes, 2, 2,
285 INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
286
287 vlc_tab_tone_level_idx_mid.table =
288 &qdm2_table[qdm2_vlc_offs[8]];
289 vlc_tab_tone_level_idx_mid.table_allocated = qdm2_vlc_offs[9] -
290 qdm2_vlc_offs[8];
291 init_vlc(&vlc_tab_tone_level_idx_mid, 8, 24,
292 vlc_tab_tone_level_idx_mid_huffbits, 1, 1,
293 vlc_tab_tone_level_idx_mid_huffcodes, 2, 2,
294 INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
295
296 vlc_tab_tone_level_idx_hi2.table =
297 &qdm2_table[qdm2_vlc_offs[9]];
298 vlc_tab_tone_level_idx_hi2.table_allocated = qdm2_vlc_offs[10] -
299 qdm2_vlc_offs[9];
300 init_vlc(&vlc_tab_tone_level_idx_hi2, 8, 24,
301 vlc_tab_tone_level_idx_hi2_huffbits, 1, 1,
302 vlc_tab_tone_level_idx_hi2_huffcodes, 2, 2,
303 INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
304
305 vlc_tab_type30.table = &qdm2_table[qdm2_vlc_offs[10]];
306 vlc_tab_type30.table_allocated = qdm2_vlc_offs[11] - qdm2_vlc_offs[10];
307 init_vlc(&vlc_tab_type30, 6, 9,
308 vlc_tab_type30_huffbits, 1, 1,
309 vlc_tab_type30_huffcodes, 1, 1,
310 INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
311
312 vlc_tab_type34.table = &qdm2_table[qdm2_vlc_offs[11]];
313 vlc_tab_type34.table_allocated = qdm2_vlc_offs[12] - qdm2_vlc_offs[11];
314 init_vlc(&vlc_tab_type34, 5, 10,
315 vlc_tab_type34_huffbits, 1, 1,
316 vlc_tab_type34_huffcodes, 1, 1,
317 INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
318
319 vlc_tab_fft_tone_offset[0].table =
320 &qdm2_table[qdm2_vlc_offs[12]];
321 vlc_tab_fft_tone_offset[0].table_allocated = qdm2_vlc_offs[13] -
322 qdm2_vlc_offs[12];
323 init_vlc(&vlc_tab_fft_tone_offset[0], 8, 23,
324 vlc_tab_fft_tone_offset_0_huffbits, 1, 1,
325 vlc_tab_fft_tone_offset_0_huffcodes, 2, 2,
326 INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
327
328 vlc_tab_fft_tone_offset[1].table =
329 &qdm2_table[qdm2_vlc_offs[13]];
330 vlc_tab_fft_tone_offset[1].table_allocated = qdm2_vlc_offs[14] -
331 qdm2_vlc_offs[13];
332 init_vlc(&vlc_tab_fft_tone_offset[1], 8, 28,
333 vlc_tab_fft_tone_offset_1_huffbits, 1, 1,
334 vlc_tab_fft_tone_offset_1_huffcodes, 2, 2,
335 INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
336
337 vlc_tab_fft_tone_offset[2].table =
338 &qdm2_table[qdm2_vlc_offs[14]];
339 vlc_tab_fft_tone_offset[2].table_allocated = qdm2_vlc_offs[15] -
340 qdm2_vlc_offs[14];
341 init_vlc(&vlc_tab_fft_tone_offset[2], 8, 32,
342 vlc_tab_fft_tone_offset_2_huffbits, 1, 1,
343 vlc_tab_fft_tone_offset_2_huffcodes, 2, 2,
344 INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
345
346 vlc_tab_fft_tone_offset[3].table =
347 &qdm2_table[qdm2_vlc_offs[15]];
348 vlc_tab_fft_tone_offset[3].table_allocated = qdm2_vlc_offs[16] -
349 qdm2_vlc_offs[15];
350 init_vlc(&vlc_tab_fft_tone_offset[3], 8, 35,
351 vlc_tab_fft_tone_offset_3_huffbits, 1, 1,
352 vlc_tab_fft_tone_offset_3_huffcodes, 2, 2,
353 INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
354
355 vlc_tab_fft_tone_offset[4].table =
356 &qdm2_table[qdm2_vlc_offs[16]];
357 vlc_tab_fft_tone_offset[4].table_allocated = qdm2_vlc_offs[17] -
358 qdm2_vlc_offs[16];
359 init_vlc(&vlc_tab_fft_tone_offset[4], 8, 38,
360 vlc_tab_fft_tone_offset_4_huffbits, 1, 1,
361 vlc_tab_fft_tone_offset_4_huffcodes, 2, 2,
362 INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
3135258e
RT
363}
364
0b5a26e8 365static int qdm2_get_vlc(BitstreamContext *bc, VLC *vlc, int flag, int depth)
3135258e
RT
366{
367 int value;
368
0b5a26e8 369 value = bitstream_read_vlc(bc, vlc->table, vlc->bits, depth);
3135258e
RT
370
371 /* stage-2, 3 bits exponent escape sequence */
372 if (value-- == 0)
0b5a26e8 373 value = bitstream_read(bc, bitstream_read(bc, 3) + 1);
3135258e
RT
374
375 /* stage-3, optional */
376 if (flag) {
377 int tmp = vlc_stage3_values[value];
378
379 if ((value & ~3) > 0)
0b5a26e8 380 tmp += bitstream_read(bc, value >> 2);
3135258e
RT
381 value = tmp;
382 }
383
384 return value;
385}
386
0b5a26e8 387static int qdm2_get_se_vlc(VLC *vlc, BitstreamContext *bc, int depth)
3135258e 388{
0b5a26e8 389 int value = qdm2_get_vlc(bc, vlc, 0, depth);
3135258e
RT
390
391 return (value & 1) ? ((value + 1) >> 1) : -(value >> 1);
392}
393
3135258e
RT
394/**
395 * QDM2 checksum
396 *
41ed7ab4 397 * @param data pointer to data to be checksummed
3135258e
RT
398 * @param length data length
399 * @param value checksum value
400 *
1c7a8c17 401 * @return 0 if checksum is OK
3135258e 402 */
76efedea
LB
403static uint16_t qdm2_packet_checksum(const uint8_t *data, int length, int value)
404{
3135258e
RT
405 int i;
406
76efedea 407 for (i = 0; i < length; i++)
3135258e
RT
408 value -= data[i];
409
410 return (uint16_t)(value & 0xffff);
411}
412
3135258e 413/**
49bd8e4b 414 * Fill a QDM2SubPacket structure with packet type, size, and data pointer.
3135258e 415 *
0b5a26e8 416 * @param bc bitreader context
3135258e
RT
417 * @param sub_packet packet under analysis
418 */
0b5a26e8 419static void qdm2_decode_sub_packet_header(BitstreamContext *bc,
76efedea 420 QDM2SubPacket *sub_packet)
3135258e 421{
0b5a26e8 422 sub_packet->type = bitstream_read(bc, 8);
3135258e
RT
423
424 if (sub_packet->type == 0) {
425 sub_packet->size = 0;
426 sub_packet->data = NULL;
427 } else {
0b5a26e8 428 sub_packet->size = bitstream_read(bc, 8);
3135258e 429
76efedea
LB
430 if (sub_packet->type & 0x80) {
431 sub_packet->size <<= 8;
0b5a26e8 432 sub_packet->size |= bitstream_read(bc, 8);
76efedea
LB
433 sub_packet->type &= 0x7f;
434 }
3135258e 435
76efedea 436 if (sub_packet->type == 0x7f)
0b5a26e8 437 sub_packet->type |= bitstream_read(bc, 8) << 8;
3135258e 438
76efedea 439 // FIXME: this depends on bitreader-internal data
0b5a26e8 440 sub_packet->data = &bc->buffer[bitstream_tell(bc) / 8];
3135258e
RT
441 }
442
76efedea 443 av_log(NULL, AV_LOG_DEBUG, "Subpacket: type=%d size=%d start_offs=%x\n",
0b5a26e8 444 sub_packet->type, sub_packet->size, bitstream_tell(bc) / 8);
3135258e
RT
445}
446
3135258e 447/**
1c7a8c17 448 * Return node pointer to first packet of requested type in list.
3135258e 449 *
1c7a8c17 450 * @param list list of subpackets to be scanned
3135258e
RT
451 * @param type type of searched subpacket
452 * @return node pointer for subpacket if found, else NULL
453 */
76efedea
LB
454static QDM2SubPNode *qdm2_search_subpacket_type_in_list(QDM2SubPNode *list,
455 int type)
3135258e 456{
4b1f5e50 457 while (list && list->packet) {
3135258e
RT
458 if (list->packet->type == type)
459 return list;
460 list = list->next;
461 }
462 return NULL;
463}
464
3135258e 465/**
49bd8e4b 466 * Replace 8 elements with their average value.
1c7a8c17 467 * Called by qdm2_decode_superblock before starting subblock decoding.
3135258e
RT
468 *
469 * @param q context
470 */
76efedea 471static void average_quantized_coeffs(QDM2Context *q)
3135258e
RT
472{
473 int i, j, n, ch, sum;
474
475 n = coeff_per_sb_for_avg[q->coeff_per_sb_select][QDM2_SB_USED(q->sub_sampling) - 1] + 1;
476
477 for (ch = 0; ch < q->nb_channels; ch++)
478 for (i = 0; i < n; i++) {
479 sum = 0;
480
481 for (j = 0; j < 8; j++)
482 sum += q->quantized_coeffs[ch][i][j];
483
484 sum /= 8;
485 if (sum > 0)
486 sum--;
487
76efedea 488 for (j = 0; j < 8; j++)
3135258e
RT
489 q->quantized_coeffs[ch][i][j] = sum;
490 }
491}
492
3135258e 493/**
1c7a8c17
DB
494 * Build subband samples with noise weighted by q->tone_level.
495 * Called by synthfilt_build_sb_samples.
3135258e
RT
496 *
497 * @param q context
498 * @param sb subband index
499 */
76efedea 500static void build_sb_samples_from_noise(QDM2Context *q, int sb)
3135258e
RT
501{
502 int ch, j;
503
504 FIX_NOISE_IDX(q->noise_idx);
505
506 if (!q->nb_channels)
507 return;
508
76efedea 509 for (ch = 0; ch < q->nb_channels; ch++) {
3135258e 510 for (j = 0; j < 64; j++) {
76efedea
LB
511 q->sb_samples[ch][j * 2][sb] =
512 SB_DITHERING_NOISE(sb, q->noise_idx) * q->tone_level[ch][sb][j];
513 q->sb_samples[ch][j * 2 + 1][sb] =
514 SB_DITHERING_NOISE(sb, q->noise_idx) * q->tone_level[ch][sb][j];
3135258e 515 }
76efedea 516 }
3135258e
RT
517}
518
3135258e 519/**
1c7a8c17
DB
520 * Called while processing data from subpackets 11 and 12.
521 * Used after making changes to coding_method array.
3135258e
RT
522 *
523 * @param sb subband index
524 * @param channels number of channels
525 * @param coding_method q->coding_method[0][0][0]
526 */
4ecdb5ed
LB
527static int fix_coding_method_array(int sb, int channels,
528 sb_int8_array coding_method)
3135258e 529{
76efedea 530 int j, k;
3135258e
RT
531 int ch;
532 int run, case_val;
3135258e
RT
533
534 for (ch = 0; ch < channels; ch++) {
535 for (j = 0; j < 64; ) {
4ecdb5ed
LB
536 if (coding_method[ch][sb][j] < 8)
537 return -1;
76efedea
LB
538 if ((coding_method[ch][sb][j] - 8) > 22) {
539 run = 1;
3135258e
RT
540 case_val = 8;
541 } else {
76efedea
LB
542 switch (switchtable[coding_method[ch][sb][j] - 8]) {
543 case 0: run = 10;
544 case_val = 10;
545 break;
546 case 1: run = 1;
547 case_val = 16;
548 break;
549 case 2: run = 5;
550 case_val = 24;
551 break;
552 case 3: run = 3;
553 case_val = 30;
554 break;
555 case 4: run = 1;
556 case_val = 30;
557 break;
558 case 5: run = 1;
559 case_val = 8;
560 break;
561 default: run = 1;
562 case_val = 8;
563 break;
3135258e
RT
564 }
565 }
76efedea
LB
566 for (k = 0; k < run; k++) {
567 if (j + k < 128) {
568 if (coding_method[ch][sb + (j + k) / 64][(j + k) % 64] > coding_method[ch][sb][j]) {
3135258e 569 if (k > 0) {
76efedea 570 SAMPLES_NEEDED
3135258e 571 //not debugged, almost never used
76efedea
LB
572 memset(&coding_method[ch][sb][j + k], case_val,
573 k *sizeof(int8_t));
574 memset(&coding_method[ch][sb][j + k], case_val,
575 3 * sizeof(int8_t));
3135258e 576 }
76efedea
LB
577 }
578 }
579 }
3135258e
RT
580 j += run;
581 }
582 }
4ecdb5ed 583 return 0;
3135258e
RT
584}
585
3135258e
RT
586/**
587 * Related to synthesis filter
588 * Called by process_subpacket_10
589 *
590 * @param q context
591 * @param flag 1 if called after getting data from subpacket 10, 0 if no subpacket 10
592 */
76efedea 593static void fill_tone_level_array(QDM2Context *q, int flag)
3135258e
RT
594{
595 int i, sb, ch, sb_used;
596 int tmp, tab;
597
3135258e
RT
598 for (ch = 0; ch < q->nb_channels; ch++)
599 for (sb = 0; sb < 30; sb++)
600 for (i = 0; i < 8; i++) {
601 if ((tab=coeff_per_sb_for_dequant[q->coeff_per_sb_select][sb]) < (last_coeff[q->coeff_per_sb_select] - 1))
602 tmp = q->quantized_coeffs[ch][tab + 1][i] * dequant_table[q->coeff_per_sb_select][tab + 1][sb]+
603 q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];
604 else
605 tmp = q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];
606 if(tmp < 0)
607 tmp += 0xff;
608 q->tone_level_idx_base[ch][sb][i] = (tmp / 256) & 0xff;
609 }
610
611 sb_used = QDM2_SB_USED(q->sub_sampling);
612
613 if ((q->superblocktype_2_3 != 0) && !flag) {
614 for (sb = 0; sb < sb_used; sb++)
615 for (ch = 0; ch < q->nb_channels; ch++)
616 for (i = 0; i < 64; i++) {
617 q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];
618 if (q->tone_level_idx[ch][sb][i] < 0)
619 q->tone_level[ch][sb][i] = 0;
620 else
621 q->tone_level[ch][sb][i] = fft_tone_level_table[0][q->tone_level_idx[ch][sb][i] & 0x3f];
622 }
623 } else {
624 tab = q->superblocktype_2_3 ? 0 : 1;
625 for (sb = 0; sb < sb_used; sb++) {
626 if ((sb >= 4) && (sb <= 23)) {
627 for (ch = 0; ch < q->nb_channels; ch++)
628 for (i = 0; i < 64; i++) {
629 tmp = q->tone_level_idx_base[ch][sb][i / 8] -
630 q->tone_level_idx_hi1[ch][sb / 8][i / 8][i % 8] -
631 q->tone_level_idx_mid[ch][sb - 4][i / 8] -
632 q->tone_level_idx_hi2[ch][sb - 4];
633 q->tone_level_idx[ch][sb][i] = tmp & 0xff;
634 if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
635 q->tone_level[ch][sb][i] = 0;
636 else
637 q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
638 }
639 } else {
640 if (sb > 4) {
641 for (ch = 0; ch < q->nb_channels; ch++)
642 for (i = 0; i < 64; i++) {
643 tmp = q->tone_level_idx_base[ch][sb][i / 8] -
644 q->tone_level_idx_hi1[ch][2][i / 8][i % 8] -
645 q->tone_level_idx_hi2[ch][sb - 4];
646 q->tone_level_idx[ch][sb][i] = tmp & 0xff;
647 if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
648 q->tone_level[ch][sb][i] = 0;
649 else
650 q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
651 }
652 } else {
653 for (ch = 0; ch < q->nb_channels; ch++)
654 for (i = 0; i < 64; i++) {
655 tmp = q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];
656 if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
657 q->tone_level[ch][sb][i] = 0;
658 else
659 q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
660 }
661 }
662 }
663 }
664 }
3135258e
RT
665}
666
3135258e
RT
667/**
668 * Related to synthesis filter
669 * Called by process_subpacket_11
670 * c is built with data from subpacket 11
76efedea
LB
671 * Most of this function is used only if superblock_type_2_3 == 0,
672 * never seen it in samples.
3135258e 673 *
115329f1 674 * @param tone_level_idx
3135258e
RT
675 * @param tone_level_idx_temp
676 * @param coding_method q->coding_method[0][0][0]
677 * @param nb_channels number of channels
678 * @param c coming from subpacket 11, passed as 8*c
679 * @param superblocktype_2_3 flag based on superblock packet type
680 * @param cm_table_select q->cm_table_select
681 */
76efedea
LB
682static void fill_coding_method_array(sb_int8_array tone_level_idx,
683 sb_int8_array tone_level_idx_temp,
684 sb_int8_array coding_method,
685 int nb_channels,
686 int c, int superblocktype_2_3,
687 int cm_table_select)
3135258e
RT
688{
689 int ch, sb, j;
690 int tmp, acc, esp_40, comp;
691 int add1, add2, add3, add4;
692 int64_t multres;
693
3135258e
RT
694 if (!superblocktype_2_3) {
695 /* This case is untested, no samples available */
696 SAMPLES_NEEDED
697 for (ch = 0; ch < nb_channels; ch++)
698 for (sb = 0; sb < 30; sb++) {
d11f9e1b 699 for (j = 1; j < 63; j++) { // The loop only iterates to 63 so the code doesn't overflow the buffer
3135258e
RT
700 add1 = tone_level_idx[ch][sb][j] - 10;
701 if (add1 < 0)
702 add1 = 0;
703 add2 = add3 = add4 = 0;
704 if (sb > 1) {
705 add2 = tone_level_idx[ch][sb - 2][j] + tone_level_idx_offset_table[sb][0] - 6;
706 if (add2 < 0)
707 add2 = 0;
708 }
709 if (sb > 0) {
710 add3 = tone_level_idx[ch][sb - 1][j] + tone_level_idx_offset_table[sb][1] - 6;
711 if (add3 < 0)
712 add3 = 0;
713 }
714 if (sb < 29) {
715 add4 = tone_level_idx[ch][sb + 1][j] + tone_level_idx_offset_table[sb][3] - 6;
716 if (add4 < 0)
717 add4 = 0;
718 }
719 tmp = tone_level_idx[ch][sb][j + 1] * 2 - add4 - add3 - add2 - add1;
720 if (tmp < 0)
721 tmp = 0;
722 tone_level_idx_temp[ch][sb][j + 1] = tmp & 0xff;
723 }
724 tone_level_idx_temp[ch][sb][0] = tone_level_idx_temp[ch][sb][1];
725 }
5ebef79a
AK
726
727 acc = 0;
728 for (ch = 0; ch < nb_channels; ch++)
729 for (sb = 0; sb < 30; sb++)
730 for (j = 0; j < 64; j++)
731 acc += tone_level_idx_temp[ch][sb][j];
732
733 multres = 0x66666667LL * (acc * 10);
734 esp_40 = (multres >> 32) / 8 + ((multres & 0xffffffff) >> 31);
735 for (ch = 0; ch < nb_channels; ch++)
736 for (sb = 0; sb < 30; sb++)
737 for (j = 0; j < 64; j++) {
738 comp = tone_level_idx_temp[ch][sb][j]* esp_40 * 10;
739 if (comp < 0)
740 comp += 0xff;
741 comp /= 256; // signed shift
742 switch(sb) {
743 case 0:
744 if (comp < 30)
745 comp = 30;
746 comp += 15;
747 break;
748 case 1:
749 if (comp < 24)
750 comp = 24;
751 comp += 10;
752 break;
753 case 2:
754 case 3:
755 case 4:
756 if (comp < 16)
757 comp = 16;
3135258e 758 }
5ebef79a
AK
759 if (comp <= 5)
760 tmp = 0;
761 else if (comp <= 10)
762 tmp = 10;
763 else if (comp <= 16)
764 tmp = 16;
765 else if (comp <= 24)
766 tmp = -1;
767 else
768 tmp = 0;
769 coding_method[ch][sb][j] = ((tmp & 0xfffa) + 30 )& 0xff;
770 }
771 for (sb = 0; sb < 30; sb++)
772 fix_coding_method_array(sb, nb_channels, coding_method);
773 for (ch = 0; ch < nb_channels; ch++)
3135258e 774 for (sb = 0; sb < 30; sb++)
5ebef79a
AK
775 for (j = 0; j < 64; j++)
776 if (sb >= 10) {
777 if (coding_method[ch][sb][j] < 10)
778 coding_method[ch][sb][j] = 10;
779 } else {
780 if (sb >= 2) {
781 if (coding_method[ch][sb][j] < 16)
782 coding_method[ch][sb][j] = 16;
3135258e 783 } else {
5ebef79a
AK
784 if (coding_method[ch][sb][j] < 30)
785 coding_method[ch][sb][j] = 30;
3135258e 786 }
5ebef79a 787 }
3135258e
RT
788 } else { // superblocktype_2_3 != 0
789 for (ch = 0; ch < nb_channels; ch++)
790 for (sb = 0; sb < 30; sb++)
791 for (j = 0; j < 64; j++)
792 coding_method[ch][sb][j] = coding_method_table[cm_table_select][sb];
793 }
3135258e
RT
794}
795
3135258e 796/**
76efedea
LB
797 * Called by process_subpacket_11 to process more data from subpacket 11
798 * with sb 0-8.
799 * Called by process_subpacket_12 to process data from subpacket 12 with
800 * sb 8-sb_used.
3135258e
RT
801 *
802 * @param q context
0b5a26e8 803 * @param bc bitreader context
1c7a8c17 804 * @param length packet length in bits
3135258e
RT
805 * @param sb_min lower subband processed (sb_min included)
806 * @param sb_max higher subband processed (sb_max excluded)
807 */
0b5a26e8 808static void synthfilt_build_sb_samples(QDM2Context *q, BitstreamContext *bc,
76efedea 809 int length, int sb_min, int sb_max)
3135258e
RT
810{
811 int sb, j, k, n, ch, run, channels;
adadc3f2 812 int joined_stereo, zero_encoding;
3135258e
RT
813 int type34_first;
814 float type34_div = 0;
815 float type34_predictor;
816 float samples[10], sign_bits[16];
817
818 if (length == 0) {
819 // If no data use noise
820 for (sb=sb_min; sb < sb_max; sb++)
45ee556d 821 build_sb_samples_from_noise(q, sb);
3135258e
RT
822
823 return;
824 }
825
826 for (sb = sb_min; sb < sb_max; sb++) {
3135258e
RT
827 channels = q->nb_channels;
828
829 if (q->nb_channels <= 1 || sb < 12)
830 joined_stereo = 0;
831 else if (sb >= 24)
832 joined_stereo = 1;
833 else
0b5a26e8 834 joined_stereo = (bitstream_bits_left(bc) >= 1) ? bitstream_read_bit(bc) : 0;
3135258e
RT
835
836 if (joined_stereo) {
0b5a26e8 837 if (bitstream_bits_left(bc) >= 16)
3135258e 838 for (j = 0; j < 16; j++)
0b5a26e8 839 sign_bits[j] = bitstream_read_bit(bc);
3135258e
RT
840
841 for (j = 0; j < 64; j++)
842 if (q->coding_method[1][sb][j] > q->coding_method[0][sb][j])
843 q->coding_method[0][sb][j] = q->coding_method[1][sb][j];
844
4ecdb5ed
LB
845 if (fix_coding_method_array(sb, q->nb_channels,
846 q->coding_method)) {
847 build_sb_samples_from_noise(q, sb);
848 continue;
849 }
3135258e
RT
850 channels = 1;
851 }
852
853 for (ch = 0; ch < channels; ch++) {
744a11c9 854 FIX_NOISE_IDX(q->noise_idx);
0b5a26e8 855 zero_encoding = (bitstream_bits_left(bc) >= 1) ? bitstream_read_bit(bc) : 0;
3135258e
RT
856 type34_predictor = 0.0;
857 type34_first = 1;
858
859 for (j = 0; j < 128; ) {
860 switch (q->coding_method[ch][sb][j / 2]) {
861 case 8:
0b5a26e8 862 if (bitstream_bits_left(bc) >= 10) {
3135258e
RT
863 if (zero_encoding) {
864 for (k = 0; k < 5; k++) {
865 if ((j + 2 * k) >= 128)
866 break;
0b5a26e8 867 samples[2 * k] = bitstream_read_bit(bc) ? dequant_1bit[joined_stereo][2 * bitstream_read_bit(bc)] : 0;
3135258e
RT
868 }
869 } else {
0b5a26e8 870 n = bitstream_read(bc, 8);
3135258e
RT
871 for (k = 0; k < 5; k++)
872 samples[2 * k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];
873 }
874 for (k = 0; k < 5; k++)
875 samples[2 * k + 1] = SB_DITHERING_NOISE(sb,q->noise_idx);
876 } else {
877 for (k = 0; k < 10; k++)
878 samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
879 }
880 run = 10;
881 break;
882
883 case 10:
0b5a26e8 884 if (bitstream_bits_left(bc) >= 1) {
3135258e
RT
885 float f = 0.81;
886
0b5a26e8 887 if (bitstream_read_bit(bc))
3135258e
RT
888 f = -f;
889 f -= noise_samples[((sb + 1) * (j +5 * ch + 1)) & 127] * 9.0 / 40.0;
890 samples[0] = f;
891 } else {
892 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
893 }
894 run = 1;
895 break;
896
897 case 16:
0b5a26e8 898 if (bitstream_bits_left(bc) >= 10) {
3135258e
RT
899 if (zero_encoding) {
900 for (k = 0; k < 5; k++) {
901 if ((j + k) >= 128)
902 break;
0b5a26e8 903 samples[k] = (bitstream_read_bit(bc) == 0) ? 0 : dequant_1bit[joined_stereo][2 * bitstream_read_bit(bc)];
3135258e
RT
904 }
905 } else {
0b5a26e8 906 n = bitstream_read (bc, 8);
3135258e
RT
907 for (k = 0; k < 5; k++)
908 samples[k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];
909 }
910 } else {
911 for (k = 0; k < 5; k++)
912 samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
913 }
914 run = 5;
915 break;
916
917 case 24:
0b5a26e8
AH
918 if (bitstream_bits_left(bc) >= 7) {
919 n = bitstream_read(bc, 7);
3135258e
RT
920 for (k = 0; k < 3; k++)
921 samples[k] = (random_dequant_type24[n][k] - 2.0) * 0.5;
922 } else {
923 for (k = 0; k < 3; k++)
924 samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
925 }
926 run = 3;
927 break;
928
929 case 30:
0b5a26e8
AH
930 if (bitstream_bits_left(bc) >= 4) {
931 unsigned index = qdm2_get_vlc(bc, &vlc_tab_type30, 0, 1);
64953f67
RB
932 if (index < FF_ARRAY_ELEMS(type30_dequant)) {
933 samples[0] = type30_dequant[index];
934 } else
935 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
936 } else
3135258e 937 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
115329f1 938
3135258e
RT
939 run = 1;
940 break;
941
942 case 34:
0b5a26e8 943 if (bitstream_bits_left(bc) >= 7) {
3135258e 944 if (type34_first) {
0b5a26e8
AH
945 type34_div = (float)(1 << bitstream_read(bc, 2));
946 samples[0] = ((float)bitstream_read(bc, 5) - 16.0) / 15.0;
3135258e
RT
947 type34_predictor = samples[0];
948 type34_first = 0;
949 } else {
0b5a26e8 950 unsigned index = qdm2_get_vlc(bc, &vlc_tab_type34, 0, 1);
64953f67
RB
951 if (index < FF_ARRAY_ELEMS(type34_delta)) {
952 samples[0] = type34_delta[index] / type34_div + type34_predictor;
953 type34_predictor = samples[0];
954 } else
955 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
3135258e
RT
956 }
957 } else {
958 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
959 }
960 run = 1;
961 break;
962
963 default:
964 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
965 run = 1;
966 break;
967 }
968
969 if (joined_stereo) {
adadc3f2
LB
970 for (k = 0; k < run && j + k < 128; k++) {
971 q->sb_samples[0][j + k][sb] =
972 q->tone_level[0][sb][(j + k) / 2] * samples[k];
973 if (q->nb_channels == 2) {
974 if (sign_bits[(j + k) / 8])
975 q->sb_samples[1][j + k][sb] =
976 q->tone_level[1][sb][(j + k) / 2] * -samples[k];
977 else
978 q->sb_samples[1][j + k][sb] =
979 q->tone_level[1][sb][(j + k) / 2] * samples[k];
980 }
3135258e 981 }
3135258e
RT
982 } else {
983 for (k = 0; k < run; k++)
984 if ((j + k) < 128)
984ece75 985 q->sb_samples[ch][j + k][sb] = q->tone_level[ch][sb][(j + k)/2] * samples[k];
3135258e
RT
986 }
987
988 j += run;
989 } // j loop
990 } // channel loop
991 } // subband loop
992}
993
3135258e 994/**
76efedea
LB
995 * Init the first element of a channel in quantized_coeffs with data
996 * from packet 10 (quantized_coeffs[ch][0]).
997 * This is similar to process_subpacket_9, but for a single channel
998 * and for element [0]
1c7a8c17 999 * same VLC tables as process_subpacket_9 are used.
3135258e 1000 *
3135258e 1001 * @param quantized_coeffs pointer to quantized_coeffs[ch][0]
0b5a26e8 1002 * @param bc bitreader context
3135258e 1003 */
76efedea 1004static void init_quantized_coeffs_elem0(int8_t *quantized_coeffs,
0b5a26e8 1005 BitstreamContext *bc)
3135258e
RT
1006{
1007 int i, k, run, level, diff;
1008
0b5a26e8 1009 if (bitstream_bits_left(bc) < 16)
3135258e 1010 return;
0b5a26e8 1011 level = qdm2_get_vlc(bc, &vlc_tab_level, 0, 2);
3135258e
RT
1012
1013 quantized_coeffs[0] = level;
1014
1015 for (i = 0; i < 7; ) {
0b5a26e8 1016 if (bitstream_bits_left(bc) < 16)
3135258e 1017 break;
0b5a26e8 1018 run = qdm2_get_vlc(bc, &vlc_tab_run, 0, 1) + 1;
3135258e 1019
0b5a26e8 1020 if (bitstream_bits_left(bc) < 16)
3135258e 1021 break;
0b5a26e8 1022 diff = qdm2_get_se_vlc(&vlc_tab_diff, bc, 2);
115329f1 1023
3135258e
RT
1024 for (k = 1; k <= run; k++)
1025 quantized_coeffs[i + k] = (level + ((k * diff) / run));
115329f1 1026
3135258e
RT
1027 level += diff;
1028 i += run;
1029 }
1030}
1031
3135258e
RT
1032/**
1033 * Related to synthesis filter, process data from packet 10
1034 * Init part of quantized_coeffs via function init_quantized_coeffs_elem0
76efedea
LB
1035 * Init tone_level_idx_hi1, tone_level_idx_hi2, tone_level_idx_mid with
1036 * data from packet 10
3135258e
RT
1037 *
1038 * @param q context
0b5a26e8 1039 * @param bc bitreader context
3135258e 1040 */
0b5a26e8 1041static void init_tone_level_dequantization(QDM2Context *q, BitstreamContext *bc)
3135258e
RT
1042{
1043 int sb, j, k, n, ch;
1044
1045 for (ch = 0; ch < q->nb_channels; ch++) {
0b5a26e8 1046 init_quantized_coeffs_elem0(q->quantized_coeffs[ch][0], bc);
3135258e 1047
0b5a26e8 1048 if (bitstream_bits_left(bc) < 16) {
3135258e
RT
1049 memset(q->quantized_coeffs[ch][0], 0, 8);
1050 break;
1051 }
1052 }
1053
1054 n = q->sub_sampling + 1;
1055
1056 for (sb = 0; sb < n; sb++)
1057 for (ch = 0; ch < q->nb_channels; ch++)
1058 for (j = 0; j < 8; j++) {
0b5a26e8 1059 if (bitstream_bits_left(bc) < 1)
3135258e 1060 break;
0b5a26e8 1061 if (bitstream_read_bit(bc)) {
3135258e 1062 for (k=0; k < 8; k++) {
0b5a26e8 1063 if (bitstream_bits_left(bc) < 16)
3135258e 1064 break;
0b5a26e8 1065 q->tone_level_idx_hi1[ch][sb][j][k] = qdm2_get_vlc(bc, &vlc_tab_tone_level_idx_hi1, 0, 2);
3135258e
RT
1066 }
1067 } else {
1068 for (k=0; k < 8; k++)
1069 q->tone_level_idx_hi1[ch][sb][j][k] = 0;
1070 }
1071 }
1072
1073 n = QDM2_SB_USED(q->sub_sampling) - 4;
1074
1075 for (sb = 0; sb < n; sb++)
1076 for (ch = 0; ch < q->nb_channels; ch++) {
0b5a26e8 1077 if (bitstream_bits_left(bc) < 16)
3135258e 1078 break;
0b5a26e8 1079 q->tone_level_idx_hi2[ch][sb] = qdm2_get_vlc(bc, &vlc_tab_tone_level_idx_hi2, 0, 2);
3135258e
RT
1080 if (sb > 19)
1081 q->tone_level_idx_hi2[ch][sb] -= 16;
1082 else
1083 for (j = 0; j < 8; j++)
1084 q->tone_level_idx_mid[ch][sb][j] = -16;
1085 }
1086
1087 n = QDM2_SB_USED(q->sub_sampling) - 5;
1088
1089 for (sb = 0; sb < n; sb++)
1090 for (ch = 0; ch < q->nb_channels; ch++)
1091 for (j = 0; j < 8; j++) {
0b5a26e8 1092 if (bitstream_bits_left(bc) < 16)
3135258e 1093 break;
0b5a26e8 1094 q->tone_level_idx_mid[ch][sb][j] = qdm2_get_vlc(bc, &vlc_tab_tone_level_idx_mid, 0, 2) - 32;
3135258e
RT
1095 }
1096}
1097
1098/**
1099 * Process subpacket 9, init quantized_coeffs with data from it
1100 *
1101 * @param q context
1102 * @param node pointer to node with packet
1103 */
76efedea 1104static void process_subpacket_9(QDM2Context *q, QDM2SubPNode *node)
3135258e 1105{
0b5a26e8 1106 BitstreamContext bc;
3135258e
RT
1107 int i, j, k, n, ch, run, level, diff;
1108
a25dac97 1109 bitstream_init8(&bc, node->packet->data, node->packet->size);
3135258e 1110
76efedea 1111 n = coeff_per_sb_for_avg[q->coeff_per_sb_select][QDM2_SB_USED(q->sub_sampling) - 1] + 1;
3135258e
RT
1112
1113 for (i = 1; i < n; i++)
76efedea 1114 for (ch = 0; ch < q->nb_channels; ch++) {
0b5a26e8 1115 level = qdm2_get_vlc(&bc, &vlc_tab_level, 0, 2);
3135258e
RT
1116 q->quantized_coeffs[ch][i][0] = level;
1117
1118 for (j = 0; j < (8 - 1); ) {
0b5a26e8
AH
1119 run = qdm2_get_vlc(&bc, &vlc_tab_run, 0, 1) + 1;
1120 diff = qdm2_get_se_vlc(&vlc_tab_diff, &bc, 2);
3135258e
RT
1121
1122 for (k = 1; k <= run; k++)
76efedea 1123 q->quantized_coeffs[ch][i][j + k] = (level + ((k * diff) / run));
3135258e
RT
1124
1125 level += diff;
76efedea 1126 j += run;
3135258e
RT
1127 }
1128 }
1129
1130 for (ch = 0; ch < q->nb_channels; ch++)
1131 for (i = 0; i < 8; i++)
1132 q->quantized_coeffs[ch][0][i] = 0;
1133}
1134
3135258e
RT
1135/**
1136 * Process subpacket 10 if not null, else
1137 *
1138 * @param q context
1139 * @param node pointer to node with packet
3135258e 1140 */
76efedea 1141static void process_subpacket_10(QDM2Context *q, QDM2SubPNode *node)
3135258e 1142{
0b5a26e8 1143 BitstreamContext bc;
3135258e 1144
9ffe8ee7 1145 if (node) {
a25dac97 1146 bitstream_init8(&bc, node->packet->data, node->packet->size);
0b5a26e8 1147 init_tone_level_dequantization(q, &bc);
3135258e
RT
1148 fill_tone_level_array(q, 1);
1149 } else {
1150 fill_tone_level_array(q, 0);
1151 }
1152}
1153
3135258e
RT
1154/**
1155 * Process subpacket 11
1156 *
1157 * @param q context
1158 * @param node pointer to node with packet
3135258e 1159 */
76efedea 1160static void process_subpacket_11(QDM2Context *q, QDM2SubPNode *node)
3135258e 1161{
0b5a26e8 1162 BitstreamContext bc;
9ffe8ee7
MR
1163 int length = 0;
1164
1165 if (node) {
1166 length = node->packet->size * 8;
0b5a26e8 1167 bitstream_init(&bc, node->packet->data, length);
9ffe8ee7 1168 }
3135258e 1169
3135258e 1170 if (length >= 32) {
0b5a26e8 1171 int c = bitstream_read(&bc, 13);
3135258e
RT
1172
1173 if (c > 3)
76efedea
LB
1174 fill_coding_method_array(q->tone_level_idx,
1175 q->tone_level_idx_temp, q->coding_method,
1176 q->nb_channels, 8 * c,
1177 q->superblocktype_2_3, q->cm_table_select);
3135258e
RT
1178 }
1179
0b5a26e8 1180 synthfilt_build_sb_samples(q, &bc, length, 0, 8);
3135258e
RT
1181}
1182
3135258e
RT
1183/**
1184 * Process subpacket 12
1185 *
1186 * @param q context
1187 * @param node pointer to node with packet
3135258e 1188 */
76efedea 1189static void process_subpacket_12(QDM2Context *q, QDM2SubPNode *node)
3135258e 1190{
0b5a26e8 1191 BitstreamContext bc;
9ffe8ee7
MR
1192 int length = 0;
1193
1194 if (node) {
1195 length = node->packet->size * 8;
0b5a26e8 1196 bitstream_init(&bc, node->packet->data, length);
9ffe8ee7 1197 }
3135258e 1198
0b5a26e8 1199 synthfilt_build_sb_samples(q, &bc, length, 8, QDM2_SB_USED(q->sub_sampling));
3135258e
RT
1200}
1201
1202/*
1203 * Process new subpackets for synthesis filter
1204 *
1205 * @param q context
1206 * @param list list with synthesis filter packets (list D)
1207 */
76efedea 1208static void process_synthesis_subpackets(QDM2Context *q, QDM2SubPNode *list)
3135258e
RT
1209{
1210 QDM2SubPNode *nodes[4];
1211
1212 nodes[0] = qdm2_search_subpacket_type_in_list(list, 9);
4b1f5e50 1213 if (nodes[0])
3135258e
RT
1214 process_subpacket_9(q, nodes[0]);
1215
1216 nodes[1] = qdm2_search_subpacket_type_in_list(list, 10);
4b1f5e50 1217 if (nodes[1])
9ffe8ee7 1218 process_subpacket_10(q, nodes[1]);
3135258e 1219 else
9ffe8ee7 1220 process_subpacket_10(q, NULL);
3135258e
RT
1221
1222 nodes[2] = qdm2_search_subpacket_type_in_list(list, 11);
4b1f5e50 1223 if (nodes[0] && nodes[1] && nodes[2])
9ffe8ee7 1224 process_subpacket_11(q, nodes[2]);
3135258e 1225 else
9ffe8ee7 1226 process_subpacket_11(q, NULL);
3135258e
RT
1227
1228 nodes[3] = qdm2_search_subpacket_type_in_list(list, 12);
4b1f5e50 1229 if (nodes[0] && nodes[1] && nodes[3])
9ffe8ee7 1230 process_subpacket_12(q, nodes[3]);
3135258e 1231 else
9ffe8ee7 1232 process_subpacket_12(q, NULL);
3135258e
RT
1233}
1234
3135258e 1235/*
1c7a8c17 1236 * Decode superblock, fill packet lists.
3135258e
RT
1237 *
1238 * @param q context
1239 */
76efedea 1240static void qdm2_decode_super_block(QDM2Context *q)
3135258e 1241{
0b5a26e8 1242 BitstreamContext bc;
3135258e
RT
1243 QDM2SubPacket header, *packet;
1244 int i, packet_bytes, sub_packet_size, sub_packets_D;
1245 unsigned int next_index = 0;
1246
1247 memset(q->tone_level_idx_hi1, 0, sizeof(q->tone_level_idx_hi1));
1248 memset(q->tone_level_idx_mid, 0, sizeof(q->tone_level_idx_mid));
1249 memset(q->tone_level_idx_hi2, 0, sizeof(q->tone_level_idx_hi2));
1250
1251 q->sub_packets_B = 0;
76efedea 1252 sub_packets_D = 0;
3135258e
RT
1253
1254 average_quantized_coeffs(q); // average elements in quantized_coeffs[max_ch][10][8]
1255
a25dac97 1256 bitstream_init8(&bc, q->compressed_data, q->compressed_size);
0b5a26e8 1257 qdm2_decode_sub_packet_header(&bc, &header);
3135258e
RT
1258
1259 if (header.type < 2 || header.type >= 8) {
1260 q->has_errors = 1;
76efedea 1261 av_log(NULL, AV_LOG_ERROR, "bad superblock type\n");
3135258e
RT
1262 return;
1263 }
1264
1265 q->superblocktype_2_3 = (header.type == 2 || header.type == 3);
0b5a26e8 1266 packet_bytes = (q->compressed_size - bitstream_tell(&bc) / 8);
3135258e 1267
a25dac97 1268 bitstream_init8(&bc, header.data, header.size);
3135258e
RT
1269
1270 if (header.type == 2 || header.type == 4 || header.type == 5) {
0b5a26e8
AH
1271 int csum = 257 * bitstream_read(&bc, 8);
1272 csum += 2 * bitstream_read(&bc, 8);
3135258e
RT
1273
1274 csum = qdm2_packet_checksum(q->compressed_data, q->checksum_size, csum);
1275
1276 if (csum != 0) {
1277 q->has_errors = 1;
76efedea 1278 av_log(NULL, AV_LOG_ERROR, "bad packet checksum\n");
3135258e
RT
1279 return;
1280 }
1281 }
1282
1283 q->sub_packet_list_B[0].packet = NULL;
1284 q->sub_packet_list_D[0].packet = NULL;
1285
1286 for (i = 0; i < 6; i++)
1287 if (--q->fft_level_exp[i] < 0)
1288 q->fft_level_exp[i] = 0;
1289
1290 for (i = 0; packet_bytes > 0; i++) {
1291 int j;
1292
39bec05e
MN
1293 if (i >= FF_ARRAY_ELEMS(q->sub_packet_list_A)) {
1294 SAMPLES_NEEDED_2("too many packet bytes");
1295 return;
1296 }
1297
3135258e
RT
1298 q->sub_packet_list_A[i].next = NULL;
1299
1300 if (i > 0) {
1301 q->sub_packet_list_A[i - 1].next = &q->sub_packet_list_A[i];
1302
1303 /* seek to next block */
a25dac97 1304 bitstream_init8(&bc, header.data, header.size);
0b5a26e8 1305 bitstream_skip(&bc, next_index * 8);
3135258e
RT
1306
1307 if (next_index >= header.size)
1308 break;
1309 }
1310
1c7a8c17 1311 /* decode subpacket */
3135258e 1312 packet = &q->sub_packets[i];
0b5a26e8
AH
1313 qdm2_decode_sub_packet_header(&bc, packet);
1314 next_index = packet->size + bitstream_tell(&bc) / 8;
3135258e
RT
1315 sub_packet_size = ((packet->size > 0xff) ? 1 : 0) + packet->size + 2;
1316
1317 if (packet->type == 0)
1318 break;
1319
1320 if (sub_packet_size > packet_bytes) {
1321 if (packet->type != 10 && packet->type != 11 && packet->type != 12)
1322 break;
1323 packet->size += packet_bytes - sub_packet_size;
1324 }
1325
1326 packet_bytes -= sub_packet_size;
1327
1c7a8c17 1328 /* add subpacket to 'all subpackets' list */
3135258e
RT
1329 q->sub_packet_list_A[i].packet = packet;
1330
1c7a8c17 1331 /* add subpacket to related list */
3135258e
RT
1332 if (packet->type == 8) {
1333 SAMPLES_NEEDED_2("packet type 8");
1334 return;
1335 } else if (packet->type >= 9 && packet->type <= 12) {
1336 /* packets for MPEG Audio like Synthesis Filter */
1337 QDM2_LIST_ADD(q->sub_packet_list_D, sub_packets_D, packet);
1338 } else if (packet->type == 13) {
1339 for (j = 0; j < 6; j++)
0b5a26e8 1340 q->fft_level_exp[j] = bitstream_read(&bc, 6);
3135258e
RT
1341 } else if (packet->type == 14) {
1342 for (j = 0; j < 6; j++)
0b5a26e8 1343 q->fft_level_exp[j] = qdm2_get_vlc(&bc, &fft_level_exp_vlc, 0, 2);
3135258e
RT
1344 } else if (packet->type == 15) {
1345 SAMPLES_NEEDED_2("packet type 15")
1346 return;
76efedea
LB
1347 } else if (packet->type >= 16 && packet->type < 48 &&
1348 !fft_subpackets[packet->type - 16]) {
3135258e
RT
1349 /* packets for FFT */
1350 QDM2_LIST_ADD(q->sub_packet_list_B, q->sub_packets_B, packet);
1351 }
1352 } // Packet bytes loop
1353
4b1f5e50 1354 if (q->sub_packet_list_D[0].packet) {
3135258e
RT
1355 process_synthesis_subpackets(q, q->sub_packet_list_D);
1356 q->do_synth_filter = 1;
1357 } else if (q->do_synth_filter) {
9ffe8ee7
MR
1358 process_subpacket_10(q, NULL);
1359 process_subpacket_11(q, NULL);
1360 process_subpacket_12(q, NULL);
3135258e 1361 }
3135258e
RT
1362}
1363
76efedea
LB
1364static void qdm2_fft_init_coefficient(QDM2Context *q, int sub_packet,
1365 int offset, int duration, int channel,
1366 int exp, int phase)
3135258e
RT
1367{
1368 if (q->fft_coefs_min_index[duration] < 0)
1369 q->fft_coefs_min_index[duration] = q->fft_coefs_index;
1370
76efedea
LB
1371 q->fft_coefs[q->fft_coefs_index].sub_packet =
1372 ((sub_packet >= 16) ? (sub_packet - 16) : sub_packet);
3135258e 1373 q->fft_coefs[q->fft_coefs_index].channel = channel;
76efedea
LB
1374 q->fft_coefs[q->fft_coefs_index].offset = offset;
1375 q->fft_coefs[q->fft_coefs_index].exp = exp;
1376 q->fft_coefs[q->fft_coefs_index].phase = phase;
3135258e
RT
1377 q->fft_coefs_index++;
1378}
1379
76efedea 1380static void qdm2_fft_decode_tones(QDM2Context *q, int duration,
0b5a26e8 1381 BitstreamContext *bc, int b)
3135258e
RT
1382{
1383 int channel, stereo, phase, exp;
76efedea 1384 int local_int_4, local_int_8, stereo_phase, local_int_10;
3135258e
RT
1385 int local_int_14, stereo_exp, local_int_20, local_int_28;
1386 int n, offset;
1387
76efedea 1388 local_int_4 = 0;
3135258e
RT
1389 local_int_28 = 0;
1390 local_int_20 = 2;
76efedea 1391 local_int_8 = (4 - duration);
3135258e 1392 local_int_10 = 1 << (q->group_order - duration - 1);
76efedea 1393 offset = 1;
3135258e
RT
1394
1395 while (1) {
1396 if (q->superblocktype_2_3) {
0b5a26e8 1397 while ((n = qdm2_get_vlc(bc, &vlc_tab_fft_tone_offset[local_int_8], 1, 2)) < 2) {
3135258e
RT
1398 offset = 1;
1399 if (n == 0) {
76efedea 1400 local_int_4 += local_int_10;
3135258e
RT
1401 local_int_28 += (1 << local_int_8);
1402 } else {
76efedea 1403 local_int_4 += 8 * local_int_10;
3135258e
RT
1404 local_int_28 += (8 << local_int_8);
1405 }
1406 }
1407 offset += (n - 2);
1408 } else {
0b5a26e8 1409 offset += qdm2_get_vlc(bc, &vlc_tab_fft_tone_offset[local_int_8], 1, 2);
3135258e 1410 while (offset >= (local_int_10 - 1)) {
76efedea 1411 offset += (1 - (local_int_10 - 1));
3135258e
RT
1412 local_int_4 += local_int_10;
1413 local_int_28 += (1 << local_int_8);
1414 }
1415 }
1416
1417 if (local_int_4 >= q->group_size)
1418 return;
1419
1420 local_int_14 = (offset >> local_int_8);
5a19acb1
LA
1421 if (local_int_14 >= FF_ARRAY_ELEMS(fft_level_index_table))
1422 return;
3135258e
RT
1423
1424 if (q->nb_channels > 1) {
0b5a26e8
AH
1425 channel = bitstream_read_bit(bc);
1426 stereo = bitstream_read_bit(bc);
3135258e
RT
1427 } else {
1428 channel = 0;
76efedea 1429 stereo = 0;
3135258e
RT
1430 }
1431
0b5a26e8 1432 exp = qdm2_get_vlc(bc, (b ? &fft_level_exp_vlc : &fft_level_exp_alt_vlc), 0, 2);
3135258e 1433 exp += q->fft_level_exp[fft_level_index_table[local_int_14]];
76efedea 1434 exp = (exp < 0) ? 0 : exp;
3135258e 1435
0b5a26e8 1436 phase = bitstream_read(bc, 3);
76efedea 1437 stereo_exp = 0;
3135258e
RT
1438 stereo_phase = 0;
1439
1440 if (stereo) {
0b5a26e8
AH
1441 stereo_exp = (exp - qdm2_get_vlc(bc, &fft_stereo_exp_vlc, 0, 1));
1442 stereo_phase = (phase - qdm2_get_vlc(bc, &fft_stereo_phase_vlc, 0, 1));
3135258e
RT
1443 if (stereo_phase < 0)
1444 stereo_phase += 8;
1445 }
1446
1447 if (q->frequency_range > (local_int_14 + 1)) {
1448 int sub_packet = (local_int_20 + local_int_28);
1449
76efedea
LB
1450 qdm2_fft_init_coefficient(q, sub_packet, offset, duration,
1451 channel, exp, phase);
3135258e 1452 if (stereo)
76efedea
LB
1453 qdm2_fft_init_coefficient(q, sub_packet, offset, duration,
1454 1 - channel,
1455 stereo_exp, stereo_phase);
3135258e 1456 }
3135258e
RT
1457 offset++;
1458 }
1459}
1460
76efedea 1461static void qdm2_decode_fft_packets(QDM2Context *q)
3135258e
RT
1462{
1463 int i, j, min, max, value, type, unknown_flag;
0b5a26e8 1464 BitstreamContext bc;
3135258e 1465
f929ab05 1466 if (!q->sub_packet_list_B[0].packet)
3135258e
RT
1467 return;
1468
f4433de9 1469 /* reset minimum indexes for FFT coefficients */
3135258e 1470 q->fft_coefs_index = 0;
76efedea 1471 for (i = 0; i < 5; i++)
3135258e
RT
1472 q->fft_coefs_min_index[i] = -1;
1473
1c7a8c17 1474 /* process subpackets ordered by type, largest type first */
3135258e 1475 for (i = 0, max = 256; i < q->sub_packets_B; i++) {
76efedea 1476 QDM2SubPacket *packet = NULL;
3135258e 1477
1c7a8c17 1478 /* find subpacket with largest type less than max */
5bfe3b85 1479 for (j = 0, min = 0; j < q->sub_packets_B; j++) {
3135258e
RT
1480 value = q->sub_packet_list_B[j].packet->type;
1481 if (value > min && value < max) {
76efedea 1482 min = value;
3135258e
RT
1483 packet = q->sub_packet_list_B[j].packet;
1484 }
1485 }
1486
1487 max = min;
1488
1489 /* check for errors (?) */
f7dbf86d
BL
1490 if (!packet)
1491 return;
1492
76efedea
LB
1493 if (i == 0 &&
1494 (packet->type < 16 || packet->type >= 48 ||
1495 fft_subpackets[packet->type - 16]))
3135258e
RT
1496 return;
1497
1498 /* decode FFT tones */
a25dac97 1499 bitstream_init8(&bc, packet->data, packet->size);
3135258e
RT
1500
1501 if (packet->type >= 32 && packet->type < 48 && !fft_subpackets[packet->type - 16])
1502 unknown_flag = 1;
1503 else
1504 unknown_flag = 0;
1505
1506 type = packet->type;
1507
1508 if ((type >= 17 && type < 24) || (type >= 33 && type < 40)) {
1509 int duration = q->sub_sampling + 5 - (type & 15);
1510
1511 if (duration >= 0 && duration < 4)
0b5a26e8 1512 qdm2_fft_decode_tones(q, duration, &bc, unknown_flag);
3135258e 1513 } else if (type == 31) {
76efedea 1514 for (j = 0; j < 4; j++)
0b5a26e8 1515 qdm2_fft_decode_tones(q, j, &bc, unknown_flag);
3135258e 1516 } else if (type == 46) {
76efedea 1517 for (j = 0; j < 6; j++)
0b5a26e8 1518 q->fft_level_exp[j] = bitstream_read(&bc, 6);
76efedea 1519 for (j = 0; j < 4; j++)
0b5a26e8 1520 qdm2_fft_decode_tones(q, j, &bc, unknown_flag);
3135258e
RT
1521 }
1522 } // Loop on B packets
1523
f4433de9 1524 /* calculate maximum indexes for FFT coefficients */
3135258e
RT
1525 for (i = 0, j = -1; i < 5; i++)
1526 if (q->fft_coefs_min_index[i] >= 0) {
1527 if (j >= 0)
1528 q->fft_coefs_max_index[j] = q->fft_coefs_min_index[i];
1529 j = i;
1530 }
1531 if (j >= 0)
1532 q->fft_coefs_max_index[j] = q->fft_coefs_index;
1533}
1534
76efedea 1535static void qdm2_fft_generate_tone(QDM2Context *q, FFTTone *tone)
3135258e 1536{
76efedea
LB
1537 float level, f[6];
1538 int i;
1539 QDM2Complex c;
1540 const double iscale = 2.0 * M_PI / 512.0;
3135258e
RT
1541
1542 tone->phase += tone->phase_shift;
1543
1544 /* calculate current level (maximum amplitude) of tone */
1545 level = fft_tone_envelope_table[tone->duration][tone->time_index] * tone->level;
76efedea
LB
1546 c.im = level * sin(tone->phase * iscale);
1547 c.re = level * cos(tone->phase * iscale);
3135258e
RT
1548
1549 /* generate FFT coefficients for tone */
1550 if (tone->duration >= 3 || tone->cutoff >= 3) {
63cae55d
AC
1551 tone->complex[0].im += c.im;
1552 tone->complex[0].re += c.re;
1553 tone->complex[1].im -= c.im;
1554 tone->complex[1].re -= c.re;
3135258e
RT
1555 } else {
1556 f[1] = -tone->table[4];
76efedea
LB
1557 f[0] = tone->table[3] - tone->table[0];
1558 f[2] = 1.0 - tone->table[2] - tone->table[3];
1559 f[3] = tone->table[1] + tone->table[4] - 1.0;
1560 f[4] = tone->table[0] - tone->table[1];
1561 f[5] = tone->table[2];
3135258e 1562 for (i = 0; i < 2; i++) {
76efedea
LB
1563 tone->complex[fft_cutoff_index_table[tone->cutoff][i]].re +=
1564 c.re * f[i];
1565 tone->complex[fft_cutoff_index_table[tone->cutoff][i]].im +=
1566 c.im * ((tone->cutoff <= i) ? -f[i] : f[i]);
3135258e
RT
1567 }
1568 for (i = 0; i < 4; i++) {
76efedea
LB
1569 tone->complex[i].re += c.re * f[i + 2];
1570 tone->complex[i].im += c.im * f[i + 2];
3135258e
RT
1571 }
1572 }
1573
1574 /* copy the tone if it has not yet died out */
1575 if (++tone->time_index < ((1 << (5 - tone->duration)) - 1)) {
76efedea
LB
1576 memcpy(&q->fft_tones[q->fft_tone_end], tone, sizeof(FFTTone));
1577 q->fft_tone_end = (q->fft_tone_end + 1) % 1000;
3135258e
RT
1578 }
1579}
1580
76efedea 1581static void qdm2_fft_tone_synthesizer(QDM2Context *q, int sub_packet)
3135258e
RT
1582{
1583 int i, j, ch;
1584 const double iscale = 0.25 * M_PI;
1585
1586 for (ch = 0; ch < q->channels; ch++) {
63cae55d 1587 memset(q->fft.complex[ch], 0, q->fft_size * sizeof(QDM2Complex));
3135258e
RT
1588 }
1589
1590
1591 /* apply FFT tones with duration 4 (1 FFT period) */
1592 if (q->fft_coefs_min_index[4] >= 0)
1593 for (i = q->fft_coefs_min_index[4]; i < q->fft_coefs_max_index[4]; i++) {
1594 float level;
1595 QDM2Complex c;
1596
1597 if (q->fft_coefs[i].sub_packet != sub_packet)
1598 break;
1599
1600 ch = (q->channels == 1) ? 0 : q->fft_coefs[i].channel;
1601 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];
1602
1603 c.re = level * cos(q->fft_coefs[i].phase * iscale);
1604 c.im = level * sin(q->fft_coefs[i].phase * iscale);
63cae55d
AC
1605 q->fft.complex[ch][q->fft_coefs[i].offset + 0].re += c.re;
1606 q->fft.complex[ch][q->fft_coefs[i].offset + 0].im += c.im;
1607 q->fft.complex[ch][q->fft_coefs[i].offset + 1].re -= c.re;
1608 q->fft.complex[ch][q->fft_coefs[i].offset + 1].im -= c.im;
3135258e
RT
1609 }
1610
1611 /* generate existing FFT tones */
1612 for (i = q->fft_tone_end; i != q->fft_tone_start; ) {
1613 qdm2_fft_generate_tone(q, &q->fft_tones[q->fft_tone_start]);
1614 q->fft_tone_start = (q->fft_tone_start + 1) % 1000;
1615 }
1616
1617 /* create and generate new FFT tones with duration 0 (long) to 3 (short) */
1618 for (i = 0; i < 4; i++)
1619 if (q->fft_coefs_min_index[i] >= 0) {
1620 for (j = q->fft_coefs_min_index[i]; j < q->fft_coefs_max_index[i]; j++) {
1621 int offset, four_i;
1622 FFTTone tone;
1623
1624 if (q->fft_coefs[j].sub_packet != sub_packet)
1625 break;
1626
1627 four_i = (4 - i);
1628 offset = q->fft_coefs[j].offset >> four_i;
1629 ch = (q->channels == 1) ? 0 : q->fft_coefs[j].channel;
1630
1631 if (offset < q->frequency_range) {
1632 if (offset < 2)
1633 tone.cutoff = offset;
1634 else
1635 tone.cutoff = (offset >= 60) ? 3 : 2;
1636
1637 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];
63cae55d 1638 tone.complex = &q->fft.complex[ch][offset];
0942f55c 1639 tone.table = fft_tone_sample_table[i][q->fft_coefs[j].offset - (offset << four_i)];
3135258e
RT
1640 tone.phase = 64 * q->fft_coefs[j].phase - (offset << 8) - 128;
1641 tone.phase_shift = (2 * q->fft_coefs[j].offset + 1) << (7 - four_i);
1642 tone.duration = i;
1643 tone.time_index = 0;
1644
1645 qdm2_fft_generate_tone(q, &tone);
1646 }
1647 }
1648 q->fft_coefs_min_index[i] = j;
1649 }
1650}
1651
76efedea 1652static void qdm2_calculate_fft(QDM2Context *q, int channel, int sub_packet)
3135258e 1653{
63cae55d 1654 const float gain = (q->channels == 1 && q->nb_channels == 2) ? 0.5f : 1.0f;
76efedea 1655 float *out = q->output_buffer + channel;
63cae55d
AC
1656 int i;
1657 q->fft.complex[channel][0].re *= 2.0f;
76efedea 1658 q->fft.complex[channel][0].im = 0.0f;
26f548bb 1659 q->rdft_ctx.rdft_calc(&q->rdft_ctx, (FFTSample *)q->fft.complex[channel]);
3135258e 1660 /* add samples to output buffer */
f5be7958
MR
1661 for (i = 0; i < FFALIGN(q->fft_size, 8); i++) {
1662 out[0] += q->fft.complex[channel][i].re * gain;
1663 out[q->channels] += q->fft.complex[channel][i].im * gain;
76efedea 1664 out += 2 * q->channels;
f5be7958 1665 }
3135258e
RT
1666}
1667
3135258e
RT
1668/**
1669 * @param q context
1670 * @param index subpacket number
1671 */
76efedea 1672static void qdm2_synthesis_filter(QDM2Context *q, int index)
3135258e 1673{
3135258e
RT
1674 int i, k, ch, sb_used, sub_sampling, dither_state = 0;
1675
1676 /* copy sb_samples */
1677 sb_used = QDM2_SB_USED(q->sub_sampling);
1678
1679 for (ch = 0; ch < q->channels; ch++)
1680 for (i = 0; i < 8; i++)
76efedea 1681 for (k = sb_used; k < SBLIMIT; k++)
3135258e
RT
1682 q->sb_samples[ch][(8 * index) + i][k] = 0;
1683
1684 for (ch = 0; ch < q->nb_channels; ch++) {
3a07f5a4 1685 float *samples_ptr = q->samples + ch;
3135258e
RT
1686
1687 for (i = 0; i < 8; i++) {
984ece75 1688 ff_mpa_synth_filter_float(&q->mpadsp,
76efedea
LB
1689 q->synth_buf[ch], &(q->synth_buf_offset[ch]),
1690 ff_mpa_synth_window_float, &dither_state,
1691 samples_ptr, q->nb_channels,
1692 q->sb_samples[ch][(8 * index) + i]);
3135258e
RT
1693 samples_ptr += 32 * q->nb_channels;
1694 }
1695 }
1696
1697 /* add samples to output buffer */
1698 sub_sampling = (4 >> q->sub_sampling);
1699
1700 for (ch = 0; ch < q->channels; ch++)
1701 for (i = 0; i < q->frame_size; i++)
3a07f5a4 1702 q->output_buffer[q->channels * i + ch] += (1 << 23) * q->samples[q->nb_channels * sub_sampling * i + ch];
3135258e
RT
1703}
1704
3135258e
RT
1705/**
1706 * Init static data (does not depend on specific file)
1707 *
1708 * @param q context
1709 */
f054e309 1710static av_cold void qdm2_init_static_data(AVCodec *codec) {
3135258e 1711 qdm2_init_vlc();
984ece75 1712 ff_mpa_synth_init_float(ff_mpa_synth_window_float);
3135258e
RT
1713 softclip_table_init();
1714 rnd_table_init();
1715 init_noise_samples();
3135258e
RT
1716}
1717
3135258e
RT
1718/**
1719 * Init parameters from codec extradata
1720 */
5ef251e5 1721static av_cold int qdm2_decode_init(AVCodecContext *avctx)
3135258e
RT
1722{
1723 QDM2Context *s = avctx->priv_data;
1724 uint8_t *extradata;
1725 int extradata_size;
1726 int tmp_val, tmp, size;
115329f1 1727
3135258e 1728 /* extradata parsing
115329f1 1729
3135258e
RT
1730 Structure:
1731 wave {
1732 frma (QDM2)
1733 QDCA
1734 QDCP
1735 }
115329f1 1736
3135258e
RT
1737 32 size (including this field)
1738 32 tag (=frma)
1739 32 type (=QDM2 or QDMC)
115329f1 1740
3135258e
RT
1741 32 size (including this field, in bytes)
1742 32 tag (=QDCA) // maybe mandatory parameters
1743 32 unknown (=1)
1744 32 channels (=2)
1745 32 samplerate (=44100)
1746 32 bitrate (=96000)
1747 32 block size (=4096)
1748 32 frame size (=256) (for one channel)
1749 32 packet size (=1300)
115329f1 1750
3135258e
RT
1751 32 size (including this field, in bytes)
1752 32 tag (=QDCP) // maybe some tuneable parameters
1753 32 float1 (=1.0)
1754 32 zero ?
1755 32 float2 (=1.0)
1756 32 float3 (=1.0)
1757 32 unknown (27)
1758 32 unknown (8)
1759 32 zero ?
1760 */
1761
1762 if (!avctx->extradata || (avctx->extradata_size < 48)) {
1763 av_log(avctx, AV_LOG_ERROR, "extradata missing or truncated\n");
f3e04526 1764 return AVERROR_INVALIDDATA;
3135258e
RT
1765 }
1766
76efedea 1767 extradata = avctx->extradata;
3135258e
RT
1768 extradata_size = avctx->extradata_size;
1769
1770 while (extradata_size > 7) {
1771 if (!memcmp(extradata, "frmaQDM", 7))
1772 break;
1773 extradata++;
1774 extradata_size--;
1775 }
1776
1777 if (extradata_size < 12) {
1778 av_log(avctx, AV_LOG_ERROR, "not enough extradata (%i)\n",
1779 extradata_size);
f3e04526 1780 return AVERROR_INVALIDDATA;
3135258e
RT
1781 }
1782
1783 if (memcmp(extradata, "frmaQDM", 7)) {
1784 av_log(avctx, AV_LOG_ERROR, "invalid headers, QDM? not found\n");
f3e04526 1785 return AVERROR_INVALIDDATA;
3135258e
RT
1786 }
1787
1788 if (extradata[7] == 'C') {
1789// s->is_qdmc = 1;
f3e04526
HS
1790 avpriv_report_missing_feature(avctx, "QDMC version 1");
1791 return AVERROR_PATCHWELCOME;
3135258e
RT
1792 }
1793
1794 extradata += 8;
1795 extradata_size -= 8;
1796
fead30d4 1797 size = AV_RB32(extradata);
3135258e
RT
1798
1799 if(size > extradata_size){
1800 av_log(avctx, AV_LOG_ERROR, "extradata size too small, %i < %i\n",
1801 extradata_size, size);
f3e04526 1802 return AVERROR_INVALIDDATA;
3135258e
RT
1803 }
1804
1805 extradata += 4;
1806 av_log(avctx, AV_LOG_DEBUG, "size: %d\n", size);
fead30d4 1807 if (AV_RB32(extradata) != MKBETAG('Q','D','C','A')) {
3135258e 1808 av_log(avctx, AV_LOG_ERROR, "invalid extradata, expecting QDCA\n");
f3e04526 1809 return AVERROR_INVALIDDATA;
3135258e
RT
1810 }
1811
1812 extradata += 8;
1813
fead30d4 1814 avctx->channels = s->nb_channels = s->channels = AV_RB32(extradata);
3135258e 1815 extradata += 4;
be2ab8b7 1816 if (s->channels <= 0 || s->channels > MPA_MAX_CHANNELS)
291d74a4 1817 return AVERROR_INVALIDDATA;
be2ab8b7
JR
1818 avctx->channel_layout = avctx->channels == 2 ? AV_CH_LAYOUT_STEREO :
1819 AV_CH_LAYOUT_MONO;
3135258e 1820
fead30d4 1821 avctx->sample_rate = AV_RB32(extradata);
3135258e
RT
1822 extradata += 4;
1823
fead30d4 1824 avctx->bit_rate = AV_RB32(extradata);
3135258e
RT
1825 extradata += 4;
1826
fead30d4 1827 s->group_size = AV_RB32(extradata);
3135258e
RT
1828 extradata += 4;
1829
fead30d4 1830 s->fft_size = AV_RB32(extradata);
3135258e
RT
1831 extradata += 4;
1832
fead30d4 1833 s->checksum_size = AV_RB32(extradata);
dac56d9c
AC
1834 if (s->checksum_size >= 1U << 28) {
1835 av_log(avctx, AV_LOG_ERROR, "data block size too large (%u)\n", s->checksum_size);
1836 return AVERROR_INVALIDDATA;
1837 }
3135258e
RT
1838
1839 s->fft_order = av_log2(s->fft_size) + 1;
3135258e
RT
1840
1841 // something like max decodable tones
1842 s->group_order = av_log2(s->group_size) + 1;
1843 s->frame_size = s->group_size / 16; // 16 iterations per super block
291d74a4
LA
1844 if (s->frame_size > QDM2_MAX_FRAME_SIZE)
1845 return AVERROR_INVALIDDATA;
3135258e 1846
a4893baf 1847 s->sub_sampling = s->fft_order - 7;
3135258e 1848 s->frequency_range = 255 / (1 << (2 - s->sub_sampling));
115329f1 1849
3135258e
RT
1850 switch ((s->sub_sampling * 2 + s->channels - 1)) {
1851 case 0: tmp = 40; break;
1852 case 1: tmp = 48; break;
1853 case 2: tmp = 56; break;
1854 case 3: tmp = 72; break;
1855 case 4: tmp = 80; break;
1856 case 5: tmp = 100;break;
1857 default: tmp=s->sub_sampling; break;
1858 }
1859 tmp_val = 0;
1860 if ((tmp * 1000) < avctx->bit_rate) tmp_val = 1;
1861 if ((tmp * 1440) < avctx->bit_rate) tmp_val = 2;
1862 if ((tmp * 1760) < avctx->bit_rate) tmp_val = 3;
1863 if ((tmp * 2240) < avctx->bit_rate) tmp_val = 4;
1864 s->cm_table_select = tmp_val;
1865
1866 if (s->sub_sampling == 0)
a4893baf 1867 tmp = 7999;
3135258e
RT
1868 else
1869 tmp = ((-(s->sub_sampling -1)) & 8000) + 20000;
1870 /*
a4893baf 1871 0: 7999 -> 0
3135258e
RT
1872 1: 20000 -> 2
1873 2: 28000 -> 2
1874 */
1875 if (tmp < 8000)
1876 s->coeff_per_sb_select = 0;
1877 else if (tmp <= 16000)
1878 s->coeff_per_sb_select = 1;
1879 else
1880 s->coeff_per_sb_select = 2;
1881
63cae55d 1882 // Fail on unknown fft order
a4893baf 1883 if ((s->fft_order < 7) || (s->fft_order > 9)) {
f3e04526
HS
1884 avpriv_request_sample(avctx, "Unknown FFT order %d", s->fft_order);
1885 return AVERROR_PATCHWELCOME;
a4893baf 1886 }
34f87a58
AK
1887 if (s->fft_size != (1 << (s->fft_order - 1))) {
1888 av_log(avctx, AV_LOG_ERROR, "FFT size %d not power of 2.\n", s->fft_size);
1889 return AVERROR_INVALIDDATA;
1890 }
3135258e 1891
41ea18fb 1892 ff_rdft_init(&s->rdft_ctx, s->fft_order, IDFT_C2R);
c4f5c2d6 1893 ff_mpadsp_init(&s->mpadsp);
3135258e 1894
5d6e4c16 1895 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
fd76c37f 1896
3135258e
RT
1897 return 0;
1898}
1899
5ef251e5 1900static av_cold int qdm2_decode_close(AVCodecContext *avctx)
3135258e
RT
1901{
1902 QDM2Context *s = avctx->priv_data;
1903
63cae55d 1904 ff_rdft_end(&s->rdft_ctx);
115329f1 1905
3135258e
RT
1906 return 0;
1907}
1908
76efedea 1909static int qdm2_decode(QDM2Context *q, const uint8_t *in, int16_t *out)
3135258e
RT
1910{
1911 int ch, i;
1912 const int frame_size = (q->frame_size * q->channels);
115329f1 1913
3135258e
RT
1914 /* select input buffer */
1915 q->compressed_data = in;
1916 q->compressed_size = q->checksum_size;
1917
3135258e
RT
1918 /* copy old block, clear new block of output samples */
1919 memmove(q->output_buffer, &q->output_buffer[frame_size], frame_size * sizeof(float));
1920 memset(&q->output_buffer[frame_size], 0, frame_size * sizeof(float));
1921
1922 /* decode block of QDM2 compressed data */
1923 if (q->sub_packet == 0) {
1924 q->has_errors = 0; // zero it for a new super block
1c7a8c17 1925 av_log(NULL,AV_LOG_DEBUG,"Superblock follows\n");
3135258e
RT
1926 qdm2_decode_super_block(q);
1927 }
1928
1c7a8c17 1929 /* parse subpackets */
3135258e
RT
1930 if (!q->has_errors) {
1931 if (q->sub_packet == 2)
1932 qdm2_decode_fft_packets(q);
1933
1934 qdm2_fft_tone_synthesizer(q, q->sub_packet);
1935 }
1936
1937 /* sound synthesis stage 1 (FFT) */
1938 for (ch = 0; ch < q->channels; ch++) {
1939 qdm2_calculate_fft(q, ch, q->sub_packet);
1940
4b1f5e50 1941 if (!q->has_errors && q->sub_packet_list_C[0].packet) {
3135258e 1942 SAMPLES_NEEDED_2("has errors, and C list is not empty")
47d2ddca 1943 return -1;
3135258e
RT
1944 }
1945 }
1946
1947 /* sound synthesis stage 2 (MPEG audio like synthesis filter) */
1948 if (!q->has_errors && q->do_synth_filter)
1949 qdm2_synthesis_filter(q, q->sub_packet);
1950
1951 q->sub_packet = (q->sub_packet + 1) % 16;
1952
41ed7ab4 1953 /* clip and convert output float[] to 16-bit signed samples */
3135258e
RT
1954 for (i = 0; i < frame_size; i++) {
1955 int value = (int)q->output_buffer[i];
1956
1957 if (value > SOFTCLIP_THRESHOLD)
1958 value = (value > HARDCLIP_THRESHOLD) ? 32767 : softclip_table[ value - SOFTCLIP_THRESHOLD];
1959 else if (value < -SOFTCLIP_THRESHOLD)
1960 value = (value < -HARDCLIP_THRESHOLD) ? -32767 : -softclip_table[-value - SOFTCLIP_THRESHOLD];
1961
1962 out[i] = value;
1963 }
47d2ddca
BC
1964
1965 return 0;
3135258e
RT
1966}
1967
0eea2129
JR
1968static int qdm2_decode_frame(AVCodecContext *avctx, void *data,
1969 int *got_frame_ptr, AVPacket *avpkt)
3135258e 1970{
e01e1a46 1971 AVFrame *frame = data;
7a00bbad
TB
1972 const uint8_t *buf = avpkt->data;
1973 int buf_size = avpkt->size;
3135258e 1974 QDM2Context *s = avctx->priv_data;
0eea2129
JR
1975 int16_t *out;
1976 int i, ret;
3135258e 1977
d00bff20 1978 if(!buf)
3135258e 1979 return 0;
d00bff20
MN
1980 if(buf_size < s->checksum_size)
1981 return -1;
3135258e 1982
0eea2129 1983 /* get output buffer */
e01e1a46 1984 frame->nb_samples = 16 * s->frame_size;
759001c5 1985 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
0eea2129
JR
1986 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1987 return ret;
7d49f79f 1988 }
e01e1a46 1989 out = (int16_t *)frame->data[0];
3135258e 1990
47d2ddca 1991 for (i = 0; i < 16; i++) {
f3e04526
HS
1992 if ((ret = qdm2_decode(s, buf, out)) < 0)
1993 return ret;
47d2ddca 1994 out += s->channels * s->frame_size;
3135258e
RT
1995 }
1996
e01e1a46 1997 *got_frame_ptr = 1;
47d2ddca 1998
0c1758f0 1999 return s->checksum_size;
3135258e
RT
2000}
2001
76efedea 2002AVCodec ff_qdm2_decoder = {
f054e309 2003 .name = "qdm2",
b2bed932 2004 .long_name = NULL_IF_CONFIG_SMALL("QDesign Music Codec 2"),
f054e309
LB
2005 .type = AVMEDIA_TYPE_AUDIO,
2006 .id = AV_CODEC_ID_QDM2,
2007 .priv_data_size = sizeof(QDM2Context),
2008 .init = qdm2_decode_init,
2009 .init_static_data = qdm2_init_static_data,
2010 .close = qdm2_decode_close,
2011 .decode = qdm2_decode_frame,
def97856 2012 .capabilities = AV_CODEC_CAP_DR1,
3135258e 2013};