1 /* ScummVM - Graphic Adventure Engine
2  *
3  * ScummVM is the legal property of its developers, whose names
4  * are too numerous to list here. Please refer to the COPYRIGHT
5  * file distributed with this source distribution.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20  *
21  */
22 
23 // Based off ffmpeg's QDM2 decoder
24 
25 #include "common/scummsys.h"
26 #include "audio/decoders/qdm2.h"
27 
28 #ifdef AUDIO_QDM2_H
29 
30 #include "audio/audiostream.h"
31 #include "audio/decoders/codec.h"
32 #include "audio/decoders/qdm2data.h"
33 #include "audio/decoders/raw.h"
34 
35 #include "common/array.h"
36 #include "common/debug.h"
37 #include "common/math.h"
38 #include "common/rdft.h"
39 #include "common/stream.h"
40 #include "common/memstream.h"
41 #include "common/bitstream.h"
42 #include "common/textconsole.h"
43 
44 namespace Audio {
45 
46 enum {
47 	SOFTCLIP_THRESHOLD = 27600,
48 	HARDCLIP_THRESHOLD = 35716,
49 	MPA_MAX_CHANNELS = 2,
50 	MPA_FRAME_SIZE = 1152,
51 	FF_INPUT_BUFFER_PADDING_SIZE = 8
52 };
53 
54 typedef int8 sb_int8_array[2][30][64];
55 
56 struct QDM2SubPacket {
57 	int type;
58 	unsigned int size;
59 	const uint8 *data; // pointer to subpacket data (points to input data buffer, it's not a private copy)
60 };
61 
62 struct QDM2SubPNode {
63 	QDM2SubPacket *packet;
64 	struct QDM2SubPNode *next; // pointer to next packet in the list, NULL if leaf node
65 };
66 
67 struct QDM2Complex {
68 	float re;
69 	float im;
70 };
71 
72 struct FFTTone {
73 	float level;
74 	QDM2Complex *complex;
75 	const float *table;
76 	int phase;
77 	int phase_shift;
78 	int duration;
79 	short time_index;
80 	short cutoff;
81 };
82 
83 struct FFTCoefficient {
84 	int16 sub_packet;
85 	uint8 channel;
86 	int16 offset;
87 	int16 exp;
88 	uint8 phase;
89 };
90 
91 struct VLC {
92 	int32 bits;
93 	int16 (*table)[2]; // code, bits
94 	int32 table_size;
95 	int32 table_allocated;
96 };
97 
98 #include "common/pack-start.h"
99 struct QDM2FFT {
100 	QDM2Complex complex[MPA_MAX_CHANNELS][256];
101 } PACKED_STRUCT;
102 #include "common/pack-end.h"
103 
104 class QDM2Stream : public Codec {
105 public:
106 	QDM2Stream(Common::SeekableReadStream *extraData, DisposeAfterUse::Flag disposeExtraData);
107 	~QDM2Stream();
108 
109 	AudioStream *decodeFrame(Common::SeekableReadStream &stream);
110 
111 private:
112 	// Parameters from codec header, do not change during playback
113 	uint8 _channels;
114 	uint16 _sampleRate;
115 	uint16 _bitRate;
116 	uint16 _blockSize;  // Group
117 	uint16 _frameSize;  // FFT
118 	uint16 _packetSize; // Checksum
119 
120 	// Parameters built from header parameters, do not change during playback
121 	int _groupOrder;       // order of frame group
122 	int _fftOrder;         // order of FFT (actually fft order+1)
123 	int _fftFrameSize;     // size of fft frame, in components (1 comples = re + im)
124 	int _sFrameSize;        // size of data frame
125 	int _frequencyRange;
126 	int _subSampling;      // subsampling: 0=25%, 1=50%, 2=100% */
127 	int _coeffPerSbSelect; // selector for "num. of coeffs. per subband" tables. Can be 0, 1, 2
128 	int _cmTableSelect;    // selector for "coding method" tables. Can be 0, 1 (from init: 0-4)
129 
130 	// Packets and packet lists
131 	QDM2SubPacket _subPackets[16];    // the packets themselves
132 	QDM2SubPNode _subPacketListA[16]; // list of all packets
133 	QDM2SubPNode _subPacketListB[16]; // FFT packets B are on list
134 	int _subPacketsB;                 // number of packets on 'B' list
135 	QDM2SubPNode _subPacketListC[16]; // packets with errors?
136 	QDM2SubPNode _subPacketListD[16]; // DCT packets
137 
138 	// FFT and tones
139 	FFTTone _fftTones[1000];
140 	int _fftToneStart;
141 	int _fftToneEnd;
142 	FFTCoefficient _fftCoefs[1000];
143 	int _fftCoefsIndex;
144 	int _fftCoefsMinIndex[5];
145 	int _fftCoefsMaxIndex[5];
146 	int _fftLevelExp[6];
147 	Common::RDFT *_rdft;
148 	QDM2FFT _fft;
149 
150 	// I/O data
151 	uint8 *_compressedData;
152 	float _outputBuffer[1024];
153 
154 	// Synthesis filter
155 	int16 ff_mpa_synth_window[512];
156 	int16 _synthBuf[MPA_MAX_CHANNELS][512*2];
157 	int _synthBufOffset[MPA_MAX_CHANNELS];
158 	int32 _sbSamples[MPA_MAX_CHANNELS][128][32];
159 
160 	// Mixed temporary data used in decoding
161 	float _toneLevel[MPA_MAX_CHANNELS][30][64];
162 	int8 _codingMethod[MPA_MAX_CHANNELS][30][64];
163 	int8 _quantizedCoeffs[MPA_MAX_CHANNELS][10][8];
164 	int8 _toneLevelIdxBase[MPA_MAX_CHANNELS][30][8];
165 	int8 _toneLevelIdxHi1[MPA_MAX_CHANNELS][3][8][8];
166 	int8 _toneLevelIdxMid[MPA_MAX_CHANNELS][26][8];
167 	int8 _toneLevelIdxHi2[MPA_MAX_CHANNELS][26];
168 	int8 _toneLevelIdx[MPA_MAX_CHANNELS][30][64];
169 	int8 _toneLevelIdxTemp[MPA_MAX_CHANNELS][30][64];
170 
171 	// Flags
172 	bool _hasErrors;         // packet has errors
173 	int _superblocktype_2_3; // select fft tables and some algorithm based on superblock type
174 	int _doSynthFilter;      // used to perform or skip synthesis filter
175 
176 	uint8 _subPacket; // 0 to 15
177 	uint32 _superBlockStart;
178 	int _noiseIdx; // index for dithering noise table
179 
180 	byte _emptyBuffer[FF_INPUT_BUFFER_PADDING_SIZE];
181 
182 	VLC _vlcTabLevel;
183 	VLC _vlcTabDiff;
184 	VLC _vlcTabRun;
185 	VLC _fftLevelExpAltVlc;
186 	VLC _fftLevelExpVlc;
187 	VLC _fftStereoExpVlc;
188 	VLC _fftStereoPhaseVlc;
189 	VLC _vlcTabToneLevelIdxHi1;
190 	VLC _vlcTabToneLevelIdxMid;
191 	VLC _vlcTabToneLevelIdxHi2;
192 	VLC _vlcTabType30;
193 	VLC _vlcTabType34;
194 	VLC _vlcTabFftToneOffset[5];
195 	bool _vlcsInitialized;
196 	void initVlc(void);
197 
198 	uint16 _softclipTable[HARDCLIP_THRESHOLD - SOFTCLIP_THRESHOLD + 1];
199 	void softclipTableInit(void);
200 
201 	float _noiseTable[4096];
202 	byte _randomDequantIndex[256][5];
203 	byte _randomDequantType24[128][3];
204 	void rndTableInit(void);
205 
206 	float _noiseSamples[128];
207 	void initNoiseSamples(void);
208 
209 	void average_quantized_coeffs(void);
210 	void build_sb_samples_from_noise(int sb);
211 	void fix_coding_method_array(int sb, int channels, sb_int8_array coding_method);
212 	void fill_tone_level_array(int flag);
213 	void fill_coding_method_array(sb_int8_array tone_level_idx, sb_int8_array tone_level_idx_temp,
214 	                              sb_int8_array coding_method, int nb_channels,
215 	                              int c, int superblocktype_2_3, int cm_table_select);
216 	void synthfilt_build_sb_samples(Common::BitStreamMemory32LELSB *gb, int length, int sb_min, int sb_max);
217 	void init_quantized_coeffs_elem0(int8 *quantized_coeffs, Common::BitStreamMemory32LELSB *gb, int length);
218 	void init_tone_level_dequantization(Common::BitStreamMemory32LELSB *gb, int length);
219 	void process_subpacket_9(QDM2SubPNode *node);
220 	void process_subpacket_10(QDM2SubPNode *node, int length);
221 	void process_subpacket_11(QDM2SubPNode *node, int length);
222 	void process_subpacket_12(QDM2SubPNode *node, int length);
223 	void process_synthesis_subpackets(QDM2SubPNode *list);
224 	void qdm2_decode_super_block(void);
225 	void qdm2_fft_init_coefficient(int sub_packet, int offset, int duration,
226 	                               int channel, int exp, int phase);
227 	void qdm2_fft_decode_tones(int duration, Common::BitStreamMemory32LELSB *gb, int b);
228 	void qdm2_decode_fft_packets(void);
229 	void qdm2_fft_generate_tone(FFTTone *tone);
230 	void qdm2_fft_tone_synthesizer(uint8 sub_packet);
231 	void qdm2_calculate_fft(int channel);
232 	void qdm2_synthesis_filter(uint8 index);
233 	bool qdm2_decodeFrame(Common::SeekableReadStream &in, QueuingAudioStream *audioStream);
234 };
235 
236 #define QDM2_LIST_ADD(list, size, packet) \
237 	do { \
238 		if (size > 0) \
239 			list[size - 1].next = &list[size]; \
240 		list[size].packet = packet; \
241 		list[size].next = NULL; \
242 		size++; \
243 	} while(0)
244 
245 // Result is 8, 16 or 30
246 #define QDM2_SB_USED(subSampling) (((subSampling) >= 2) ? 30 : 8 << (subSampling))
247 
248 #define FIX_NOISE_IDX(noiseIdx) \
249 	if ((noiseIdx) >= 3840) \
250 		(noiseIdx) -= 3840 \
251 
252 #define SB_DITHERING_NOISE(sb, noiseIdx) (_noiseTable[(noiseIdx)++] * sb_noise_attenuation[(sb)])
253 
254 // half mpeg encoding window (full precision)
255 const int32 ff_mpa_enwindow[257] = {
256 	 0,    -1,    -1,    -1,    -1,    -1,    -1,    -2,
257 	-2,    -2,    -2,    -3,    -3,    -4,    -4,    -5,
258 	-5,    -6,    -7,    -7,    -8,    -9,   -10,   -11,
259    -13,   -14,   -16,   -17,   -19,   -21,   -24,   -26,
260    -29,   -31,   -35,   -38,   -41,   -45,   -49,   -53,
261    -58,   -63,   -68,   -73,   -79,   -85,   -91,   -97,
262   -104,  -111,  -117,  -125,  -132,  -139,  -147,  -154,
263   -161,  -169,  -176,  -183,  -190,  -196,  -202,  -208,
264    213,   218,   222,   225,   227,   228,   228,   227,
265    224,   221,   215,   208,   200,   189,   177,   163,
266    146,   127,   106,    83,    57,    29,    -2,   -36,
267    -72,  -111,  -153,  -197,  -244,  -294,  -347,  -401,
268   -459,  -519,  -581,  -645,  -711,  -779,  -848,  -919,
269   -991, -1064, -1137, -1210, -1283, -1356, -1428, -1498,
270  -1567, -1634, -1698, -1759, -1817, -1870, -1919, -1962,
271  -2001, -2032, -2057, -2075, -2085, -2087, -2080, -2063,
272   2037,  2000,  1952,  1893,  1822,  1739,  1644,  1535,
273   1414,  1280,  1131,   970,   794,   605,   402,   185,
274    -45,  -288,  -545,  -814, -1095, -1388, -1692, -2006,
275  -2330, -2663, -3004, -3351, -3705, -4063, -4425, -4788,
276  -5153, -5517, -5879, -6237, -6589, -6935, -7271, -7597,
277  -7910, -8209, -8491, -8755, -8998, -9219, -9416, -9585,
278  -9727, -9838, -9916, -9959, -9966, -9935, -9863, -9750,
279  -9592, -9389, -9139, -8840, -8492, -8092, -7640, -7134,
280   6574,  5959,  5288,  4561,  3776,  2935,  2037,  1082,
281 	70,  -998, -2122, -3300, -4533, -5818, -7154, -8540,
282  -9975,-11455,-12980,-14548,-16155,-17799,-19478,-21189,
283 -22929,-24694,-26482,-28289,-30112,-31947,-33791,-35640,
284 -37489,-39336,-41176,-43006,-44821,-46617,-48390,-50137,
285 -51853,-53534,-55178,-56778,-58333,-59838,-61289,-62684,
286 -64019,-65290,-66494,-67629,-68692,-69679,-70590,-71420,
287 -72169,-72835,-73415,-73908,-74313,-74630,-74856,-74992,
288  75038
289 };
290 
ff_mpa_synth_init(int16 * window)291 void ff_mpa_synth_init(int16 *window) {
292 	int i;
293 	int32 v;
294 
295 	// max = 18760, max sum over all 16 coefs : 44736
296 	for(i = 0; i < 257; i++) {
297 		v = ff_mpa_enwindow[i];
298 		v = (v + 2) >> 2;
299 		window[i] = v;
300 
301 		if ((i & 63) != 0)
302 			v = -v;
303 
304 		if (i != 0)
305 			window[512 - i] = v;
306 	}
307 }
308 
round_sample(int * sum)309 static inline uint16 round_sample(int *sum) {
310 	int sum1;
311 	sum1 = (*sum) >> 14;
312 	*sum &= (1 << 14)-1;
313 	if (sum1 < (-0x7fff - 1))
314 		sum1 = (-0x7fff - 1);
315 	if (sum1 > 0x7fff)
316 		sum1 = 0x7fff;
317 	return sum1;
318 }
319 
MULH(int a,int b)320 static inline int MULH(int a, int b) {
321 	return ((int64)(a) * (int64)(b))>>32;
322 }
323 
324 // signed 16x16 -> 32 multiply add accumulate
325 #define MACS(rt, ra, rb) rt += (ra) * (rb)
326 
327 #define MLSS(rt, ra, rb) ((rt) -= (ra) * (rb))
328 
329 #define SUM8(op, sum, w, p)\
330 {\
331 	op(sum, (w)[0 * 64], (p)[0 * 64]);\
332 	op(sum, (w)[1 * 64], (p)[1 * 64]);\
333 	op(sum, (w)[2 * 64], (p)[2 * 64]);\
334 	op(sum, (w)[3 * 64], (p)[3 * 64]);\
335 	op(sum, (w)[4 * 64], (p)[4 * 64]);\
336 	op(sum, (w)[5 * 64], (p)[5 * 64]);\
337 	op(sum, (w)[6 * 64], (p)[6 * 64]);\
338 	op(sum, (w)[7 * 64], (p)[7 * 64]);\
339 }
340 
341 #define SUM8P2(sum1, op1, sum2, op2, w1, w2, p) \
342 {\
343 	tmp_s = p[0 * 64];\
344 	op1(sum1, (w1)[0 * 64], tmp_s);\
345 	op2(sum2, (w2)[0 * 64], tmp_s);\
346 	tmp_s = p[1 * 64];\
347 	op1(sum1, (w1)[1 * 64], tmp_s);\
348 	op2(sum2, (w2)[1 * 64], tmp_s);\
349 	tmp_s = p[2 * 64];\
350 	op1(sum1, (w1)[2 * 64], tmp_s);\
351 	op2(sum2, (w2)[2 * 64], tmp_s);\
352 	tmp_s = p[3 * 64];\
353 	op1(sum1, (w1)[3 * 64], tmp_s);\
354 	op2(sum2, (w2)[3 * 64], tmp_s);\
355 	tmp_s = p[4 * 64];\
356 	op1(sum1, (w1)[4 * 64], tmp_s);\
357 	op2(sum2, (w2)[4 * 64], tmp_s);\
358 	tmp_s = p[5 * 64];\
359 	op1(sum1, (w1)[5 * 64], tmp_s);\
360 	op2(sum2, (w2)[5 * 64], tmp_s);\
361 	tmp_s = p[6 * 64];\
362 	op1(sum1, (w1)[6 * 64], tmp_s);\
363 	op2(sum2, (w2)[6 * 64], tmp_s);\
364 	tmp_s = p[7 * 64];\
365 	op1(sum1, (w1)[7 * 64], tmp_s);\
366 	op2(sum2, (w2)[7 * 64], tmp_s);\
367 }
368 
369 #define FIXHR(a) ((int)((a) * (1LL<<32) + 0.5))
370 
371 // tab[i][j] = 1.0 / (2.0 * cos(pi*(2*k+1) / 2^(6 - j)))
372 
373 // cos(i*pi/64)
374 
375 #define COS0_0  FIXHR(0.50060299823519630134/2)
376 #define COS0_1  FIXHR(0.50547095989754365998/2)
377 #define COS0_2  FIXHR(0.51544730992262454697/2)
378 #define COS0_3  FIXHR(0.53104259108978417447/2)
379 #define COS0_4  FIXHR(0.55310389603444452782/2)
380 #define COS0_5  FIXHR(0.58293496820613387367/2)
381 #define COS0_6  FIXHR(0.62250412303566481615/2)
382 #define COS0_7  FIXHR(0.67480834145500574602/2)
383 #define COS0_8  FIXHR(0.74453627100229844977/2)
384 #define COS0_9  FIXHR(0.83934964541552703873/2)
385 #define COS0_10 FIXHR(0.97256823786196069369/2)
386 #define COS0_11 FIXHR(1.16943993343288495515/4)
387 #define COS0_12 FIXHR(1.48416461631416627724/4)
388 #define COS0_13 FIXHR(2.05778100995341155085/8)
389 #define COS0_14 FIXHR(3.40760841846871878570/8)
390 #define COS0_15 FIXHR(10.19000812354805681150/32)
391 
392 #define COS1_0 FIXHR(0.50241928618815570551/2)
393 #define COS1_1 FIXHR(0.52249861493968888062/2)
394 #define COS1_2 FIXHR(0.56694403481635770368/2)
395 #define COS1_3 FIXHR(0.64682178335999012954/2)
396 #define COS1_4 FIXHR(0.78815462345125022473/2)
397 #define COS1_5 FIXHR(1.06067768599034747134/4)
398 #define COS1_6 FIXHR(1.72244709823833392782/4)
399 #define COS1_7 FIXHR(5.10114861868916385802/16)
400 
401 #define COS2_0 FIXHR(0.50979557910415916894/2)
402 #define COS2_1 FIXHR(0.60134488693504528054/2)
403 #define COS2_2 FIXHR(0.89997622313641570463/2)
404 #define COS2_3 FIXHR(2.56291544774150617881/8)
405 
406 #define COS3_0 FIXHR(0.54119610014619698439/2)
407 #define COS3_1 FIXHR(1.30656296487637652785/4)
408 
409 #define COS4_0 FIXHR(0.70710678118654752439/2)
410 
411 /* butterfly operator */
412 #define BF(a, b, c, s)\
413 {\
414 	tmp0 = tab[a] + tab[b];\
415 	tmp1 = tab[a] - tab[b];\
416 	tab[a] = tmp0;\
417 	tab[b] = MULH(tmp1<<(s), c);\
418 }
419 
420 #define BF1(a, b, c, d)\
421 {\
422 	BF(a, b, COS4_0, 1);\
423 	BF(c, d,-COS4_0, 1);\
424 	tab[c] += tab[d];\
425 }
426 
427 #define BF2(a, b, c, d)\
428 {\
429 	BF(a, b, COS4_0, 1);\
430 	BF(c, d,-COS4_0, 1);\
431 	tab[c] += tab[d];\
432 	tab[a] += tab[c];\
433 	tab[c] += tab[b];\
434 	tab[b] += tab[d];\
435 }
436 
437 #define ADD(a, b) tab[a] += tab[b]
438 
439 // DCT32 without 1/sqrt(2) coef zero scaling.
dct32(int32 * out,int32 * tab)440 static void dct32(int32 *out, int32 *tab) {
441 	int tmp0, tmp1;
442 
443 	// pass 1
444 	BF( 0, 31, COS0_0 , 1);
445 	BF(15, 16, COS0_15, 5);
446 	// pass 2
447 	BF( 0, 15, COS1_0 , 1);
448 	BF(16, 31,-COS1_0 , 1);
449 	// pass 1
450 	BF( 7, 24, COS0_7 , 1);
451 	BF( 8, 23, COS0_8 , 1);
452 	// pass 2
453 	BF( 7,  8, COS1_7 , 4);
454 	BF(23, 24,-COS1_7 , 4);
455 	// pass 3
456 	BF( 0,  7, COS2_0 , 1);
457 	BF( 8, 15,-COS2_0 , 1);
458 	BF(16, 23, COS2_0 , 1);
459 	BF(24, 31,-COS2_0 , 1);
460 	// pass 1
461 	BF( 3, 28, COS0_3 , 1);
462 	BF(12, 19, COS0_12, 2);
463 	// pass 2
464 	BF( 3, 12, COS1_3 , 1);
465 	BF(19, 28,-COS1_3 , 1);
466 	// pass 1
467 	BF( 4, 27, COS0_4 , 1);
468 	BF(11, 20, COS0_11, 2);
469 	// pass 2
470 	BF( 4, 11, COS1_4 , 1);
471 	BF(20, 27,-COS1_4 , 1);
472 	// pass 3
473 	BF( 3,  4, COS2_3 , 3);
474 	BF(11, 12,-COS2_3 , 3);
475 	BF(19, 20, COS2_3 , 3);
476 	BF(27, 28,-COS2_3 , 3);
477 	// pass 4
478 	BF( 0,  3, COS3_0 , 1);
479 	BF( 4,  7,-COS3_0 , 1);
480 	BF( 8, 11, COS3_0 , 1);
481 	BF(12, 15,-COS3_0 , 1);
482 	BF(16, 19, COS3_0 , 1);
483 	BF(20, 23,-COS3_0 , 1);
484 	BF(24, 27, COS3_0 , 1);
485 	BF(28, 31,-COS3_0 , 1);
486 
487 	// pass 1
488 	BF( 1, 30, COS0_1 , 1);
489 	BF(14, 17, COS0_14, 3);
490 	// pass 2
491 	BF( 1, 14, COS1_1 , 1);
492 	BF(17, 30,-COS1_1 , 1);
493 	// pass 1
494 	BF( 6, 25, COS0_6 , 1);
495 	BF( 9, 22, COS0_9 , 1);
496 	// pass 2
497 	BF( 6,  9, COS1_6 , 2);
498 	BF(22, 25,-COS1_6 , 2);
499 	// pass 3
500 	BF( 1,  6, COS2_1 , 1);
501 	BF( 9, 14,-COS2_1 , 1);
502 	BF(17, 22, COS2_1 , 1);
503 	BF(25, 30,-COS2_1 , 1);
504 
505 	// pass 1
506 	BF( 2, 29, COS0_2 , 1);
507 	BF(13, 18, COS0_13, 3);
508 	// pass 2
509 	BF( 2, 13, COS1_2 , 1);
510 	BF(18, 29,-COS1_2 , 1);
511 	// pass 1
512 	BF( 5, 26, COS0_5 , 1);
513 	BF(10, 21, COS0_10, 1);
514 	// pass 2
515 	BF( 5, 10, COS1_5 , 2);
516 	BF(21, 26,-COS1_5 , 2);
517 	// pass 3
518 	BF( 2,  5, COS2_2 , 1);
519 	BF(10, 13,-COS2_2 , 1);
520 	BF(18, 21, COS2_2 , 1);
521 	BF(26, 29,-COS2_2 , 1);
522 	// pass 4
523 	BF( 1,  2, COS3_1 , 2);
524 	BF( 5,  6,-COS3_1 , 2);
525 	BF( 9, 10, COS3_1 , 2);
526 	BF(13, 14,-COS3_1 , 2);
527 	BF(17, 18, COS3_1 , 2);
528 	BF(21, 22,-COS3_1 , 2);
529 	BF(25, 26, COS3_1 , 2);
530 	BF(29, 30,-COS3_1 , 2);
531 
532 	// pass 5
533 	BF1( 0,  1,  2,  3);
534 	BF2( 4,  5,  6,  7);
535 	BF1( 8,  9, 10, 11);
536 	BF2(12, 13, 14, 15);
537 	BF1(16, 17, 18, 19);
538 	BF2(20, 21, 22, 23);
539 	BF1(24, 25, 26, 27);
540 	BF2(28, 29, 30, 31);
541 
542 	// pass 6
543 	ADD( 8, 12);
544 	ADD(12, 10);
545 	ADD(10, 14);
546 	ADD(14,  9);
547 	ADD( 9, 13);
548 	ADD(13, 11);
549 	ADD(11, 15);
550 
551 	out[ 0] = tab[0];
552 	out[16] = tab[1];
553 	out[ 8] = tab[2];
554 	out[24] = tab[3];
555 	out[ 4] = tab[4];
556 	out[20] = tab[5];
557 	out[12] = tab[6];
558 	out[28] = tab[7];
559 	out[ 2] = tab[8];
560 	out[18] = tab[9];
561 	out[10] = tab[10];
562 	out[26] = tab[11];
563 	out[ 6] = tab[12];
564 	out[22] = tab[13];
565 	out[14] = tab[14];
566 	out[30] = tab[15];
567 
568 	ADD(24, 28);
569 	ADD(28, 26);
570 	ADD(26, 30);
571 	ADD(30, 25);
572 	ADD(25, 29);
573 	ADD(29, 27);
574 	ADD(27, 31);
575 
576 	out[ 1] = tab[16] + tab[24];
577 	out[17] = tab[17] + tab[25];
578 	out[ 9] = tab[18] + tab[26];
579 	out[25] = tab[19] + tab[27];
580 	out[ 5] = tab[20] + tab[28];
581 	out[21] = tab[21] + tab[29];
582 	out[13] = tab[22] + tab[30];
583 	out[29] = tab[23] + tab[31];
584 	out[ 3] = tab[24] + tab[20];
585 	out[19] = tab[25] + tab[21];
586 	out[11] = tab[26] + tab[22];
587 	out[27] = tab[27] + tab[23];
588 	out[ 7] = tab[28] + tab[18];
589 	out[23] = tab[29] + tab[19];
590 	out[15] = tab[30] + tab[17];
591 	out[31] = tab[31];
592 }
593 
594 // 32 sub band synthesis filter. Input: 32 sub band samples, Output:
595 // 32 samples.
596 // XXX: optimize by avoiding ring buffer usage
ff_mpa_synth_filter(int16 * synth_buf_ptr,int * synth_buf_offset,int16 * window,int * dither_state,int16 * samples,int incr,int32 sb_samples[32])597 void ff_mpa_synth_filter(int16 *synth_buf_ptr, int *synth_buf_offset,
598 						 int16 *window, int *dither_state,
599 						 int16 *samples, int incr,
600 						 int32 sb_samples[32])
601 {
602 	int16 *synth_buf;
603 	const int16 *w, *w2, *p;
604 	int j, offset;
605 	int16 *samples2;
606 	int32 tmp[32];
607 	int sum, sum2;
608 	int tmp_s;
609 
610 	offset = *synth_buf_offset;
611 	synth_buf = synth_buf_ptr + offset;
612 
613 	dct32(tmp, sb_samples);
614 	for(j = 0; j < 32; j++) {
615 		// NOTE: can cause a loss in precision if very high amplitude sound
616 		if (tmp[j] < (-0x7fff - 1))
617 			synth_buf[j] = (-0x7fff - 1);
618 		else if (tmp[j] > 0x7fff)
619 			synth_buf[j] = 0x7fff;
620 		else
621 			synth_buf[j] = tmp[j];
622 	}
623 
624 	// copy to avoid wrap
625 	memcpy(synth_buf + 512, synth_buf, 32 * sizeof(int16));
626 
627 	samples2 = samples + 31 * incr;
628 	w = window;
629 	w2 = window + 31;
630 
631 	sum = *dither_state;
632 	p = synth_buf + 16;
633 	SUM8(MACS, sum, w, p);
634 	p = synth_buf + 48;
635 	SUM8(MLSS, sum, w + 32, p);
636 	*samples = round_sample(&sum);
637 	samples += incr;
638 	w++;
639 
640 	// we calculate two samples at the same time to avoid one memory
641 	// access per two sample
642 	for(j = 1; j < 16; j++) {
643 		sum2 = 0;
644 		p = synth_buf + 16 + j;
645 		SUM8P2(sum, MACS, sum2, MLSS, w, w2, p);
646 		p = synth_buf + 48 - j;
647 		SUM8P2(sum, MLSS, sum2, MLSS, w + 32, w2 + 32, p);
648 
649 		*samples = round_sample(&sum);
650 		samples += incr;
651 		sum += sum2;
652 		*samples2 = round_sample(&sum);
653 		samples2 -= incr;
654 		w++;
655 		w2--;
656 	}
657 
658 	p = synth_buf + 32;
659 	SUM8(MLSS, sum, w + 32, p);
660 	*samples = round_sample(&sum);
661 	*dither_state= sum;
662 
663 	offset = (offset - 32) & 511;
664 	*synth_buf_offset = offset;
665 }
666 
667 /**
668  * parses a vlc code, faster then get_vlc()
669  * @param bits is the number of bits which will be read at once, must be
670  *             identical to nb_bits in init_vlc()
671  * @param max_depth is the number of times bits bits must be read to completely
672  *                  read the longest vlc code
673  *                  = (max_vlc_length + bits - 1) / bits
674  */
getVlc2(Common::BitStreamMemory32LELSB * s,int16 (* table)[2],int bits,int maxDepth)675 static int getVlc2(Common::BitStreamMemory32LELSB *s, int16 (*table)[2], int bits, int maxDepth) {
676 	int index = s->peekBits(bits);
677 	int code = table[index][0];
678 	int n = table[index][1];
679 
680 	if (maxDepth > 1 && n < 0) {
681 		s->skip(bits);
682 		int nbBits = -n;
683 		index = s->peekBits(-n) + code;
684 		code = table[index][0];
685 		n = table[index][1];
686 
687 		if (maxDepth > 2 && n < 0) {
688 			s->skip(nbBits);
689 			index = s->getBits(-n) + code;
690 			code = table[index][0];
691 			n = table[index][1];
692 		}
693 	}
694 
695 	s->skip(n);
696 	return code;
697 }
698 
allocTable(VLC * vlc,int size,int use_static)699 static int allocTable(VLC *vlc, int size, int use_static) {
700 	int index;
701 	int16 (*temp)[2] = NULL;
702 	index = vlc->table_size;
703 	vlc->table_size += size;
704 	if (vlc->table_size > vlc->table_allocated) {
705 		if(use_static)
706 			error("QDM2 cant do anything, init_vlc() is used with too little memory");
707 		vlc->table_allocated += (1 << vlc->bits);
708 		temp = (int16 (*)[2])realloc(vlc->table, sizeof(int16 *) * 2 * vlc->table_allocated);
709 		if (!temp) {
710 			free(vlc->table);
711 			vlc->table = NULL;
712 			return -1;
713 		}
714 		vlc->table = temp;
715 	}
716 	return index;
717 }
718 
719 #define GET_DATA(v, table, i, wrap, size)\
720 {\
721 	const uint8 *ptr = (const uint8 *)table + i * wrap;\
722 	switch(size) {\
723 		case 1:\
724 			v = *(const uint8 *)ptr;\
725 			break;\
726 		case 2:\
727 			v = *(const uint16 *)ptr;\
728 			break;\
729 		default:\
730 			v = *(const uint32 *)ptr;\
731 			break;\
732 	}\
733 }
734 
build_table(VLC * vlc,int table_nb_bits,int nb_codes,const void * bits,int bits_wrap,int bits_size,const void * codes,int codes_wrap,int codes_size,const void * symbols,int symbols_wrap,int symbols_size,int code_prefix,int n_prefix,int flags)735 static int build_table(VLC *vlc, int table_nb_bits,
736 					   int nb_codes,
737 					   const void *bits, int bits_wrap, int bits_size,
738 					   const void *codes, int codes_wrap, int codes_size,
739 					   const void *symbols, int symbols_wrap, int symbols_size,
740 					   int code_prefix, int n_prefix, int flags)
741 {
742 	int i, j, k, n, table_size, table_index, nb, n1, index, code_prefix2, symbol;
743 	uint32 code;
744 	int16 (*table)[2];
745 
746 	table_size = 1 << table_nb_bits;
747 	table_index = allocTable(vlc, table_size, flags & 4);
748 	if (table_index < 0)
749 		return -1;
750 	table = &vlc->table[table_index];
751 
752 	for(i = 0; i < table_size; i++) {
753 		table[i][1] = 0; //bits
754 		table[i][0] = -1; //codes
755 	}
756 
757 	// first pass: map codes and compute auxillary table sizes
758 	for(i = 0; i < nb_codes; i++) {
759 		GET_DATA(n, bits, i, bits_wrap, bits_size);
760 		GET_DATA(code, codes, i, codes_wrap, codes_size);
761 		// we accept tables with holes
762 		if (n <= 0)
763 			continue;
764 		if (!symbols)
765 			symbol = i;
766 		else
767 			GET_DATA(symbol, symbols, i, symbols_wrap, symbols_size);
768 		// if code matches the prefix, it is in the table
769 		n -= n_prefix;
770 		if(flags & 2)
771 			code_prefix2= code & (n_prefix>=32 ? 0xffffffff : (1 << n_prefix)-1);
772 		else
773 			code_prefix2= code >> n;
774 		if (n > 0 && code_prefix2 == code_prefix) {
775 			if (n <= table_nb_bits) {
776 				// no need to add another table
777 				j = (code << (table_nb_bits - n)) & (table_size - 1);
778 				nb = 1 << (table_nb_bits - n);
779 				for(k = 0; k < nb; k++) {
780 					if(flags & 2)
781 						j = (code >> n_prefix) + (k<<n);
782 					if (table[j][1] /*bits*/ != 0) {
783 						error("QDM2 incorrect codes");
784 						return -1;
785 					}
786 					table[j][1] = n; //bits
787 					table[j][0] = symbol;
788 					j++;
789 				}
790 			} else {
791 				n -= table_nb_bits;
792 				j = (code >> ((flags & 2) ? n_prefix : n)) & ((1 << table_nb_bits) - 1);
793 				// compute table size
794 				n1 = -table[j][1]; //bits
795 				if (n > n1)
796 					n1 = n;
797 				table[j][1] = -n1; //bits
798 			}
799 		}
800 	}
801 
802 	// second pass : fill auxillary tables recursively
803 	for(i = 0;i < table_size; i++) {
804 		n = table[i][1]; //bits
805 		if (n < 0) {
806 			n = -n;
807 			if (n > table_nb_bits) {
808 				n = table_nb_bits;
809 				table[i][1] = -n; //bits
810 			}
811 			index = build_table(vlc, n, nb_codes,
812 			                    bits, bits_wrap, bits_size,
813 			                    codes, codes_wrap, codes_size,
814 			                    symbols, symbols_wrap, symbols_size,
815 			                    (flags & 2) ? (code_prefix | (i << n_prefix)) : ((code_prefix << table_nb_bits) | i),
816 			                    n_prefix + table_nb_bits, flags);
817  			if (index < 0)
818 				return -1;
819 			// note: realloc has been done, so reload tables
820 			table = &vlc->table[table_index];
821 			table[i][0] = index; //code
822 		}
823 	}
824 	return table_index;
825 }
826 
827 /* Build VLC decoding tables suitable for use with get_vlc().
828 
829    'nb_bits' set thee decoding table size (2^nb_bits) entries. The
830    bigger it is, the faster is the decoding. But it should not be too
831    big to save memory and L1 cache. '9' is a good compromise.
832 
833    'nb_codes' : number of vlcs codes
834 
835    'bits' : table which gives the size (in bits) of each vlc code.
836 
837    'codes' : table which gives the bit pattern of of each vlc code.
838 
839    'symbols' : table which gives the values to be returned from get_vlc().
840 
841    'xxx_wrap' : give the number of bytes between each entry of the
842    'bits' or 'codes' tables.
843 
844    'xxx_size' : gives the number of bytes of each entry of the 'bits'
845    or 'codes' tables.
846 
847    'wrap' and 'size' allows to use any memory configuration and types
848    (byte/word/long) to store the 'bits', 'codes', and 'symbols' tables.
849 
850    'use_static' should be set to 1 for tables, which should be freed
851    with av_free_static(), 0 if free_vlc() will be used.
852 */
initVlcSparse(VLC * vlc,int nb_bits,int nb_codes,const void * bits,int bits_wrap,int bits_size,const void * codes,int codes_wrap,int codes_size,const void * symbols,int symbols_wrap,int symbols_size)853 void initVlcSparse(VLC *vlc, int nb_bits, int nb_codes,
854 		const void *bits, int bits_wrap, int bits_size,
855 		const void *codes, int codes_wrap, int codes_size,
856 		const void *symbols, int symbols_wrap, int symbols_size) {
857 	vlc->bits = nb_bits;
858 
859 	if (vlc->table_size && vlc->table_size == vlc->table_allocated) {
860 		return;
861 	} else if (vlc->table_size) {
862 		error("called on a partially initialized table");
863 	}
864 
865 	if (build_table(vlc, nb_bits, nb_codes,
866 	                bits, bits_wrap, bits_size,
867 	                codes, codes_wrap, codes_size,
868 	                symbols, symbols_wrap, symbols_size,
869 	                0, 0, 4 | 2) < 0) {
870 		free(vlc->table);
871 		return; // Error
872 	}
873 
874 	if(vlc->table_size != vlc->table_allocated)
875 		error("QDM2 needed %d had %d", vlc->table_size, vlc->table_allocated);
876 }
877 
softclipTableInit(void)878 void QDM2Stream::softclipTableInit(void) {
879 	uint16 i;
880 	double dfl = SOFTCLIP_THRESHOLD - 32767;
881 	float delta = 1.0 / -dfl;
882 
883 	for (i = 0; i < ARRAYSIZE(_softclipTable); i++)
884 		_softclipTable[i] = SOFTCLIP_THRESHOLD - ((int)(sin((float)i * delta) * dfl) & 0x0000FFFF);
885 }
886 
887 // random generated table
rndTableInit(void)888 void QDM2Stream::rndTableInit(void) {
889 	uint16 i;
890 	uint16 j;
891 	uint32 ldw, hdw;
892 	int64 tmp64_1;
893 	int64 random_seed = 0;
894 	float delta = 1.0 / 16384.0;
895 
896 	for(i = 0; i < ARRAYSIZE(_noiseTable); i++) {
897 		random_seed = random_seed * 214013 + 2531011;
898 		_noiseTable[i] = (delta * (float)(((int32)random_seed >> 16) & 0x00007FFF)- 1.0) * 1.3;
899 	}
900 
901 	for (i = 0; i < 256; i++) {
902 		random_seed = 81;
903 		ldw = i;
904 		for (j = 0; j < 5; j++) {
905 			_randomDequantIndex[i][j] = (uint8)((ldw / random_seed) & 0xFF);
906 			ldw = (uint32)ldw % (uint32)random_seed;
907 			tmp64_1 = (random_seed * 0x55555556);
908 			hdw = (uint32)(tmp64_1 >> 32);
909 			random_seed = (int64)(hdw + (ldw >> 31));
910 		}
911 	}
912 
913 	for (i = 0; i < 128; i++) {
914 		random_seed = 25;
915 		ldw = i;
916 		for (j = 0; j < 3; j++) {
917 			_randomDequantType24[i][j] = (uint8)((ldw / random_seed) & 0xFF);
918 			ldw = (uint32)ldw % (uint32)random_seed;
919 			tmp64_1 = (random_seed * 0x66666667);
920 			hdw = (uint32)(tmp64_1 >> 33);
921 			random_seed = hdw + (ldw >> 31);
922 		}
923 	}
924 }
925 
initNoiseSamples(void)926 void QDM2Stream::initNoiseSamples(void) {
927 	uint16 i;
928 	uint32 random_seed = 0;
929 	float delta = 1.0 / 16384.0;
930 
931 	for (i = 0; i < ARRAYSIZE(_noiseSamples); i++) {
932 		random_seed = random_seed * 214013 + 2531011;
933 		_noiseSamples[i] = (delta * (float)((random_seed >> 16) & 0x00007fff) - 1.0);
934 	}
935 }
936 
937 static const uint16 qdm2_vlc_offs[18] = {
938 	0, 260, 566, 598, 894, 1166, 1230, 1294, 1678, 1950, 2214, 2278, 2310, 2570, 2834, 3124, 3448, 3838
939 };
940 
initVlc(void)941 void QDM2Stream::initVlc(void) {
942 	static int16 qdm2_table[3838][2];
943 
944 	if (!_vlcsInitialized) {
945 		_vlcTabLevel.table = &qdm2_table[qdm2_vlc_offs[0]];
946 		_vlcTabLevel.table_allocated = qdm2_vlc_offs[1] - qdm2_vlc_offs[0];
947 		_vlcTabLevel.table_size = 0;
948 		initVlcSparse(&_vlcTabLevel, 8, 24,
949 			vlc_tab_level_huffbits, 1, 1,
950 			vlc_tab_level_huffcodes, 2, 2, NULL, 0, 0);
951 
952 		_vlcTabDiff.table = &qdm2_table[qdm2_vlc_offs[1]];
953 		_vlcTabDiff.table_allocated = qdm2_vlc_offs[2] - qdm2_vlc_offs[1];
954 		_vlcTabDiff.table_size = 0;
955 		initVlcSparse(&_vlcTabDiff, 8, 37,
956 			vlc_tab_diff_huffbits, 1, 1,
957 			vlc_tab_diff_huffcodes, 2, 2, NULL, 0, 0);
958 
959 		_vlcTabRun.table = &qdm2_table[qdm2_vlc_offs[2]];
960 		_vlcTabRun.table_allocated = qdm2_vlc_offs[3] - qdm2_vlc_offs[2];
961 		_vlcTabRun.table_size = 0;
962 		initVlcSparse(&_vlcTabRun, 5, 6,
963 			vlc_tab_run_huffbits, 1, 1,
964 			vlc_tab_run_huffcodes, 1, 1, NULL, 0, 0);
965 
966 		_fftLevelExpAltVlc.table = &qdm2_table[qdm2_vlc_offs[3]];
967 		_fftLevelExpAltVlc.table_allocated = qdm2_vlc_offs[4] - qdm2_vlc_offs[3];
968 		_fftLevelExpAltVlc.table_size = 0;
969 		initVlcSparse(&_fftLevelExpAltVlc, 8, 28,
970 			fft_level_exp_alt_huffbits, 1, 1,
971 			fft_level_exp_alt_huffcodes, 2, 2, NULL, 0, 0);
972 
973 		_fftLevelExpVlc.table = &qdm2_table[qdm2_vlc_offs[4]];
974 		_fftLevelExpVlc.table_allocated = qdm2_vlc_offs[5] - qdm2_vlc_offs[4];
975 		_fftLevelExpVlc.table_size = 0;
976 		initVlcSparse(&_fftLevelExpVlc, 8, 20,
977 			fft_level_exp_huffbits, 1, 1,
978 			fft_level_exp_huffcodes, 2, 2, NULL, 0, 0);
979 
980 		_fftStereoExpVlc.table = &qdm2_table[qdm2_vlc_offs[5]];
981 		_fftStereoExpVlc.table_allocated = qdm2_vlc_offs[6] - qdm2_vlc_offs[5];
982 		_fftStereoExpVlc.table_size = 0;
983 		initVlcSparse(&_fftStereoExpVlc, 6, 7,
984 			fft_stereo_exp_huffbits, 1, 1,
985 			fft_stereo_exp_huffcodes, 1, 1, NULL, 0, 0);
986 
987 		_fftStereoPhaseVlc.table = &qdm2_table[qdm2_vlc_offs[6]];
988 		_fftStereoPhaseVlc.table_allocated = qdm2_vlc_offs[7] - qdm2_vlc_offs[6];
989 		_fftStereoPhaseVlc.table_size = 0;
990 		initVlcSparse(&_fftStereoPhaseVlc, 6, 9,
991 			fft_stereo_phase_huffbits, 1, 1,
992 			fft_stereo_phase_huffcodes, 1, 1, NULL, 0, 0);
993 
994 		_vlcTabToneLevelIdxHi1.table = &qdm2_table[qdm2_vlc_offs[7]];
995 		_vlcTabToneLevelIdxHi1.table_allocated = qdm2_vlc_offs[8] - qdm2_vlc_offs[7];
996 		_vlcTabToneLevelIdxHi1.table_size = 0;
997 		initVlcSparse(&_vlcTabToneLevelIdxHi1, 8, 20,
998 			vlc_tab_tone_level_idx_hi1_huffbits, 1, 1,
999 			vlc_tab_tone_level_idx_hi1_huffcodes, 2, 2, NULL, 0, 0);
1000 
1001 		_vlcTabToneLevelIdxMid.table = &qdm2_table[qdm2_vlc_offs[8]];
1002 		_vlcTabToneLevelIdxMid.table_allocated = qdm2_vlc_offs[9] - qdm2_vlc_offs[8];
1003 		_vlcTabToneLevelIdxMid.table_size = 0;
1004 		initVlcSparse(&_vlcTabToneLevelIdxMid, 8, 24,
1005 			vlc_tab_tone_level_idx_mid_huffbits, 1, 1,
1006 			vlc_tab_tone_level_idx_mid_huffcodes, 2, 2, NULL, 0, 0);
1007 
1008 		_vlcTabToneLevelIdxHi2.table = &qdm2_table[qdm2_vlc_offs[9]];
1009 		_vlcTabToneLevelIdxHi2.table_allocated = qdm2_vlc_offs[10] - qdm2_vlc_offs[9];
1010 		_vlcTabToneLevelIdxHi2.table_size = 0;
1011 		initVlcSparse(&_vlcTabToneLevelIdxHi2, 8, 24,
1012 			vlc_tab_tone_level_idx_hi2_huffbits, 1, 1,
1013 			vlc_tab_tone_level_idx_hi2_huffcodes, 2, 2, NULL, 0, 0);
1014 
1015 		_vlcTabType30.table = &qdm2_table[qdm2_vlc_offs[10]];
1016 		_vlcTabType30.table_allocated = qdm2_vlc_offs[11] - qdm2_vlc_offs[10];
1017 		_vlcTabType30.table_size = 0;
1018 		initVlcSparse(&_vlcTabType30, 6, 9,
1019 			vlc_tab_type30_huffbits, 1, 1,
1020 			vlc_tab_type30_huffcodes, 1, 1, NULL, 0, 0);
1021 
1022 		_vlcTabType34.table = &qdm2_table[qdm2_vlc_offs[11]];
1023 		_vlcTabType34.table_allocated = qdm2_vlc_offs[12] - qdm2_vlc_offs[11];
1024 		_vlcTabType34.table_size = 0;
1025 		initVlcSparse(&_vlcTabType34, 5, 10,
1026 			vlc_tab_type34_huffbits, 1, 1,
1027 			vlc_tab_type34_huffcodes, 1, 1, NULL, 0, 0);
1028 
1029 		_vlcTabFftToneOffset[0].table = &qdm2_table[qdm2_vlc_offs[12]];
1030 		_vlcTabFftToneOffset[0].table_allocated = qdm2_vlc_offs[13] - qdm2_vlc_offs[12];
1031 		_vlcTabFftToneOffset[0].table_size = 0;
1032 		initVlcSparse(&_vlcTabFftToneOffset[0], 8, 23,
1033 			vlc_tab_fft_tone_offset_0_huffbits, 1, 1,
1034 			vlc_tab_fft_tone_offset_0_huffcodes, 2, 2, NULL, 0, 0);
1035 
1036 		_vlcTabFftToneOffset[1].table = &qdm2_table[qdm2_vlc_offs[13]];
1037 		_vlcTabFftToneOffset[1].table_allocated = qdm2_vlc_offs[14] - qdm2_vlc_offs[13];
1038 		_vlcTabFftToneOffset[1].table_size = 0;
1039 		initVlcSparse(&_vlcTabFftToneOffset[1], 8, 28,
1040 			vlc_tab_fft_tone_offset_1_huffbits, 1, 1,
1041 			vlc_tab_fft_tone_offset_1_huffcodes, 2, 2, NULL, 0, 0);
1042 
1043 		_vlcTabFftToneOffset[2].table = &qdm2_table[qdm2_vlc_offs[14]];
1044 		_vlcTabFftToneOffset[2].table_allocated = qdm2_vlc_offs[15] - qdm2_vlc_offs[14];
1045 		_vlcTabFftToneOffset[2].table_size = 0;
1046 		initVlcSparse(&_vlcTabFftToneOffset[2], 8, 32,
1047 			vlc_tab_fft_tone_offset_2_huffbits, 1, 1,
1048 			vlc_tab_fft_tone_offset_2_huffcodes, 2, 2, NULL, 0, 0);
1049 
1050 		_vlcTabFftToneOffset[3].table = &qdm2_table[qdm2_vlc_offs[15]];
1051 		_vlcTabFftToneOffset[3].table_allocated = qdm2_vlc_offs[16] - qdm2_vlc_offs[15];
1052 		_vlcTabFftToneOffset[3].table_size = 0;
1053 		initVlcSparse(&_vlcTabFftToneOffset[3], 8, 35,
1054 			vlc_tab_fft_tone_offset_3_huffbits, 1, 1,
1055 			vlc_tab_fft_tone_offset_3_huffcodes, 2, 2, NULL, 0, 0);
1056 
1057 		_vlcTabFftToneOffset[4].table = &qdm2_table[qdm2_vlc_offs[16]];
1058 		_vlcTabFftToneOffset[4].table_allocated = qdm2_vlc_offs[17] - qdm2_vlc_offs[16];
1059 		_vlcTabFftToneOffset[4].table_size = 0;
1060 		initVlcSparse(&_vlcTabFftToneOffset[4], 8, 38,
1061 			vlc_tab_fft_tone_offset_4_huffbits, 1, 1,
1062 			vlc_tab_fft_tone_offset_4_huffcodes, 2, 2, NULL, 0, 0);
1063 
1064 		_vlcsInitialized = true;
1065 	}
1066 }
1067 
QDM2Stream(Common::SeekableReadStream * extraData,DisposeAfterUse::Flag disposeExtraData)1068 QDM2Stream::QDM2Stream(Common::SeekableReadStream *extraData, DisposeAfterUse::Flag disposeExtraData) {
1069 	uint32 tmp;
1070 	int tmp_val;
1071 	int i;
1072 
1073 	debug(1, "QDM2Stream::QDM2Stream() Call");
1074 
1075 	_compressedData = NULL;
1076 	_subPacket = 0;
1077 	_superBlockStart = 0;
1078 	memset(_quantizedCoeffs, 0, sizeof(_quantizedCoeffs));
1079 	memset(_fftLevelExp, 0, sizeof(_fftLevelExp));
1080 	_noiseIdx = 0;
1081 	memset(_fftCoefsMinIndex, 0, sizeof(_fftCoefsMinIndex));
1082 	memset(_fftCoefsMaxIndex, 0, sizeof(_fftCoefsMaxIndex));
1083 	_fftToneStart = 0;
1084 	_fftToneEnd = 0;
1085 	for(i = 0; i < ARRAYSIZE(_subPacketListA); i++) {
1086 		_subPacketListA[i].packet = NULL;
1087 		_subPacketListA[i].next = NULL;
1088 	}
1089 	_subPacketsB = 0;
1090 	for(i = 0; i < ARRAYSIZE(_subPacketListB); i++) {
1091 		_subPacketListB[i].packet = NULL;
1092 		_subPacketListB[i].next = NULL;
1093 	}
1094 	for(i = 0; i < ARRAYSIZE(_subPacketListC); i++) {
1095 		_subPacketListC[i].packet = NULL;
1096 		_subPacketListC[i].next = NULL;
1097 	}
1098 	for(i = 0; i < ARRAYSIZE(_subPacketListD); i++) {
1099 		_subPacketListD[i].packet = NULL;
1100 		_subPacketListD[i].next = NULL;
1101 	}
1102 	memset(_synthBuf, 0, sizeof(_synthBuf));
1103 	memset(_synthBufOffset, 0, sizeof(_synthBufOffset));
1104 	memset(_sbSamples, 0, sizeof(_sbSamples));
1105 	memset(_outputBuffer, 0, sizeof(_outputBuffer));
1106 	_vlcsInitialized = false;
1107 	_superblocktype_2_3 = 0;
1108 	_hasErrors = false;
1109 
1110 	// The QDM2 "extra data" is really just an amalgam of three QuickTime
1111 	// atoms needed to correctly set up the decoder.
1112 
1113 	// Rewind extraData stream from any previous calls
1114 	extraData->seek(0, SEEK_SET);
1115 
1116 	// First, the frma atom
1117 	uint32 frmaSize = extraData->readUint32BE();
1118 	if (frmaSize != 12)
1119 		error("Invalid QDM2 frma atom");
1120 
1121 	if (extraData->readUint32BE() != MKTAG('f', 'r', 'm', 'a'))
1122 		error("Failed to find frma atom for QDM2");
1123 
1124 	uint32 version = extraData->readUint32BE();
1125 	if (version == MKTAG('Q', 'D', 'M', 'C'))
1126 		error("Unhandled QDMC sound");
1127 	else if (version != MKTAG('Q', 'D', 'M', '2'))
1128 		error("Failed to find QDM2 tag in frma atom");
1129 
1130 	// Second, the QDCA atom
1131 	uint32 qdcaSize = extraData->readUint32BE();
1132 	if (qdcaSize > (uint32)(extraData->size() - extraData->pos()))
1133 		error("Invalid QDM2 QDCA atom");
1134 
1135 	if (extraData->readUint32BE() != MKTAG('Q', 'D', 'C', 'A'))
1136 		error("Failed to find QDCA atom for QDM2");
1137 
1138 	extraData->readUint32BE(); // unknown
1139 
1140 	_channels = extraData->readUint32BE();
1141 	_sampleRate = extraData->readUint32BE();
1142 	_bitRate = extraData->readUint32BE();
1143 	_blockSize = extraData->readUint32BE();
1144 	_frameSize = extraData->readUint32BE();
1145 	_packetSize = extraData->readUint32BE();
1146 
1147 	// Third, we don't care about the QDCP atom
1148 
1149 	_fftOrder = Common::intLog2(_frameSize) + 1;
1150 	_fftFrameSize = 2 * _frameSize; // complex has two floats
1151 
1152 	// something like max decodable tones
1153 	_groupOrder = Common::intLog2(_blockSize) + 1;
1154 	_sFrameSize = _blockSize / 16; // 16 iterations per super block
1155 
1156 	_subSampling = _fftOrder - 7;
1157 	_frequencyRange = 255 / (1 << (2 - _subSampling));
1158 
1159 	switch (_subSampling * 2 + _channels - 1) {
1160 		case 0:
1161 			tmp = 40;
1162 			break;
1163 		case 1:
1164 			tmp = 48;
1165 			break;
1166 		case 2:
1167 			tmp = 56;
1168 			break;
1169 		case 3:
1170 			tmp = 72;
1171 			break;
1172 		case 4:
1173 			tmp = 80;
1174 			break;
1175 		case 5:
1176 			tmp = 100;
1177 			break;
1178 		default:
1179 			tmp = _subSampling;
1180 			break;
1181 	}
1182 
1183 	tmp_val = 0;
1184 	if ((tmp * 1000) < _bitRate)  tmp_val = 1;
1185 	if ((tmp * 1440) < _bitRate)  tmp_val = 2;
1186 	if ((tmp * 1760) < _bitRate)  tmp_val = 3;
1187 	if ((tmp * 2240) < _bitRate)  tmp_val = 4;
1188 	_cmTableSelect = tmp_val;
1189 
1190 	if (_subSampling == 0)
1191 		tmp = 7999;
1192 	else
1193 		tmp = ((-(_subSampling -1)) & 8000) + 20000;
1194 
1195 	if (tmp < 8000)
1196 		_coeffPerSbSelect = 0;
1197 	else if (tmp <= 16000)
1198 		_coeffPerSbSelect = 1;
1199 	else
1200 		_coeffPerSbSelect = 2;
1201 
1202 	if (_fftOrder < 7 || _fftOrder > 9)
1203 		error("QDM2Stream::QDM2Stream() Unsupported fft_order: %d", _fftOrder);
1204 
1205 	_rdft = new Common::RDFT(_fftOrder, Common::RDFT::IDFT_C2R);
1206 
1207 	initVlc();
1208 	ff_mpa_synth_init(ff_mpa_synth_window);
1209 	softclipTableInit();
1210 	rndTableInit();
1211 	initNoiseSamples();
1212 
1213 	_compressedData = new uint8[_packetSize + FF_INPUT_BUFFER_PADDING_SIZE];
1214 
1215 	if (disposeExtraData == DisposeAfterUse::YES)
1216 		delete extraData;
1217 }
1218 
~QDM2Stream()1219 QDM2Stream::~QDM2Stream() {
1220 	delete _rdft;
1221 	delete[] _compressedData;
1222 }
1223 
qdm2_get_vlc(Common::BitStreamMemory32LELSB * gb,VLC * vlc,int flag,int depth)1224 static int qdm2_get_vlc(Common::BitStreamMemory32LELSB *gb, VLC *vlc, int flag, int depth) {
1225 	int value = getVlc2(gb, vlc->table, vlc->bits, depth);
1226 
1227 	// stage-2, 3 bits exponent escape sequence
1228 	if (value-- == 0)
1229 		value = gb->getBits(gb->getBits(3) + 1);
1230 
1231 	// stage-3, optional
1232 	if (flag) {
1233 		int tmp = vlc_stage3_values[value];
1234 
1235 		if ((value & ~3) > 0)
1236 			tmp += gb->getBits(value >> 2);
1237 		value = tmp;
1238 	}
1239 
1240 	return value;
1241 }
1242 
qdm2_get_se_vlc(VLC * vlc,Common::BitStreamMemory32LELSB * gb,int depth)1243 static int qdm2_get_se_vlc(VLC *vlc, Common::BitStreamMemory32LELSB *gb, int depth)
1244 {
1245 	int value = qdm2_get_vlc(gb, vlc, 0, depth);
1246 
1247 	return (value & 1) ? ((value + 1) >> 1) : -(value >> 1);
1248 }
1249 
1250 /**
1251  * QDM2 checksum
1252  *
1253  * @param data      pointer to data to be checksum'ed
1254  * @param length    data length
1255  * @param value     checksum value
1256  *
1257  * @return          0 if checksum is OK
1258  */
qdm2_packet_checksum(const uint8 * data,int length,int value)1259 static uint16 qdm2_packet_checksum(const uint8 *data, int length, int value) {
1260 	int i;
1261 
1262 	for (i = 0; i < length; i++)
1263 		value -= data[i];
1264 
1265 	return (uint16)(value & 0xffff);
1266 }
1267 
1268 /**
1269  * Return node pointer to first packet of requested type in list.
1270  *
1271  * @param list    list of subpackets to be scanned
1272  * @param type    type of searched subpacket
1273  * @return        node pointer for subpacket if found, else NULL
1274  */
qdm2_search_subpacket_type_in_list(QDM2SubPNode * list,int type)1275 static QDM2SubPNode* qdm2_search_subpacket_type_in_list(QDM2SubPNode *list, int type)
1276 {
1277 	while (list != NULL && list->packet != NULL) {
1278 		if (list->packet->type == type)
1279 			return list;
1280 		list = list->next;
1281 	}
1282 	return NULL;
1283 }
1284 
1285 /**
1286  * Replaces 8 elements with their average value.
1287  * Called by qdm2_decode_superblock before starting subblock decoding.
1288  */
average_quantized_coeffs(void)1289 void QDM2Stream::average_quantized_coeffs(void) {
1290 	int i, j, n, ch, sum;
1291 
1292 	n = coeff_per_sb_for_avg[_coeffPerSbSelect][QDM2_SB_USED(_subSampling) - 1] + 1;
1293 
1294 	for (ch = 0; ch < _channels; ch++) {
1295 		for (i = 0; i < n; i++) {
1296 			sum = 0;
1297 
1298 			for (j = 0; j < 8; j++)
1299 				sum += _quantizedCoeffs[ch][i][j];
1300 
1301 			sum /= 8;
1302 			if (sum > 0)
1303 				sum--;
1304 
1305 			for (j = 0; j < 8; j++)
1306 				_quantizedCoeffs[ch][i][j] = sum;
1307 		}
1308 	}
1309 }
1310 
1311 /**
1312  * Build subband samples with noise weighted by q->tone_level.
1313  * Called by synthfilt_build_sb_samples.
1314  *
1315  * @param sb    subband index
1316  */
build_sb_samples_from_noise(int sb)1317 void QDM2Stream::build_sb_samples_from_noise(int sb) {
1318 	int ch, j;
1319 
1320 	FIX_NOISE_IDX(_noiseIdx);
1321 
1322 	if (!_channels)
1323 		return;
1324 
1325 	for (ch = 0; ch < _channels; ch++) {
1326 		for (j = 0; j < 64; j++) {
1327 			_sbSamples[ch][j * 2][sb] = (int32)(SB_DITHERING_NOISE(sb, _noiseIdx) * _toneLevel[ch][sb][j] + .5);
1328 			_sbSamples[ch][j * 2 + 1][sb] = (int32)(SB_DITHERING_NOISE(sb, _noiseIdx) * _toneLevel[ch][sb][j] + .5);
1329 		}
1330 	}
1331 }
1332 
1333 /**
1334  * Called while processing data from subpackets 11 and 12.
1335  * Used after making changes to coding_method array.
1336  *
1337  * @param sb               subband index
1338  * @param channels         number of channels
1339  * @param coding_method    q->coding_method[0][0][0]
1340  */
fix_coding_method_array(int sb,int channels,sb_int8_array coding_method)1341 void QDM2Stream::fix_coding_method_array(int sb, int channels, sb_int8_array coding_method)
1342 {
1343 	int j, k;
1344 	int ch;
1345 	int run, case_val;
1346 	int switchtable[23] = {0,5,1,5,5,5,5,5,2,5,5,5,5,5,5,5,3,5,5,5,5,5,4};
1347 
1348 	for (ch = 0; ch < channels; ch++) {
1349 		for (j = 0; j < 64; ) {
1350 			if ((coding_method[ch][sb][j] - 8) > 22) {
1351 				run = 1;
1352 				case_val = 8;
1353 			} else {
1354 				switch (switchtable[coding_method[ch][sb][j]-8]) {
1355 					case 0: run = 10; case_val = 10; break;
1356 					case 1: run = 1; case_val = 16; break;
1357 					case 2: run = 5; case_val = 24; break;
1358 					case 3: run = 3; case_val = 30; break;
1359 					case 4: run = 1; case_val = 30; break;
1360 					case 5: run = 1; case_val = 8; break;
1361 					default: run = 1; case_val = 8; break;
1362 				}
1363 			}
1364 			for (k = 0; k < run; k++)
1365 				if (j + k < 128)
1366 					if (coding_method[ch][sb + (j + k) / 64][(j + k) % 64] > coding_method[ch][sb][j])
1367 						if (k > 0) {
1368 							warning("QDM2 Untested Code: not debugged, almost never used");
1369 							memset(&coding_method[ch][sb][j + k], case_val, k * sizeof(int8));
1370 							memset(&coding_method[ch][sb][j + k], case_val, 3 * sizeof(int8));
1371 						}
1372 			j += run;
1373 		}
1374 	}
1375 }
1376 
1377 /**
1378  * Related to synthesis filter
1379  * Called by process_subpacket_10
1380  *
1381  * @param flag    1 if called after getting data from subpacket 10, 0 if no subpacket 10
1382  */
fill_tone_level_array(int flag)1383 void QDM2Stream::fill_tone_level_array(int flag) {
1384 	int i, sb, ch, sb_used;
1385 	int tmp, tab;
1386 
1387 	// This should never happen
1388 	if (_channels <= 0)
1389 		return;
1390 
1391 	for (ch = 0; ch < _channels; ch++) {
1392 		for (sb = 0; sb < 30; sb++) {
1393 			for (i = 0; i < 8; i++) {
1394 				if ((tab=coeff_per_sb_for_dequant[_coeffPerSbSelect][sb]) < (last_coeff[_coeffPerSbSelect] - 1))
1395 					tmp = _quantizedCoeffs[ch][tab + 1][i] * dequant_table[_coeffPerSbSelect][tab + 1][sb]+
1396 					      _quantizedCoeffs[ch][tab][i] * dequant_table[_coeffPerSbSelect][tab][sb];
1397 				else
1398 					tmp = _quantizedCoeffs[ch][tab][i] * dequant_table[_coeffPerSbSelect][tab][sb];
1399 				if(tmp < 0)
1400 					tmp += 0xff;
1401 				_toneLevelIdxBase[ch][sb][i] = (tmp / 256) & 0xff;
1402 			}
1403 		}
1404 	}
1405 
1406 	sb_used = QDM2_SB_USED(_subSampling);
1407 
1408 	if ((_superblocktype_2_3 != 0) && !flag) {
1409 		for (sb = 0; sb < sb_used; sb++) {
1410 			for (ch = 0; ch < _channels; ch++) {
1411 				for (i = 0; i < 64; i++) {
1412 					_toneLevelIdx[ch][sb][i] = _toneLevelIdxBase[ch][sb][i / 8];
1413 					if (_toneLevelIdx[ch][sb][i] < 0)
1414 						_toneLevel[ch][sb][i] = 0;
1415 					else
1416 						_toneLevel[ch][sb][i] = fft_tone_level_table[0][_toneLevelIdx[ch][sb][i] & 0x3f];
1417 				}
1418 			}
1419 		}
1420 	} else {
1421 		tab = _superblocktype_2_3 ? 0 : 1;
1422 		for (sb = 0; sb < sb_used; sb++) {
1423 			if ((sb >= 4) && (sb <= 23)) {
1424 				for (ch = 0; ch < _channels; ch++) {
1425 					for (i = 0; i < 64; i++) {
1426 						tmp = _toneLevelIdxBase[ch][sb][i / 8] -
1427 						      _toneLevelIdxHi1[ch][sb / 8][i / 8][i % 8] -
1428 						      _toneLevelIdxMid[ch][sb - 4][i / 8] -
1429 						      _toneLevelIdxHi2[ch][sb - 4];
1430 						_toneLevelIdx[ch][sb][i] = tmp & 0xff;
1431 						if ((tmp < 0) || (!_superblocktype_2_3 && !tmp))
1432 							_toneLevel[ch][sb][i] = 0;
1433 						else
1434 							_toneLevel[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
1435 					}
1436 				}
1437 			} else {
1438 				if (sb > 4) {
1439 					for (ch = 0; ch < _channels; ch++) {
1440 						for (i = 0; i < 64; i++) {
1441 							tmp = _toneLevelIdxBase[ch][sb][i / 8] -
1442 							      _toneLevelIdxHi1[ch][2][i / 8][i % 8] -
1443 							      _toneLevelIdxHi2[ch][sb - 4];
1444 							_toneLevelIdx[ch][sb][i] = tmp & 0xff;
1445 							if ((tmp < 0) || (!_superblocktype_2_3 && !tmp))
1446 								_toneLevel[ch][sb][i] = 0;
1447 							else
1448 								_toneLevel[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
1449 						}
1450 					}
1451 				} else {
1452 					for (ch = 0; ch < _channels; ch++) {
1453 						for (i = 0; i < 64; i++) {
1454 							tmp = _toneLevelIdx[ch][sb][i] = _toneLevelIdxBase[ch][sb][i / 8];
1455 							if ((tmp < 0) || (!_superblocktype_2_3 && !tmp))
1456 								_toneLevel[ch][sb][i] = 0;
1457 							else
1458 								_toneLevel[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
1459 						}
1460 					}
1461 				}
1462 			}
1463 		}
1464 	}
1465 }
1466 
1467 /**
1468  * Related to synthesis filter
1469  * Called by process_subpacket_11
1470  * c is built with data from subpacket 11
1471  * Most of this function is used only if superblock_type_2_3 == 0, never seen it in samples
1472  *
1473  * @param tone_level_idx
1474  * @param tone_level_idx_temp
1475  * @param coding_method        q->coding_method[0][0][0]
1476  * @param nb_channels          number of channels
1477  * @param c                    coming from subpacket 11, passed as 8*c
1478  * @param superblocktype_2_3   flag based on superblock packet type
1479  * @param cm_table_select      q->cm_table_select
1480  */
fill_coding_method_array(sb_int8_array tone_level_idx,sb_int8_array tone_level_idx_temp,sb_int8_array coding_method,int nb_channels,int c,int superblocktype_2_3,int cm_table_select)1481 void QDM2Stream::fill_coding_method_array(sb_int8_array tone_level_idx, sb_int8_array tone_level_idx_temp,
1482 				sb_int8_array coding_method, int nb_channels,
1483 				int c, int superblocktype_2_3, int cm_table_select) {
1484 	int ch, sb, j;
1485 	int tmp, acc, esp_40, comp;
1486 	int add1, add2, add3, add4;
1487 	int64 multres;
1488 
1489 	// This should never happen
1490 	if (nb_channels <= 0)
1491 		return;
1492 	if (!superblocktype_2_3) {
1493 		warning("QDM2 This case is untested, no samples available");
1494 		for (ch = 0; ch < nb_channels; ch++) {
1495 			for (sb = 0; sb < 30; sb++) {
1496 				for (j = 1; j < 63; j++) {  // The loop only iterates to 63 so the code doesn't overflow the buffer
1497 					add1 = tone_level_idx[ch][sb][j] - 10;
1498 					if (add1 < 0)
1499 						add1 = 0;
1500 					add2 = add3 = add4 = 0;
1501 					if (sb > 1) {
1502 						add2 = tone_level_idx[ch][sb - 2][j] + tone_level_idx_offset_table[sb][0] - 6;
1503 						if (add2 < 0)
1504 							add2 = 0;
1505 					}
1506 					if (sb > 0) {
1507 						add3 = tone_level_idx[ch][sb - 1][j] + tone_level_idx_offset_table[sb][1] - 6;
1508 						if (add3 < 0)
1509 							add3 = 0;
1510 					}
1511 					if (sb < 29) {
1512 						add4 = tone_level_idx[ch][sb + 1][j] + tone_level_idx_offset_table[sb][3] - 6;
1513 						if (add4 < 0)
1514 							add4 = 0;
1515 					}
1516 					tmp = tone_level_idx[ch][sb][j + 1] * 2 - add4 - add3 - add2 - add1;
1517 					if (tmp < 0)
1518 						tmp = 0;
1519 					tone_level_idx_temp[ch][sb][j + 1] = tmp & 0xff;
1520 				}
1521 				tone_level_idx_temp[ch][sb][0] = tone_level_idx_temp[ch][sb][1];
1522 			}
1523 		}
1524 		acc = 0;
1525 		for (ch = 0; ch < nb_channels; ch++)
1526 			for (sb = 0; sb < 30; sb++)
1527 				for (j = 0; j < 64; j++)
1528 					acc += tone_level_idx_temp[ch][sb][j];
1529 
1530 		multres = 0x66666667 * (acc * 10);
1531 		esp_40 = (multres >> 32) / 8 + ((multres & 0xffffffff) >> 31);
1532 		for (ch = 0;  ch < nb_channels; ch++) {
1533 			for (sb = 0; sb < 30; sb++) {
1534 				for (j = 0; j < 64; j++) {
1535 					comp = tone_level_idx_temp[ch][sb][j]* esp_40 * 10;
1536 					if (comp < 0)
1537 						comp += 0xff;
1538 					comp /= 256; // signed shift
1539 					switch(sb) {
1540 						case 0:
1541 							if (comp < 30)
1542 								comp = 30;
1543 							comp += 15;
1544 							break;
1545 						case 1:
1546 							if (comp < 24)
1547 								comp = 24;
1548 							comp += 10;
1549 							break;
1550 						case 2:
1551 						case 3:
1552 						case 4:
1553 							if (comp < 16)
1554 								comp = 16;
1555 							break;
1556 						default:
1557 							break;
1558 					}
1559 					if (comp <= 5)
1560 						tmp = 0;
1561 					else if (comp <= 10)
1562 						tmp = 10;
1563 					else if (comp <= 16)
1564 						tmp = 16;
1565 					else if (comp <= 24)
1566 						tmp = -1;
1567 					else
1568 						tmp = 0;
1569 					coding_method[ch][sb][j] = ((tmp & 0xfffa) + 30 )& 0xff;
1570 				}
1571 			}
1572 		}
1573 		for (sb = 0; sb < 30; sb++)
1574 			fix_coding_method_array(sb, nb_channels, coding_method);
1575 		for (ch = 0; ch < nb_channels; ch++) {
1576 			for (sb = 0; sb < 30; sb++) {
1577 				for (j = 0; j < 64; j++) {
1578 					if (sb >= 10) {
1579 						if (coding_method[ch][sb][j] < 10)
1580 							coding_method[ch][sb][j] = 10;
1581 					} else {
1582 						if (sb >= 2) {
1583 							if (coding_method[ch][sb][j] < 16)
1584 								coding_method[ch][sb][j] = 16;
1585 						} else {
1586 							if (coding_method[ch][sb][j] < 30)
1587 								coding_method[ch][sb][j] = 30;
1588 						}
1589 					}
1590 				}
1591 			}
1592 		}
1593 	} else { // superblocktype_2_3 != 0
1594 		for (ch = 0; ch < nb_channels; ch++)
1595 			for (sb = 0; sb < 30; sb++)
1596 				for (j = 0; j < 64; j++)
1597 					coding_method[ch][sb][j] = coding_method_table[cm_table_select][sb];
1598 	}
1599 }
1600 
1601 /**
1602  *
1603  * Called by process_subpacket_11 to process more data from subpacket 11 with sb 0-8
1604  * Called by process_subpacket_12 to process data from subpacket 12 with sb 8-sb_used
1605  *
1606  * @param gb        bitreader context
1607  * @param length    packet length in bits
1608  * @param sb_min    lower subband processed (sb_min included)
1609  * @param sb_max    higher subband processed (sb_max excluded)
1610  */
synthfilt_build_sb_samples(Common::BitStreamMemory32LELSB * gb,int length,int sb_min,int sb_max)1611 void QDM2Stream::synthfilt_build_sb_samples(Common::BitStreamMemory32LELSB *gb, int length, int sb_min, int sb_max) {
1612 	int sb, j, k, n, ch, run, channels;
1613 	int joined_stereo, zero_encoding, chs;
1614 	int type34_first;
1615 	float type34_div = 0;
1616 	float type34_predictor;
1617 	float samples[10], sign_bits[16];
1618 
1619 	if (length == 0) {
1620 		// If no data use noise
1621 		for (sb = sb_min; sb < sb_max; sb++)
1622 			build_sb_samples_from_noise(sb);
1623 
1624 		return;
1625 	}
1626 
1627 	for (sb = sb_min; sb < sb_max; sb++) {
1628 		FIX_NOISE_IDX(_noiseIdx);
1629 
1630 		channels = _channels;
1631 
1632 		if (_channels <= 1 || sb < 12)
1633 			joined_stereo = 0;
1634 		else if (sb >= 24)
1635 			joined_stereo = 1;
1636 		else
1637 			joined_stereo = ((length - gb->pos()) >= 1) ? gb->getBit() : 0;
1638 
1639 		if (joined_stereo) {
1640 			if ((length - gb->pos()) >= 16)
1641 				for (j = 0; j < 16; j++)
1642 					sign_bits[j] = gb->getBit();
1643 
1644 			for (j = 0; j < 64; j++)
1645 				if (_codingMethod[1][sb][j] > _codingMethod[0][sb][j])
1646 					_codingMethod[0][sb][j] = _codingMethod[1][sb][j];
1647 
1648 			fix_coding_method_array(sb, _channels, _codingMethod);
1649 			channels = 1;
1650 		}
1651 
1652 		for (ch = 0; ch < channels; ch++) {
1653 			zero_encoding = ((length - gb->pos()) >= 1) ? gb->getBit() : 0;
1654 			type34_predictor = 0.0;
1655 			type34_first = 1;
1656 
1657 			for (j = 0; j < 128; ) {
1658 				switch (_codingMethod[ch][sb][j / 2]) {
1659 					case 8:
1660 						if ((length - gb->pos()) >= 10) {
1661 							if (zero_encoding) {
1662 								for (k = 0; k < 5; k++) {
1663 									if ((j + 2 * k) >= 128)
1664 										break;
1665 									samples[2 * k] = gb->getBit() ? dequant_1bit[joined_stereo][2 * gb->getBit()] : 0;
1666 								}
1667 							} else {
1668 								n = gb->getBits(8);
1669 								for (k = 0; k < 5; k++)
1670 									samples[2 * k] = dequant_1bit[joined_stereo][_randomDequantIndex[n][k]];
1671 							}
1672 							for (k = 0; k < 5; k++)
1673 								samples[2 * k + 1] = SB_DITHERING_NOISE(sb, _noiseIdx);
1674 						} else {
1675 							for (k = 0; k < 10; k++)
1676 								samples[k] = SB_DITHERING_NOISE(sb, _noiseIdx);
1677 						}
1678 						run = 10;
1679 						break;
1680 
1681 					case 10:
1682 						if ((length - gb->pos()) >= 1) {
1683 							double f = 0.81;
1684 
1685 							if (gb->getBit())
1686 								f = -f;
1687 							f -= _noiseSamples[((sb + 1) * (j +5 * ch + 1)) & 127] * 9.0 / 40.0;
1688 							samples[0] = f;
1689 						} else {
1690 							samples[0] = SB_DITHERING_NOISE(sb, _noiseIdx);
1691 						}
1692 						run = 1;
1693 						break;
1694 
1695 					case 16:
1696 						if ((length - gb->pos()) >= 10) {
1697 							if (zero_encoding) {
1698 								for (k = 0; k < 5; k++) {
1699 									if ((j + k) >= 128)
1700 										break;
1701 									samples[k] = (gb->getBit() == 0) ? 0 : dequant_1bit[joined_stereo][2 * gb->getBit()];
1702 								}
1703 							} else {
1704 								n = gb->getBits(8);
1705 								for (k = 0; k < 5; k++)
1706 									samples[k] = dequant_1bit[joined_stereo][_randomDequantIndex[n][k]];
1707 							}
1708 						} else {
1709 							for (k = 0; k < 5; k++)
1710 								samples[k] = SB_DITHERING_NOISE(sb, _noiseIdx);
1711 						}
1712 						run = 5;
1713 						break;
1714 
1715 					case 24:
1716 						if ((length - gb->pos()) >= 7) {
1717 							n = gb->getBits(7);
1718 							for (k = 0; k < 3; k++)
1719 								samples[k] = (_randomDequantType24[n][k] - 2.0) * 0.5;
1720 						} else {
1721 							for (k = 0; k < 3; k++)
1722 								samples[k] = SB_DITHERING_NOISE(sb, _noiseIdx);
1723 						}
1724 						run = 3;
1725 						break;
1726 
1727 					case 30:
1728 						if ((length - gb->pos()) >= 4)
1729 							samples[0] = type30_dequant[qdm2_get_vlc(gb, &_vlcTabType30, 0, 1)];
1730 						else
1731 							samples[0] = SB_DITHERING_NOISE(sb, _noiseIdx);
1732 
1733 						run = 1;
1734 						break;
1735 
1736 					case 34:
1737 						if ((length - gb->pos()) >= 7) {
1738 							if (type34_first) {
1739 								type34_div = (float)(1 << gb->getBits(2));
1740 								samples[0] = ((float)gb->getBits(5) - 16.0) / 15.0;
1741 								type34_predictor = samples[0];
1742 								type34_first = 0;
1743 							} else {
1744 								samples[0] = type34_delta[qdm2_get_vlc(gb, &_vlcTabType34, 0, 1)] / type34_div + type34_predictor;
1745 								type34_predictor = samples[0];
1746 							}
1747 						} else {
1748 							samples[0] = SB_DITHERING_NOISE(sb, _noiseIdx);
1749 						}
1750 						run = 1;
1751 						break;
1752 
1753 					default:
1754 						samples[0] = SB_DITHERING_NOISE(sb, _noiseIdx);
1755 						run = 1;
1756 						break;
1757 				}
1758 
1759 				if (joined_stereo) {
1760 					float tmp[10][MPA_MAX_CHANNELS];
1761 
1762 					for (k = 0; k < run; k++) {
1763 						tmp[k][0] = samples[k];
1764 						tmp[k][1] = (sign_bits[(j + k) / 8]) ? -samples[k] : samples[k];
1765 					}
1766 					for (chs = 0; chs < _channels; chs++)
1767 						for (k = 0; k < run; k++)
1768 							if ((j + k) < 128)
1769 								_sbSamples[chs][j + k][sb] = (int32)(_toneLevel[chs][sb][((j + k)/2)] * tmp[k][chs] + .5);
1770 				} else {
1771 					for (k = 0; k < run; k++)
1772 						if ((j + k) < 128)
1773 							_sbSamples[ch][j + k][sb] = (int32)(_toneLevel[ch][sb][(j + k)/2] * samples[k] + .5);
1774 				}
1775 
1776 				j += run;
1777 			} // j loop
1778 		} // channel loop
1779 	} // subband loop
1780 }
1781 
1782 /**
1783  * Init the first element of a channel in quantized_coeffs with data from packet 10 (quantized_coeffs[ch][0]).
1784  * This is similar to process_subpacket_9, but for a single channel and for element [0]
1785  * same VLC tables as process_subpacket_9 are used.
1786  *
1787  * @param quantized_coeffs    pointer to quantized_coeffs[ch][0]
1788  * @param gb        bitreader context
1789  * @param length    packet length in bits
1790  */
init_quantized_coeffs_elem0(int8 * quantized_coeffs,Common::BitStreamMemory32LELSB * gb,int length)1791 void QDM2Stream::init_quantized_coeffs_elem0(int8 *quantized_coeffs, Common::BitStreamMemory32LELSB *gb, int length) {
1792 	int i, k, run, level, diff;
1793 
1794 	if ((length - gb->pos()) < 16)
1795 		return;
1796 	level = qdm2_get_vlc(gb, &_vlcTabLevel, 0, 2);
1797 
1798 	quantized_coeffs[0] = level;
1799 
1800 	for (i = 0; i < 7; ) {
1801 		if ((length - gb->pos()) < 16)
1802 			break;
1803 		run = qdm2_get_vlc(gb, &_vlcTabRun, 0, 1) + 1;
1804 
1805 		if ((length - gb->pos()) < 16)
1806 			break;
1807 		diff = qdm2_get_se_vlc(&_vlcTabDiff, gb, 2);
1808 
1809 		for (k = 1; k <= run; k++)
1810 			quantized_coeffs[i + k] = (level + ((k * diff) / run));
1811 
1812 		level += diff;
1813 		i += run;
1814 	}
1815 }
1816 
1817 /**
1818  * Related to synthesis filter, process data from packet 10
1819  * Init part of quantized_coeffs via function init_quantized_coeffs_elem0
1820  * Init tone_level_idx_hi1, tone_level_idx_hi2, tone_level_idx_mid with data from packet 10
1821  *
1822  * @param gb        bitreader context
1823  * @param length    packet length in bits
1824  */
init_tone_level_dequantization(Common::BitStreamMemory32LELSB * gb,int length)1825 void QDM2Stream::init_tone_level_dequantization(Common::BitStreamMemory32LELSB *gb, int length) {
1826 	int sb, j, k, n, ch;
1827 
1828 	for (ch = 0; ch < _channels; ch++) {
1829 		init_quantized_coeffs_elem0(_quantizedCoeffs[ch][0], gb, length);
1830 
1831 		if ((length - gb->pos()) < 16) {
1832 			memset(_quantizedCoeffs[ch][0], 0, 8);
1833 			break;
1834 		}
1835 	}
1836 
1837 	n = _subSampling + 1;
1838 
1839 	for (sb = 0; sb < n; sb++)
1840 		for (ch = 0; ch < _channels; ch++)
1841 			for (j = 0; j < 8; j++) {
1842 				if ((length - gb->pos()) < 1)
1843 					break;
1844 				if (gb->getBit()) {
1845 					for (k=0; k < 8; k++) {
1846 						if ((length - gb->pos()) < 16)
1847 							break;
1848 						_toneLevelIdxHi1[ch][sb][j][k] = qdm2_get_vlc(gb, &_vlcTabToneLevelIdxHi1, 0, 2);
1849 					}
1850 				} else {
1851 					for (k=0; k < 8; k++)
1852 						_toneLevelIdxHi1[ch][sb][j][k] = 0;
1853 				}
1854 			}
1855 
1856 	n = QDM2_SB_USED(_subSampling) - 4;
1857 
1858 	for (sb = 0; sb < n; sb++)
1859 		for (ch = 0; ch < _channels; ch++) {
1860 			if ((length - gb->pos()) < 16)
1861 				break;
1862 			_toneLevelIdxHi2[ch][sb] = qdm2_get_vlc(gb, &_vlcTabToneLevelIdxHi2, 0, 2);
1863 			if (sb > 19)
1864 				_toneLevelIdxHi2[ch][sb] -= 16;
1865 			else
1866 				for (j = 0; j < 8; j++)
1867 					_toneLevelIdxMid[ch][sb][j] = -16;
1868 		}
1869 
1870 	n = QDM2_SB_USED(_subSampling) - 5;
1871 
1872 	for (sb = 0; sb < n; sb++) {
1873 		for (ch = 0; ch < _channels; ch++) {
1874 			for (j = 0; j < 8; j++) {
1875 				if ((length - gb->pos()) < 16)
1876 					break;
1877 				_toneLevelIdxMid[ch][sb][j] = qdm2_get_vlc(gb, &_vlcTabToneLevelIdxMid, 0, 2) - 32;
1878 			}
1879 		}
1880 	}
1881 }
1882 
1883 /**
1884  * Process subpacket 9, init quantized_coeffs with data from it
1885  *
1886  * @param node    pointer to node with packet
1887  */
process_subpacket_9(QDM2SubPNode * node)1888 void QDM2Stream::process_subpacket_9(QDM2SubPNode *node) {
1889 	int i, j, k, n, ch, run, level, diff;
1890 
1891 	Common::BitStreamMemoryStream d(node->packet->data, node->packet->size + FF_INPUT_BUFFER_PADDING_SIZE);
1892 	Common::BitStreamMemory32LELSB gb(&d);
1893 
1894 	n = coeff_per_sb_for_avg[_coeffPerSbSelect][QDM2_SB_USED(_subSampling) - 1] + 1; // same as averagesomething function
1895 
1896 	for (i = 1; i < n; i++)
1897 		for (ch = 0; ch < _channels; ch++) {
1898 			level = qdm2_get_vlc(&gb, &_vlcTabLevel, 0, 2);
1899 			_quantizedCoeffs[ch][i][0] = level;
1900 
1901 			for (j = 0; j < (8 - 1); ) {
1902 				run = qdm2_get_vlc(&gb, &_vlcTabRun, 0, 1) + 1;
1903 				diff = qdm2_get_se_vlc(&_vlcTabDiff, &gb, 2);
1904 
1905 				for (k = 1; k <= run; k++)
1906 					_quantizedCoeffs[ch][i][j + k] = (level + ((k*diff) / run));
1907 
1908 				level += diff;
1909 				j += run;
1910 			}
1911 		}
1912 
1913 	for (ch = 0; ch < _channels; ch++)
1914 		for (i = 0; i < 8; i++)
1915 			_quantizedCoeffs[ch][0][i] = 0;
1916 }
1917 
1918 /**
1919  * Process subpacket 10 if not null, else
1920  *
1921  * @param node      pointer to node with packet
1922  * @param length    packet length in bits
1923  */
process_subpacket_10(QDM2SubPNode * node,int length)1924 void QDM2Stream::process_subpacket_10(QDM2SubPNode *node, int length) {
1925 	Common::BitStreamMemoryStream d(((node == NULL) ? _emptyBuffer : node->packet->data), ((node == NULL) ? 0 : node->packet->size + FF_INPUT_BUFFER_PADDING_SIZE));
1926 	Common::BitStreamMemory32LELSB gb(&d);
1927 
1928 	if (length != 0) {
1929 		init_tone_level_dequantization(&gb, length);
1930 		fill_tone_level_array(1);
1931 	} else {
1932 		fill_tone_level_array(0);
1933 	}
1934 }
1935 
1936 /**
1937  * Process subpacket 11
1938  *
1939  * @param node      pointer to node with packet
1940  * @param length    packet length in bit
1941  */
process_subpacket_11(QDM2SubPNode * node,int length)1942 void QDM2Stream::process_subpacket_11(QDM2SubPNode *node, int length) {
1943 	Common::BitStreamMemoryStream d(((node == NULL) ? _emptyBuffer : node->packet->data), ((node == NULL) ? 0 : node->packet->size + FF_INPUT_BUFFER_PADDING_SIZE));
1944 	Common::BitStreamMemory32LELSB gb(&d);
1945 
1946 	if (length >= 32) {
1947 		int c = gb.getBits(13);
1948 
1949 		if (c > 3)
1950 			fill_coding_method_array(_toneLevelIdx, _toneLevelIdxTemp, _codingMethod,
1951 			                         _channels, 8*c, _superblocktype_2_3, _cmTableSelect);
1952 	}
1953 
1954 	synthfilt_build_sb_samples(&gb, length, 0, 8);
1955 }
1956 
1957 /**
1958  * Process subpacket 12
1959  *
1960  * @param node      pointer to node with packet
1961  * @param length    packet length in bits
1962  */
process_subpacket_12(QDM2SubPNode * node,int length)1963 void QDM2Stream::process_subpacket_12(QDM2SubPNode *node, int length) {
1964 	Common::BitStreamMemoryStream d(((node == NULL) ? _emptyBuffer : node->packet->data), ((node == NULL) ? 0 : node->packet->size + FF_INPUT_BUFFER_PADDING_SIZE));
1965 	Common::BitStreamMemory32LELSB gb(&d);
1966 
1967 	synthfilt_build_sb_samples(&gb, length, 8, QDM2_SB_USED(_subSampling));
1968 }
1969 
1970 /*
1971  * Process new subpackets for synthesis filter
1972  *
1973  * @param list    list with synthesis filter packets (list D)
1974  */
process_synthesis_subpackets(QDM2SubPNode * list)1975 void QDM2Stream::process_synthesis_subpackets(QDM2SubPNode *list) {
1976 	struct QDM2SubPNode *nodes[4];
1977 
1978 	nodes[0] = qdm2_search_subpacket_type_in_list(list, 9);
1979 	if (nodes[0] != NULL)
1980 		process_subpacket_9(nodes[0]);
1981 
1982 	nodes[1] = qdm2_search_subpacket_type_in_list(list, 10);
1983 	if (nodes[1] != NULL)
1984 		process_subpacket_10(nodes[1], nodes[1]->packet->size << 3);
1985 	else
1986 		process_subpacket_10(NULL, 0);
1987 
1988 	nodes[2] = qdm2_search_subpacket_type_in_list(list, 11);
1989 	if (nodes[0] != NULL && nodes[1] != NULL && nodes[2] != NULL)
1990 		process_subpacket_11(nodes[2], (nodes[2]->packet->size << 3));
1991 	else
1992 		process_subpacket_11(NULL, 0);
1993 
1994 	nodes[3] = qdm2_search_subpacket_type_in_list(list, 12);
1995 	if (nodes[0] != NULL && nodes[1] != NULL && nodes[3] != NULL)
1996 		process_subpacket_12(nodes[3], (nodes[3]->packet->size << 3));
1997 	else
1998 		process_subpacket_12(NULL, 0);
1999 }
2000 
2001 /*
2002  * Decode superblock, fill packet lists.
2003  *
2004  */
qdm2_decode_super_block(void)2005 void QDM2Stream::qdm2_decode_super_block(void) {
2006 	struct QDM2SubPacket header, *packet;
2007 	int i, packet_bytes, sub_packet_size, subPacketsD;
2008 	unsigned int next_index = 0;
2009 
2010 	memset(_toneLevelIdxHi1, 0, sizeof(_toneLevelIdxHi1));
2011 	memset(_toneLevelIdxMid, 0, sizeof(_toneLevelIdxMid));
2012 	memset(_toneLevelIdxHi2, 0, sizeof(_toneLevelIdxHi2));
2013 
2014 	_subPacketsB = 0;
2015 	subPacketsD = 0;
2016 
2017 	average_quantized_coeffs(); // average elements in quantized_coeffs[max_ch][10][8]
2018 
2019 	Common::BitStreamMemoryStream packetStream(_compressedData, _packetSize + FF_INPUT_BUFFER_PADDING_SIZE);
2020 	Common::BitStreamMemory32LELSB packetBitStream(packetStream);
2021 	//qdm2_decode_sub_packet_header
2022 	header.type = packetBitStream.getBits(8);
2023 
2024 	if (header.type == 0) {
2025 		header.size = 0;
2026 		header.data = NULL;
2027 	} else {
2028 		header.size = packetBitStream.getBits(8);
2029 
2030 		if (header.type & 0x80) {
2031 			header.size <<= 8;
2032 			header.size |= packetBitStream.getBits(8);
2033 			header.type &= 0x7f;
2034 		}
2035 
2036 		if (header.type == 0x7f)
2037 			header.type |= (packetBitStream.getBits(8) << 8);
2038 
2039 		header.data = &_compressedData[packetBitStream.pos() / 8];
2040 	}
2041 
2042 	if (header.type < 2 || header.type >= 8) {
2043 		_hasErrors = true;
2044 		error("QDM2 : bad superblock type");
2045 		return;
2046 	}
2047 
2048 	_superblocktype_2_3 = (header.type == 2 || header.type == 3);
2049 	packet_bytes = (_packetSize - packetBitStream.pos() / 8);
2050 
2051 	Common::BitStreamMemoryStream headerStream(header.data, header.size + FF_INPUT_BUFFER_PADDING_SIZE);
2052 	Common::BitStreamMemory32LELSB headerBitStream(headerStream);
2053 
2054 	if (header.type == 2 || header.type == 4 || header.type == 5) {
2055 		int csum = 257 * headerBitStream.getBits(8) + 2 * headerBitStream.getBits(8);
2056 
2057 		csum = qdm2_packet_checksum(_compressedData, _packetSize, csum);
2058 
2059 		if (csum != 0) {
2060 			_hasErrors = true;
2061 			error("QDM2 : bad packet checksum");
2062 			return;
2063 		}
2064 	}
2065 
2066 	_subPacketListB[0].packet = NULL;
2067 	_subPacketListD[0].packet = NULL;
2068 
2069 	for (i = 0; i < 6; i++)
2070 		if (--_fftLevelExp[i] < 0)
2071 			_fftLevelExp[i] = 0;
2072 
2073 	for (i = 0; packet_bytes > 0; i++) {
2074 		int j;
2075 
2076 		_subPacketListA[i].next = NULL;
2077 
2078 		if (i > 0) {
2079 			_subPacketListA[i - 1].next = &_subPacketListA[i];
2080 
2081 			if (next_index >= header.size)
2082 				break;
2083 
2084 			// seek to next block
2085 			headerBitStream.skip(next_index * 8 - headerBitStream.pos());
2086 		}
2087 
2088 		// decode subpacket
2089 		packet = &_subPackets[i];
2090 		//qdm2_decode_sub_packet_header
2091 		packet->type = headerBitStream.getBits(8);
2092 
2093 		if (packet->type == 0) {
2094 			packet->size = 0;
2095 			packet->data = NULL;
2096 		} else {
2097 			packet->size = headerBitStream.getBits(8);
2098 
2099 			if (packet->type & 0x80) {
2100 				packet->size <<= 8;
2101 				packet->size |= headerBitStream.getBits(8);
2102 				packet->type &= 0x7f;
2103 			}
2104 
2105 			if (packet->type == 0x7f)
2106 				packet->type |= (headerBitStream.getBits(8) << 8);
2107 
2108 			packet->data = &header.data[headerBitStream.pos() / 8];
2109 		}
2110 
2111 		next_index = packet->size + headerBitStream.pos() / 8;
2112 		sub_packet_size = ((packet->size > 0xff) ? 1 : 0) + packet->size + 2;
2113 
2114 		if (packet->type == 0)
2115 			break;
2116 
2117 		if (sub_packet_size > packet_bytes) {
2118 			if (packet->type != 10 && packet->type != 11 && packet->type != 12)
2119 				break;
2120 			packet->size += packet_bytes - sub_packet_size;
2121 		}
2122 
2123 		packet_bytes -= sub_packet_size;
2124 
2125 		// add subpacket to 'all subpackets' list
2126 		_subPacketListA[i].packet = packet;
2127 
2128 		// add subpacket to related list
2129 		if (packet->type == 8) {
2130 			error("Unsupported packet type 8");
2131 			return;
2132 		} else if (packet->type >= 9 && packet->type <= 12) {
2133 			// packets for MPEG Audio like Synthesis Filter
2134 			QDM2_LIST_ADD(_subPacketListD, subPacketsD, packet);
2135 		} else if (packet->type == 13) {
2136 			for (j = 0; j < 6; j++)
2137 				_fftLevelExp[j] = headerBitStream.getBits(6);
2138 		} else if (packet->type == 14) {
2139 			for (j = 0; j < 6; j++)
2140 				_fftLevelExp[j] = qdm2_get_vlc(&headerBitStream, &_fftLevelExpVlc, 0, 2);
2141 		} else if (packet->type == 15) {
2142 			error("Unsupported packet type 15");
2143 			return;
2144 		} else if (packet->type >= 16 && packet->type < 48 && !fft_subpackets[packet->type - 16]) {
2145 			// packets for FFT
2146 			QDM2_LIST_ADD(_subPacketListB, _subPacketsB, packet);
2147 		}
2148 	} // Packet bytes loop
2149 
2150 // ****************************************************************
2151 	if (_subPacketListD[0].packet != NULL) {
2152 		process_synthesis_subpackets(_subPacketListD);
2153 		_doSynthFilter = 1;
2154 	} else if (_doSynthFilter) {
2155 		process_subpacket_10(NULL, 0);
2156 		process_subpacket_11(NULL, 0);
2157 		process_subpacket_12(NULL, 0);
2158 	}
2159 // ****************************************************************
2160 }
2161 
qdm2_fft_init_coefficient(int sub_packet,int offset,int duration,int channel,int exp,int phase)2162 void QDM2Stream::qdm2_fft_init_coefficient(int sub_packet, int offset, int duration,
2163 										   int channel, int exp, int phase) {
2164 	if (_fftCoefsMinIndex[duration] < 0)
2165 	    _fftCoefsMinIndex[duration] = _fftCoefsIndex;
2166 
2167 	_fftCoefs[_fftCoefsIndex].sub_packet = ((sub_packet >= 16) ? (sub_packet - 16) : sub_packet);
2168 	_fftCoefs[_fftCoefsIndex].channel = channel;
2169 	_fftCoefs[_fftCoefsIndex].offset = offset;
2170 	_fftCoefs[_fftCoefsIndex].exp = exp;
2171 	_fftCoefs[_fftCoefsIndex].phase = phase;
2172 	_fftCoefsIndex++;
2173 }
2174 
qdm2_fft_decode_tones(int duration,Common::BitStreamMemory32LELSB * gb,int b)2175 void QDM2Stream::qdm2_fft_decode_tones(int duration, Common::BitStreamMemory32LELSB *gb, int b) {
2176 	int channel, stereo, phase, exp;
2177 	int local_int_4,  local_int_8,  stereo_phase,  local_int_10;
2178 	int local_int_14, stereo_exp, local_int_20, local_int_28;
2179 	int n, offset;
2180 
2181 	local_int_4 = 0;
2182 	local_int_28 = 0;
2183 	local_int_20 = 2;
2184 	local_int_8 = (4 - duration);
2185 	local_int_10 = 1 << (_groupOrder - duration - 1);
2186 	offset = 1;
2187 
2188 	while (1) {
2189 		if (_superblocktype_2_3) {
2190 			while ((n = qdm2_get_vlc(gb, &_vlcTabFftToneOffset[local_int_8], 1, 2)) < 2) {
2191 				offset = 1;
2192 				if (n == 0) {
2193 					local_int_4 += local_int_10;
2194 					local_int_28 += (1 << local_int_8);
2195 				} else {
2196 					local_int_4 += 8*local_int_10;
2197 					local_int_28 += (8 << local_int_8);
2198 				}
2199 			}
2200 			offset += (n - 2);
2201 		} else {
2202 			offset += qdm2_get_vlc(gb, &_vlcTabFftToneOffset[local_int_8], 1, 2);
2203 			while (offset >= (local_int_10 - 1)) {
2204 				offset += (1 - (local_int_10 - 1));
2205 				local_int_4  += local_int_10;
2206 				local_int_28 += (1 << local_int_8);
2207 			}
2208 		}
2209 
2210 		if (local_int_4 >= _blockSize)
2211 			return;
2212 
2213 		local_int_14 = (offset >> local_int_8);
2214 
2215 		if (_channels > 1) {
2216 			channel = gb->getBit();
2217 			stereo = gb->getBit();
2218 		} else {
2219 			channel = 0;
2220 			stereo = 0;
2221 		}
2222 
2223 		exp = qdm2_get_vlc(gb, (b ? &_fftLevelExpVlc : &_fftLevelExpAltVlc), 0, 2);
2224 		exp += _fftLevelExp[fft_level_index_table[local_int_14]];
2225 		exp = (exp < 0) ? 0 : exp;
2226 
2227 		phase = gb->getBits(3);
2228 		stereo_exp = 0;
2229 		stereo_phase = 0;
2230 
2231 		if (stereo) {
2232 			stereo_exp = (exp - qdm2_get_vlc(gb, &_fftStereoExpVlc, 0, 1));
2233 			stereo_phase = (phase - qdm2_get_vlc(gb, &_fftStereoPhaseVlc, 0, 1));
2234 			if (stereo_phase < 0)
2235 				stereo_phase += 8;
2236 		}
2237 
2238 		if (_frequencyRange > (local_int_14 + 1)) {
2239 			int sub_packet = (local_int_20 + local_int_28);
2240 
2241 			qdm2_fft_init_coefficient(sub_packet, offset, duration, channel, exp, phase);
2242 			if (stereo)
2243 				qdm2_fft_init_coefficient(sub_packet, offset, duration, (1 - channel), stereo_exp, stereo_phase);
2244 		}
2245 
2246 		offset++;
2247 	}
2248 }
2249 
qdm2_decode_fft_packets(void)2250 void QDM2Stream::qdm2_decode_fft_packets(void) {
2251 	int i, j, min, max, value, type, unknown_flag;
2252 
2253 	if (_subPacketListB[0].packet == NULL)
2254 		return;
2255 
2256 	// reset minimum indexes for FFT coefficients
2257 	_fftCoefsIndex = 0;
2258 	for (i=0; i < 5; i++)
2259 		_fftCoefsMinIndex[i] = -1;
2260 
2261 	// process subpackets ordered by type, largest type first
2262 	for (i = 0, max = 256; i < _subPacketsB; i++) {
2263 		QDM2SubPacket *packet= NULL;
2264 
2265 		// find subpacket with largest type less than max
2266 		for (j = 0, min = 0; j < _subPacketsB; j++) {
2267 			value = _subPacketListB[j].packet->type;
2268 			if (value > min && value < max) {
2269 				min = value;
2270 				packet = _subPacketListB[j].packet;
2271 			}
2272 		}
2273 
2274 		max = min;
2275 
2276 		// check for errors (?)
2277 		if (!packet)
2278 			return;
2279 
2280 		if (i == 0 && (packet->type < 16 || packet->type >= 48 || fft_subpackets[packet->type - 16]))
2281 			return;
2282 
2283 		// decode FFT tones
2284 		Common::BitStreamMemoryStream d(packet->data, packet->size + FF_INPUT_BUFFER_PADDING_SIZE);
2285 		Common::BitStreamMemory32LELSB gb(&d);
2286 
2287 		if (packet->type >= 32 && packet->type < 48 && !fft_subpackets[packet->type - 16])
2288 			unknown_flag = 1;
2289 		else
2290 			unknown_flag = 0;
2291 
2292 		type = packet->type;
2293 
2294 		if ((type >= 17 && type < 24) || (type >= 33 && type < 40)) {
2295 			int duration = _subSampling + 5 - (type & 15);
2296 
2297 			if (duration >= 0 && duration < 4) { // TODO: Should be <= 4?
2298 				qdm2_fft_decode_tones(duration, &gb, unknown_flag);
2299 			}
2300 		} else if (type == 31) {
2301 			for (j=0; j < 4; j++) {
2302 				qdm2_fft_decode_tones(j, &gb, unknown_flag);
2303 			}
2304 		} else if (type == 46) {
2305 			for (j=0; j < 6; j++)
2306 				_fftLevelExp[j] = gb.getBits(6);
2307 			for (j=0; j < 4; j++) {
2308 				qdm2_fft_decode_tones(j, &gb, unknown_flag);
2309 			}
2310 		}
2311 	} // Loop on B packets
2312 
2313 	// calculate maximum indexes for FFT coefficients
2314 	for (i = 0, j = -1; i < 5; i++)
2315 		if (_fftCoefsMinIndex[i] >= 0) {
2316 			if (j >= 0)
2317 				_fftCoefsMaxIndex[j] = _fftCoefsMinIndex[i];
2318 			j = i;
2319 		}
2320 	if (j >= 0)
2321 		_fftCoefsMaxIndex[j] = _fftCoefsIndex;
2322 }
2323 
qdm2_fft_generate_tone(FFTTone * tone)2324 void QDM2Stream::qdm2_fft_generate_tone(FFTTone *tone)
2325 {
2326 	float level, f[6];
2327 	int i;
2328 	QDM2Complex c;
2329 	const double iscale = 2.0 * M_PI / 512.0;
2330 
2331 	tone->phase += tone->phase_shift;
2332 
2333 	// calculate current level (maximum amplitude) of tone
2334 	level = fft_tone_envelope_table[tone->duration][tone->time_index] * tone->level;
2335 	c.im = level * sin(tone->phase*iscale);
2336 	c.re = level * cos(tone->phase*iscale);
2337 
2338 	// generate FFT coefficients for tone
2339 	if (tone->duration >= 3 || tone->cutoff >= 3) {
2340 	    tone->complex[0].im += c.im;
2341 	    tone->complex[0].re += c.re;
2342 	    tone->complex[1].im -= c.im;
2343 	    tone->complex[1].re -= c.re;
2344 	} else {
2345 		f[1] = -tone->table[4];
2346 		f[0] =  tone->table[3] - tone->table[0];
2347 		f[2] =  1.0 - tone->table[2] - tone->table[3];
2348 		f[3] =  tone->table[1] + tone->table[4] - 1.0;
2349 		f[4] =  tone->table[0] - tone->table[1];
2350 		f[5] =  tone->table[2];
2351 		for (i = 0; i < 2; i++) {
2352 			tone->complex[fft_cutoff_index_table[tone->cutoff][i]].re += c.re * f[i];
2353 			tone->complex[fft_cutoff_index_table[tone->cutoff][i]].im += c.im *((tone->cutoff <= i) ? -f[i] : f[i]);
2354 		}
2355 		for (i = 0; i < 4; i++) {
2356 			tone->complex[i].re += c.re * f[i+2];
2357 			tone->complex[i].im += c.im * f[i+2];
2358 		}
2359 	}
2360 
2361 	// copy the tone if it has not yet died out
2362 	if (++tone->time_index < ((1 << (5 - tone->duration)) - 1)) {
2363 		memcpy(&_fftTones[_fftToneEnd], tone, sizeof(FFTTone));
2364 		_fftToneEnd = (_fftToneEnd + 1) % 1000;
2365 	}
2366 }
2367 
qdm2_fft_tone_synthesizer(uint8 sub_packet)2368 void QDM2Stream::qdm2_fft_tone_synthesizer(uint8 sub_packet) {
2369 	int i, j, ch;
2370 	const double iscale = 0.25 * M_PI;
2371 
2372 	for (ch = 0; ch < _channels; ch++) {
2373 		memset(_fft.complex[ch], 0, _frameSize * sizeof(QDM2Complex));
2374 	}
2375 
2376 	// apply FFT tones with duration 4 (1 FFT period)
2377 	if (_fftCoefsMinIndex[4] >= 0)
2378 		for (i = _fftCoefsMinIndex[4]; i < _fftCoefsMaxIndex[4]; i++) {
2379 			float level;
2380 			QDM2Complex c;
2381 
2382 			if (_fftCoefs[i].sub_packet != sub_packet)
2383 				break;
2384 
2385 			ch = (_channels == 1) ? 0 : _fftCoefs[i].channel;
2386 			level = (_fftCoefs[i].exp < 0) ? 0.0 : fft_tone_level_table[_superblocktype_2_3 ? 0 : 1][_fftCoefs[i].exp & 63];
2387 
2388 			c.re = level * cos(_fftCoefs[i].phase * iscale);
2389 			c.im = level * sin(_fftCoefs[i].phase * iscale);
2390 			_fft.complex[ch][_fftCoefs[i].offset + 0].re += c.re;
2391 			_fft.complex[ch][_fftCoefs[i].offset + 0].im += c.im;
2392 			_fft.complex[ch][_fftCoefs[i].offset + 1].re -= c.re;
2393 			_fft.complex[ch][_fftCoefs[i].offset + 1].im -= c.im;
2394 		}
2395 
2396 	// generate existing FFT tones
2397 	for (i = _fftToneEnd; i != _fftToneStart; ) {
2398 		qdm2_fft_generate_tone(&_fftTones[_fftToneStart]);
2399 		_fftToneStart = (_fftToneStart + 1) % 1000;
2400 	}
2401 
2402 	// create and generate new FFT tones with duration 0 (long) to 3 (short)
2403 	for (i = 0; i < 4; i++)
2404 		if (_fftCoefsMinIndex[i] >= 0) {
2405 			for (j = _fftCoefsMinIndex[i]; j < _fftCoefsMaxIndex[i]; j++) {
2406 				int offset, four_i;
2407 				FFTTone tone;
2408 
2409 				if (_fftCoefs[j].sub_packet != sub_packet)
2410 					break;
2411 
2412 				four_i = (4 - i);
2413 				offset = _fftCoefs[j].offset >> four_i;
2414 				ch = (_channels == 1) ? 0 : _fftCoefs[j].channel;
2415 
2416 				if (offset < _frequencyRange) {
2417 					if (offset < 2)
2418 						tone.cutoff = offset;
2419 					else
2420 						tone.cutoff = (offset >= 60) ? 3 : 2;
2421 
2422 					tone.level = (_fftCoefs[j].exp < 0) ? 0.0 : fft_tone_level_table[_superblocktype_2_3 ? 0 : 1][_fftCoefs[j].exp & 63];
2423 					tone.complex = &_fft.complex[ch][offset];
2424 					tone.table = fft_tone_sample_table[i][_fftCoefs[j].offset - (offset << four_i)];
2425 					tone.phase = 64 * _fftCoefs[j].phase - (offset << 8) - 128;
2426 					tone.phase_shift = (2 * _fftCoefs[j].offset + 1) << (7 - four_i);
2427 					tone.duration = i;
2428 					tone.time_index = 0;
2429 
2430 					qdm2_fft_generate_tone(&tone);
2431 				}
2432 			}
2433 			_fftCoefsMinIndex[i] = j;
2434 		}
2435 }
2436 
qdm2_calculate_fft(int channel)2437 void QDM2Stream::qdm2_calculate_fft(int channel) {
2438 	_fft.complex[channel][0].re *= 2.0f;
2439 	_fft.complex[channel][0].im = 0.0f;
2440 
2441 	_rdft->calc((float *)_fft.complex[channel]);
2442 
2443 	// add samples to output buffer
2444 	for (int i = 0; i < ((_fftFrameSize + 15) & ~15); i++)
2445 		_outputBuffer[_channels * i + channel] += ((float *) _fft.complex[channel])[i];
2446 }
2447 
2448 /**
2449  * @param index    subpacket number
2450  */
qdm2_synthesis_filter(uint8 index)2451 void QDM2Stream::qdm2_synthesis_filter(uint8 index)
2452 {
2453 	int16 samples[MPA_MAX_CHANNELS * MPA_FRAME_SIZE];
2454 	int i, k, ch, sb_used, sub_sampling, dither_state = 0;
2455 
2456 	// copy sb_samples
2457 	sb_used = QDM2_SB_USED(_subSampling);
2458 
2459 	for (ch = 0; ch < _channels; ch++)
2460 		for (i = 0; i < 8; i++)
2461 			for (k = sb_used; k < 32; k++)
2462 				_sbSamples[ch][(8 * index) + i][k] = 0;
2463 
2464 	for (ch = 0; ch < _channels; ch++) {
2465 		int16 *samples_ptr = samples + ch;
2466 
2467 		for (i = 0; i < 8; i++) {
2468 			ff_mpa_synth_filter(_synthBuf[ch], &(_synthBufOffset[ch]),
2469 			                    ff_mpa_synth_window, &dither_state,
2470 			                    samples_ptr, _channels,
2471 			                    _sbSamples[ch][(8 * index) + i]);
2472 			samples_ptr += 32 * _channels;
2473 		}
2474 	}
2475 
2476 	// add samples to output buffer
2477 	sub_sampling = (4 >> _subSampling);
2478 
2479 	for (ch = 0; ch < _channels; ch++)
2480 		for (i = 0; i < _sFrameSize; i++)
2481 			_outputBuffer[_channels * i + ch] += (float)(samples[_channels * sub_sampling * i + ch] >> (sizeof(int16)*8-16));
2482 }
2483 
qdm2_decodeFrame(Common::SeekableReadStream & in,QueuingAudioStream * audioStream)2484 bool QDM2Stream::qdm2_decodeFrame(Common::SeekableReadStream &in, QueuingAudioStream *audioStream) {
2485 	debug(1, "QDM2Stream::qdm2_decodeFrame in.pos(): %ld in.size(): %ld", in.pos(), in.size());
2486 	int ch, i;
2487 	const int frame_size = (_sFrameSize * _channels);
2488 
2489 	// If we're in any packet but the first, seek back to the first
2490 	if (_subPacket == 0)
2491 		_superBlockStart = in.pos();
2492 	else
2493 		in.seek(_superBlockStart);
2494 
2495 	// select input buffer
2496 	if (in.eos() || in.pos() >= in.size()) {
2497 		debug(1, "QDM2Stream::qdm2_decodeFrame End of Input Stream");
2498 		return false;
2499 	}
2500 
2501 	if ((in.size() - in.pos()) < _packetSize) {
2502 		debug(1, "QDM2Stream::qdm2_decodeFrame Insufficient Packet Data in Input Stream Found: %ld Need: %d", in.size() - in.pos(), _packetSize);
2503 		return false;
2504 	}
2505 
2506 	if (!in.eos()) {
2507 		in.read(_compressedData, _packetSize);
2508 		memset(_compressedData + _packetSize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2509 		debug(1, "QDM2Stream::qdm2_decodeFrame constructed input data");
2510 	}
2511 
2512 	// copy old block, clear new block of output samples
2513 	memmove(_outputBuffer, &_outputBuffer[frame_size], frame_size * sizeof(float));
2514 	memset(&_outputBuffer[frame_size], 0, frame_size * sizeof(float));
2515 	debug(1, "QDM2Stream::qdm2_decodeFrame cleared outputBuffer");
2516 
2517 	if (!in.eos()) {
2518 		// decode block of QDM2 compressed data
2519 		debug(1, "QDM2Stream::qdm2_decodeFrame decode block of QDM2 compressed data");
2520 		if (_subPacket == 0) {
2521 			_hasErrors = false; // reset it for a new super block
2522 			debug(1, "QDM2 : Superblock follows");
2523 			qdm2_decode_super_block();
2524 		}
2525 
2526 		// parse subpackets
2527 		debug(1, "QDM2Stream::qdm2_decodeFrame parse subpackets");
2528 		if (!_hasErrors) {
2529 			if (_subPacket == 2) {
2530 				debug(1, "QDM2Stream::qdm2_decodeFrame qdm2_decode_fft_packets()");
2531 				qdm2_decode_fft_packets();
2532 			}
2533 
2534 			debug(1, "QDM2Stream::qdm2_decodeFrame qdm2_fft_tone_synthesizer(%d)", _subPacket);
2535 			qdm2_fft_tone_synthesizer(_subPacket);
2536 		}
2537 
2538 		// sound synthesis stage 1 (FFT)
2539 		debug(1, "QDM2Stream::qdm2_decodeFrame sound synthesis stage 1 (FFT)");
2540 		for (ch = 0; ch < _channels; ch++) {
2541 			qdm2_calculate_fft(ch);
2542 
2543 			if (!_hasErrors && _subPacketListC[0].packet != NULL) {
2544 				error("QDM2 : has errors, and C list is not empty");
2545 				return false;
2546 			}
2547 		}
2548 
2549 		// sound synthesis stage 2 (MPEG audio like synthesis filter)
2550 		debug(1, "QDM2Stream::qdm2_decodeFrame sound synthesis stage 2 (MPEG audio like synthesis filter)");
2551 		if (!_hasErrors && _doSynthFilter)
2552 			qdm2_synthesis_filter(_subPacket);
2553 
2554 		_subPacket = (_subPacket + 1) % 16;
2555 
2556 		if(_hasErrors)
2557 			warning("QDM2 Packet error...");
2558 
2559 		// clip and convert output float[] to 16bit signed samples
2560 		debug(1, "QDM2Stream::qdm2_decodeFrame clip and convert output float[] to 16bit signed samples");
2561 	}
2562 
2563 	if (frame_size == 0)
2564 		return false;
2565 
2566 	// Prepare a buffer for queuing
2567 	uint16 *outputBuffer = (uint16 *)malloc(frame_size * 2);
2568 
2569 	for (i = 0; i < frame_size; i++) {
2570 		int value = (int)_outputBuffer[i];
2571 
2572 		if (value > SOFTCLIP_THRESHOLD)
2573 			value = (value >  HARDCLIP_THRESHOLD) ?  32767 :  _softclipTable[ value - SOFTCLIP_THRESHOLD];
2574 		else if (value < -SOFTCLIP_THRESHOLD)
2575 			value = (value < -HARDCLIP_THRESHOLD) ? -32767 : -_softclipTable[-value - SOFTCLIP_THRESHOLD];
2576 
2577 		outputBuffer[i] = value;
2578 	}
2579 
2580 	// Queue the translated buffer to our stream
2581 	byte flags = FLAG_16BITS;
2582 
2583 	if (_channels == 2)
2584 		flags |= FLAG_STEREO;
2585 
2586 #ifdef SCUMM_LITTLE_ENDIAN
2587 	flags |= FLAG_LITTLE_ENDIAN;
2588 #endif
2589 
2590 	audioStream->queueBuffer((byte *)outputBuffer, frame_size * 2, DisposeAfterUse::YES, flags);
2591 
2592 	return true;
2593 }
2594 
decodeFrame(Common::SeekableReadStream & stream)2595 AudioStream *QDM2Stream::decodeFrame(Common::SeekableReadStream &stream) {
2596 	QueuingAudioStream *audioStream = makeQueuingAudioStream(_sampleRate, _channels == 2);
2597 
2598 	while (qdm2_decodeFrame(stream, audioStream))
2599 		;
2600 
2601 	audioStream->finish();
2602 	return audioStream;
2603 }
2604 
makeQDM2Decoder(Common::SeekableReadStream * extraData,DisposeAfterUse::Flag disposeExtraData)2605 Codec *makeQDM2Decoder(Common::SeekableReadStream *extraData, DisposeAfterUse::Flag disposeExtraData) {
2606 	return new QDM2Stream(extraData, disposeExtraData);
2607 }
2608 
2609 } // End of namespace Audio
2610 
2611 #endif
2612