ResidualVM logo ResidualVM website - Forums - Contact us BuildBot - Doxygen - Wiki curved edge

qdm2.cpp

Go to the documentation of this file.
00001 /* ScummVM - Graphic Adventure Engine
00002  *
00003  * ScummVM is the legal property of its developers, whose names
00004  * are too numerous to list here. Please refer to the COPYRIGHT
00005  * file distributed with this source distribution.
00006  *
00007  * This program is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU General Public License
00009  * as published by the Free Software Foundation; either version 2
00010  * of the License, or (at your option) any later version.
00011  *
00012  * This program is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015  * GNU General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU General Public License
00018  * along with this program; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
00020  *
00021  */
00022 
00023 // Based off ffmpeg's QDM2 decoder
00024 
00025 #include "common/scummsys.h"
00026 #include "audio/decoders/qdm2.h"
00027 
00028 #ifdef AUDIO_QDM2_H
00029 
00030 #include "audio/audiostream.h"
00031 #include "audio/decoders/codec.h"
00032 #include "audio/decoders/qdm2data.h"
00033 #include "audio/decoders/raw.h"
00034 
00035 #include "common/array.h"
00036 #include "common/debug.h"
00037 #include "common/math.h"
00038 #include "common/rdft.h"
00039 #include "common/stream.h"
00040 #include "common/memstream.h"
00041 #include "common/bitstream.h"
00042 #include "common/textconsole.h"
00043 
00044 namespace Audio {
00045 
00046 enum {
00047     SOFTCLIP_THRESHOLD = 27600,
00048     HARDCLIP_THRESHOLD = 35716,
00049     MPA_MAX_CHANNELS = 2,
00050     MPA_FRAME_SIZE = 1152,
00051     FF_INPUT_BUFFER_PADDING_SIZE = 8
00052 };
00053 
00054 typedef int8 sb_int8_array[2][30][64];
00055 
00056 struct QDM2SubPacket {
00057     int type;
00058     unsigned int size;
00059     const uint8 *data; // pointer to subpacket data (points to input data buffer, it's not a private copy)
00060 };
00061 
00062 struct QDM2SubPNode {
00063     QDM2SubPacket *packet;
00064     struct QDM2SubPNode *next; // pointer to next packet in the list, NULL if leaf node
00065 };
00066 
00067 struct QDM2Complex {
00068     float re;
00069     float im;
00070 };
00071 
00072 struct FFTTone {
00073     float level;
00074     QDM2Complex *complex;
00075     const float *table;
00076     int phase;
00077     int phase_shift;
00078     int duration;
00079     short time_index;
00080     short cutoff;
00081 };
00082 
00083 struct FFTCoefficient {
00084     int16 sub_packet;
00085     uint8 channel;
00086     int16 offset;
00087     int16 exp;
00088     uint8 phase;
00089 };
00090 
00091 struct VLC {
00092     int32 bits;
00093     int16 (*table)[2]; // code, bits
00094     int32 table_size;
00095     int32 table_allocated;
00096 };
00097 
00098 #include "common/pack-start.h"
00099 struct QDM2FFT {
00100     QDM2Complex complex[MPA_MAX_CHANNELS][256];
00101 } PACKED_STRUCT;
00102 #include "common/pack-end.h"
00103 
00104 class QDM2Stream : public Codec {
00105 public:
00106     QDM2Stream(Common::SeekableReadStream *extraData, DisposeAfterUse::Flag disposeExtraData);
00107     ~QDM2Stream();
00108 
00109     AudioStream *decodeFrame(Common::SeekableReadStream &stream);
00110 
00111 private:
00112     // Parameters from codec header, do not change during playback
00113     uint8 _channels;
00114     uint16 _sampleRate;
00115     uint16 _bitRate;
00116     uint16 _blockSize;  // Group
00117     uint16 _frameSize;  // FFT
00118     uint16 _packetSize; // Checksum
00119 
00120     // Parameters built from header parameters, do not change during playback
00121     int _groupOrder;       // order of frame group
00122     int _fftOrder;         // order of FFT (actually fft order+1)
00123     int _fftFrameSize;     // size of fft frame, in components (1 comples = re + im)
00124     int _sFrameSize;        // size of data frame
00125     int _frequencyRange;
00126     int _subSampling;      // subsampling: 0=25%, 1=50%, 2=100% */
00127     int _coeffPerSbSelect; // selector for "num. of coeffs. per subband" tables. Can be 0, 1, 2
00128     int _cmTableSelect;    // selector for "coding method" tables. Can be 0, 1 (from init: 0-4)
00129 
00130     // Packets and packet lists
00131     QDM2SubPacket _subPackets[16];    // the packets themselves
00132     QDM2SubPNode _subPacketListA[16]; // list of all packets
00133     QDM2SubPNode _subPacketListB[16]; // FFT packets B are on list
00134     int _subPacketsB;                 // number of packets on 'B' list
00135     QDM2SubPNode _subPacketListC[16]; // packets with errors?
00136     QDM2SubPNode _subPacketListD[16]; // DCT packets
00137 
00138     // FFT and tones
00139     FFTTone _fftTones[1000];
00140     int _fftToneStart;
00141     int _fftToneEnd;
00142     FFTCoefficient _fftCoefs[1000];
00143     int _fftCoefsIndex;
00144     int _fftCoefsMinIndex[5];
00145     int _fftCoefsMaxIndex[5];
00146     int _fftLevelExp[6];
00147     Common::RDFT *_rdft;
00148     QDM2FFT _fft;
00149 
00150     // I/O data
00151     uint8 *_compressedData;
00152     float _outputBuffer[1024];
00153 
00154     // Synthesis filter
00155     int16 ff_mpa_synth_window[512];
00156     int16 _synthBuf[MPA_MAX_CHANNELS][512*2];
00157     int _synthBufOffset[MPA_MAX_CHANNELS];
00158     int32 _sbSamples[MPA_MAX_CHANNELS][128][32];
00159 
00160     // Mixed temporary data used in decoding
00161     float _toneLevel[MPA_MAX_CHANNELS][30][64];
00162     int8 _codingMethod[MPA_MAX_CHANNELS][30][64];
00163     int8 _quantizedCoeffs[MPA_MAX_CHANNELS][10][8];
00164     int8 _toneLevelIdxBase[MPA_MAX_CHANNELS][30][8];
00165     int8 _toneLevelIdxHi1[MPA_MAX_CHANNELS][3][8][8];
00166     int8 _toneLevelIdxMid[MPA_MAX_CHANNELS][26][8];
00167     int8 _toneLevelIdxHi2[MPA_MAX_CHANNELS][26];
00168     int8 _toneLevelIdx[MPA_MAX_CHANNELS][30][64];
00169     int8 _toneLevelIdxTemp[MPA_MAX_CHANNELS][30][64];
00170 
00171     // Flags
00172     bool _hasErrors;         // packet has errors
00173     int _superblocktype_2_3; // select fft tables and some algorithm based on superblock type
00174     int _doSynthFilter;      // used to perform or skip synthesis filter
00175 
00176     uint8 _subPacket; // 0 to 15
00177     uint32 _superBlockStart;
00178     int _noiseIdx; // index for dithering noise table
00179 
00180     byte _emptyBuffer[FF_INPUT_BUFFER_PADDING_SIZE];
00181 
00182     VLC _vlcTabLevel;
00183     VLC _vlcTabDiff;
00184     VLC _vlcTabRun;
00185     VLC _fftLevelExpAltVlc;
00186     VLC _fftLevelExpVlc;
00187     VLC _fftStereoExpVlc;
00188     VLC _fftStereoPhaseVlc;
00189     VLC _vlcTabToneLevelIdxHi1;
00190     VLC _vlcTabToneLevelIdxMid;
00191     VLC _vlcTabToneLevelIdxHi2;
00192     VLC _vlcTabType30;
00193     VLC _vlcTabType34;
00194     VLC _vlcTabFftToneOffset[5];
00195     bool _vlcsInitialized;
00196     void initVlc(void);
00197 
00198     uint16 _softclipTable[HARDCLIP_THRESHOLD - SOFTCLIP_THRESHOLD + 1];
00199     void softclipTableInit(void);
00200 
00201     float _noiseTable[4096];
00202     byte _randomDequantIndex[256][5];
00203     byte _randomDequantType24[128][3];
00204     void rndTableInit(void);
00205 
00206     float _noiseSamples[128];
00207     void initNoiseSamples(void);
00208 
00209     void average_quantized_coeffs(void);
00210     void build_sb_samples_from_noise(int sb);
00211     void fix_coding_method_array(int sb, int channels, sb_int8_array coding_method);
00212     void fill_tone_level_array(int flag);
00213     void fill_coding_method_array(sb_int8_array tone_level_idx, sb_int8_array tone_level_idx_temp,
00214                                   sb_int8_array coding_method, int nb_channels,
00215                                   int c, int superblocktype_2_3, int cm_table_select);
00216     void synthfilt_build_sb_samples(Common::BitStreamMemory32LELSB *gb, int length, int sb_min, int sb_max);
00217     void init_quantized_coeffs_elem0(int8 *quantized_coeffs, Common::BitStreamMemory32LELSB *gb, int length);
00218     void init_tone_level_dequantization(Common::BitStreamMemory32LELSB *gb, int length);
00219     void process_subpacket_9(QDM2SubPNode *node);
00220     void process_subpacket_10(QDM2SubPNode *node, int length);
00221     void process_subpacket_11(QDM2SubPNode *node, int length);
00222     void process_subpacket_12(QDM2SubPNode *node, int length);
00223     void process_synthesis_subpackets(QDM2SubPNode *list);
00224     void qdm2_decode_super_block(void);
00225     void qdm2_fft_init_coefficient(int sub_packet, int offset, int duration,
00226                                    int channel, int exp, int phase);
00227     void qdm2_fft_decode_tones(int duration, Common::BitStreamMemory32LELSB *gb, int b);
00228     void qdm2_decode_fft_packets(void);
00229     void qdm2_fft_generate_tone(FFTTone *tone);
00230     void qdm2_fft_tone_synthesizer(uint8 sub_packet);
00231     void qdm2_calculate_fft(int channel);
00232     void qdm2_synthesis_filter(uint8 index);
00233     bool qdm2_decodeFrame(Common::SeekableReadStream &in, QueuingAudioStream *audioStream);
00234 };
00235 
00236 #define QDM2_LIST_ADD(list, size, packet) \
00237     do { \
00238         if (size > 0) \
00239             list[size - 1].next = &list[size]; \
00240         list[size].packet = packet; \
00241         list[size].next = NULL; \
00242         size++; \
00243     } while(0)
00244 
00245 // Result is 8, 16 or 30
00246 #define QDM2_SB_USED(subSampling) (((subSampling) >= 2) ? 30 : 8 << (subSampling))
00247 
00248 #define FIX_NOISE_IDX(noiseIdx) \
00249     if ((noiseIdx) >= 3840) \
00250         (noiseIdx) -= 3840 \
00251 
00252 #define SB_DITHERING_NOISE(sb, noiseIdx) (_noiseTable[(noiseIdx)++] * sb_noise_attenuation[(sb)])
00253 
00254 // half mpeg encoding window (full precision)
00255 const int32 ff_mpa_enwindow[257] = {
00256      0,    -1,    -1,    -1,    -1,    -1,    -1,    -2,
00257     -2,    -2,    -2,    -3,    -3,    -4,    -4,    -5,
00258     -5,    -6,    -7,    -7,    -8,    -9,   -10,   -11,
00259    -13,   -14,   -16,   -17,   -19,   -21,   -24,   -26,
00260    -29,   -31,   -35,   -38,   -41,   -45,   -49,   -53,
00261    -58,   -63,   -68,   -73,   -79,   -85,   -91,   -97,
00262   -104,  -111,  -117,  -125,  -132,  -139,  -147,  -154,
00263   -161,  -169,  -176,  -183,  -190,  -196,  -202,  -208,
00264    213,   218,   222,   225,   227,   228,   228,   227,
00265    224,   221,   215,   208,   200,   189,   177,   163,
00266    146,   127,   106,    83,    57,    29,    -2,   -36,
00267    -72,  -111,  -153,  -197,  -244,  -294,  -347,  -401,
00268   -459,  -519,  -581,  -645,  -711,  -779,  -848,  -919,
00269   -991, -1064, -1137, -1210, -1283, -1356, -1428, -1498,
00270  -1567, -1634, -1698, -1759, -1817, -1870, -1919, -1962,
00271  -2001, -2032, -2057, -2075, -2085, -2087, -2080, -2063,
00272   2037,  2000,  1952,  1893,  1822,  1739,  1644,  1535,
00273   1414,  1280,  1131,   970,   794,   605,   402,   185,
00274    -45,  -288,  -545,  -814, -1095, -1388, -1692, -2006,
00275  -2330, -2663, -3004, -3351, -3705, -4063, -4425, -4788,
00276  -5153, -5517, -5879, -6237, -6589, -6935, -7271, -7597,
00277  -7910, -8209, -8491, -8755, -8998, -9219, -9416, -9585,
00278  -9727, -9838, -9916, -9959, -9966, -9935, -9863, -9750,
00279  -9592, -9389, -9139, -8840, -8492, -8092, -7640, -7134,
00280   6574,  5959,  5288,  4561,  3776,  2935,  2037,  1082,
00281     70,  -998, -2122, -3300, -4533, -5818, -7154, -8540,
00282  -9975,-11455,-12980,-14548,-16155,-17799,-19478,-21189,
00283 -22929,-24694,-26482,-28289,-30112,-31947,-33791,-35640,
00284 -37489,-39336,-41176,-43006,-44821,-46617,-48390,-50137,
00285 -51853,-53534,-55178,-56778,-58333,-59838,-61289,-62684,
00286 -64019,-65290,-66494,-67629,-68692,-69679,-70590,-71420,
00287 -72169,-72835,-73415,-73908,-74313,-74630,-74856,-74992,
00288  75038
00289 };
00290 
00291 void ff_mpa_synth_init(int16 *window) {
00292     int i;
00293     int32 v;
00294 
00295     // max = 18760, max sum over all 16 coefs : 44736
00296     for(i = 0; i < 257; i++) {
00297         v = ff_mpa_enwindow[i];
00298         v = (v + 2) >> 2;
00299         window[i] = v;
00300 
00301         if ((i & 63) != 0)
00302             v = -v;
00303 
00304         if (i != 0)
00305             window[512 - i] = v;
00306     }
00307 }
00308 
00309 static inline uint16 round_sample(int *sum) {
00310     int sum1;
00311     sum1 = (*sum) >> 14;
00312     *sum &= (1 << 14)-1;
00313     if (sum1 < (-0x7fff - 1))
00314         sum1 = (-0x7fff - 1);
00315     if (sum1 > 0x7fff)
00316         sum1 = 0x7fff;
00317     return sum1;
00318 }
00319 
00320 static inline int MULH(int a, int b) {
00321     return ((int64)(a) * (int64)(b))>>32;
00322 }
00323 
00324 // signed 16x16 -> 32 multiply add accumulate
00325 #define MACS(rt, ra, rb) rt += (ra) * (rb)
00326 
00327 #define MLSS(rt, ra, rb) ((rt) -= (ra) * (rb))
00328 
00329 #define SUM8(op, sum, w, p)\
00330 {\
00331     op(sum, (w)[0 * 64], (p)[0 * 64]);\
00332     op(sum, (w)[1 * 64], (p)[1 * 64]);\
00333     op(sum, (w)[2 * 64], (p)[2 * 64]);\
00334     op(sum, (w)[3 * 64], (p)[3 * 64]);\
00335     op(sum, (w)[4 * 64], (p)[4 * 64]);\
00336     op(sum, (w)[5 * 64], (p)[5 * 64]);\
00337     op(sum, (w)[6 * 64], (p)[6 * 64]);\
00338     op(sum, (w)[7 * 64], (p)[7 * 64]);\
00339 }
00340 
00341 #define SUM8P2(sum1, op1, sum2, op2, w1, w2, p) \
00342 {\
00343     tmp_s = p[0 * 64];\
00344     op1(sum1, (w1)[0 * 64], tmp_s);\
00345     op2(sum2, (w2)[0 * 64], tmp_s);\
00346     tmp_s = p[1 * 64];\
00347     op1(sum1, (w1)[1 * 64], tmp_s);\
00348     op2(sum2, (w2)[1 * 64], tmp_s);\
00349     tmp_s = p[2 * 64];\
00350     op1(sum1, (w1)[2 * 64], tmp_s);\
00351     op2(sum2, (w2)[2 * 64], tmp_s);\
00352     tmp_s = p[3 * 64];\
00353     op1(sum1, (w1)[3 * 64], tmp_s);\
00354     op2(sum2, (w2)[3 * 64], tmp_s);\
00355     tmp_s = p[4 * 64];\
00356     op1(sum1, (w1)[4 * 64], tmp_s);\
00357     op2(sum2, (w2)[4 * 64], tmp_s);\
00358     tmp_s = p[5 * 64];\
00359     op1(sum1, (w1)[5 * 64], tmp_s);\
00360     op2(sum2, (w2)[5 * 64], tmp_s);\
00361     tmp_s = p[6 * 64];\
00362     op1(sum1, (w1)[6 * 64], tmp_s);\
00363     op2(sum2, (w2)[6 * 64], tmp_s);\
00364     tmp_s = p[7 * 64];\
00365     op1(sum1, (w1)[7 * 64], tmp_s);\
00366     op2(sum2, (w2)[7 * 64], tmp_s);\
00367 }
00368 
00369 #define FIXHR(a) ((int)((a) * (1LL<<32) + 0.5))
00370 
00371 // tab[i][j] = 1.0 / (2.0 * cos(pi*(2*k+1) / 2^(6 - j)))
00372 
00373 // cos(i*pi/64)
00374 
00375 #define COS0_0  FIXHR(0.50060299823519630134/2)
00376 #define COS0_1  FIXHR(0.50547095989754365998/2)
00377 #define COS0_2  FIXHR(0.51544730992262454697/2)
00378 #define COS0_3  FIXHR(0.53104259108978417447/2)
00379 #define COS0_4  FIXHR(0.55310389603444452782/2)
00380 #define COS0_5  FIXHR(0.58293496820613387367/2)
00381 #define COS0_6  FIXHR(0.62250412303566481615/2)
00382 #define COS0_7  FIXHR(0.67480834145500574602/2)
00383 #define COS0_8  FIXHR(0.74453627100229844977/2)
00384 #define COS0_9  FIXHR(0.83934964541552703873/2)
00385 #define COS0_10 FIXHR(0.97256823786196069369/2)
00386 #define COS0_11 FIXHR(1.16943993343288495515/4)
00387 #define COS0_12 FIXHR(1.48416461631416627724/4)
00388 #define COS0_13 FIXHR(2.05778100995341155085/8)
00389 #define COS0_14 FIXHR(3.40760841846871878570/8)
00390 #define COS0_15 FIXHR(10.19000812354805681150/32)
00391 
00392 #define COS1_0 FIXHR(0.50241928618815570551/2)
00393 #define COS1_1 FIXHR(0.52249861493968888062/2)
00394 #define COS1_2 FIXHR(0.56694403481635770368/2)
00395 #define COS1_3 FIXHR(0.64682178335999012954/2)
00396 #define COS1_4 FIXHR(0.78815462345125022473/2)
00397 #define COS1_5 FIXHR(1.06067768599034747134/4)
00398 #define COS1_6 FIXHR(1.72244709823833392782/4)
00399 #define COS1_7 FIXHR(5.10114861868916385802/16)
00400 
00401 #define COS2_0 FIXHR(0.50979557910415916894/2)
00402 #define COS2_1 FIXHR(0.60134488693504528054/2)
00403 #define COS2_2 FIXHR(0.89997622313641570463/2)
00404 #define COS2_3 FIXHR(2.56291544774150617881/8)
00405 
00406 #define COS3_0 FIXHR(0.54119610014619698439/2)
00407 #define COS3_1 FIXHR(1.30656296487637652785/4)
00408 
00409 #define COS4_0 FIXHR(0.70710678118654752439/2)
00410 
00411 /* butterfly operator */
00412 #define BF(a, b, c, s)\
00413 {\
00414     tmp0 = tab[a] + tab[b];\
00415     tmp1 = tab[a] - tab[b];\
00416     tab[a] = tmp0;\
00417     tab[b] = MULH(tmp1<<(s), c);\
00418 }
00419 
00420 #define BF1(a, b, c, d)\
00421 {\
00422     BF(a, b, COS4_0, 1);\
00423     BF(c, d,-COS4_0, 1);\
00424     tab[c] += tab[d];\
00425 }
00426 
00427 #define BF2(a, b, c, d)\
00428 {\
00429     BF(a, b, COS4_0, 1);\
00430     BF(c, d,-COS4_0, 1);\
00431     tab[c] += tab[d];\
00432     tab[a] += tab[c];\
00433     tab[c] += tab[b];\
00434     tab[b] += tab[d];\
00435 }
00436 
00437 #define ADD(a, b) tab[a] += tab[b]
00438 
00439 // DCT32 without 1/sqrt(2) coef zero scaling.
00440 static void dct32(int32 *out, int32 *tab) {
00441     int tmp0, tmp1;
00442 
00443     // pass 1
00444     BF( 0, 31, COS0_0 , 1);
00445     BF(15, 16, COS0_15, 5);
00446     // pass 2
00447     BF( 0, 15, COS1_0 , 1);
00448     BF(16, 31,-COS1_0 , 1);
00449     // pass 1
00450     BF( 7, 24, COS0_7 , 1);
00451     BF( 8, 23, COS0_8 , 1);
00452     // pass 2
00453     BF( 7,  8, COS1_7 , 4);
00454     BF(23, 24,-COS1_7 , 4);
00455     // pass 3
00456     BF( 0,  7, COS2_0 , 1);
00457     BF( 8, 15,-COS2_0 , 1);
00458     BF(16, 23, COS2_0 , 1);
00459     BF(24, 31,-COS2_0 , 1);
00460     // pass 1
00461     BF( 3, 28, COS0_3 , 1);
00462     BF(12, 19, COS0_12, 2);
00463     // pass 2
00464     BF( 3, 12, COS1_3 , 1);
00465     BF(19, 28,-COS1_3 , 1);
00466     // pass 1
00467     BF( 4, 27, COS0_4 , 1);
00468     BF(11, 20, COS0_11, 2);
00469     // pass 2
00470     BF( 4, 11, COS1_4 , 1);
00471     BF(20, 27,-COS1_4 , 1);
00472     // pass 3
00473     BF( 3,  4, COS2_3 , 3);
00474     BF(11, 12,-COS2_3 , 3);
00475     BF(19, 20, COS2_3 , 3);
00476     BF(27, 28,-COS2_3 , 3);
00477     // pass 4
00478     BF( 0,  3, COS3_0 , 1);
00479     BF( 4,  7,-COS3_0 , 1);
00480     BF( 8, 11, COS3_0 , 1);
00481     BF(12, 15,-COS3_0 , 1);
00482     BF(16, 19, COS3_0 , 1);
00483     BF(20, 23,-COS3_0 , 1);
00484     BF(24, 27, COS3_0 , 1);
00485     BF(28, 31,-COS3_0 , 1);
00486 
00487     // pass 1
00488     BF( 1, 30, COS0_1 , 1);
00489     BF(14, 17, COS0_14, 3);
00490     // pass 2
00491     BF( 1, 14, COS1_1 , 1);
00492     BF(17, 30,-COS1_1 , 1);
00493     // pass 1
00494     BF( 6, 25, COS0_6 , 1);
00495     BF( 9, 22, COS0_9 , 1);
00496     // pass 2
00497     BF( 6,  9, COS1_6 , 2);
00498     BF(22, 25,-COS1_6 , 2);
00499     // pass 3
00500     BF( 1,  6, COS2_1 , 1);
00501     BF( 9, 14,-COS2_1 , 1);
00502     BF(17, 22, COS2_1 , 1);
00503     BF(25, 30,-COS2_1 , 1);
00504 
00505     // pass 1
00506     BF( 2, 29, COS0_2 , 1);
00507     BF(13, 18, COS0_13, 3);
00508     // pass 2
00509     BF( 2, 13, COS1_2 , 1);
00510     BF(18, 29,-COS1_2 , 1);
00511     // pass 1
00512     BF( 5, 26, COS0_5 , 1);
00513     BF(10, 21, COS0_10, 1);
00514     // pass 2
00515     BF( 5, 10, COS1_5 , 2);
00516     BF(21, 26,-COS1_5 , 2);
00517     // pass 3
00518     BF( 2,  5, COS2_2 , 1);
00519     BF(10, 13,-COS2_2 , 1);
00520     BF(18, 21, COS2_2 , 1);
00521     BF(26, 29,-COS2_2 , 1);
00522     // pass 4
00523     BF( 1,  2, COS3_1 , 2);
00524     BF( 5,  6,-COS3_1 , 2);
00525     BF( 9, 10, COS3_1 , 2);
00526     BF(13, 14,-COS3_1 , 2);
00527     BF(17, 18, COS3_1 , 2);
00528     BF(21, 22,-COS3_1 , 2);
00529     BF(25, 26, COS3_1 , 2);
00530     BF(29, 30,-COS3_1 , 2);
00531 
00532     // pass 5
00533     BF1( 0,  1,  2,  3);
00534     BF2( 4,  5,  6,  7);
00535     BF1( 8,  9, 10, 11);
00536     BF2(12, 13, 14, 15);
00537     BF1(16, 17, 18, 19);
00538     BF2(20, 21, 22, 23);
00539     BF1(24, 25, 26, 27);
00540     BF2(28, 29, 30, 31);
00541 
00542     // pass 6
00543     ADD( 8, 12);
00544     ADD(12, 10);
00545     ADD(10, 14);
00546     ADD(14,  9);
00547     ADD( 9, 13);
00548     ADD(13, 11);
00549     ADD(11, 15);
00550 
00551     out[ 0] = tab[0];
00552     out[16] = tab[1];
00553     out[ 8] = tab[2];
00554     out[24] = tab[3];
00555     out[ 4] = tab[4];
00556     out[20] = tab[5];
00557     out[12] = tab[6];
00558     out[28] = tab[7];
00559     out[ 2] = tab[8];
00560     out[18] = tab[9];
00561     out[10] = tab[10];
00562     out[26] = tab[11];
00563     out[ 6] = tab[12];
00564     out[22] = tab[13];
00565     out[14] = tab[14];
00566     out[30] = tab[15];
00567 
00568     ADD(24, 28);
00569     ADD(28, 26);
00570     ADD(26, 30);
00571     ADD(30, 25);
00572     ADD(25, 29);
00573     ADD(29, 27);
00574     ADD(27, 31);
00575 
00576     out[ 1] = tab[16] + tab[24];
00577     out[17] = tab[17] + tab[25];
00578     out[ 9] = tab[18] + tab[26];
00579     out[25] = tab[19] + tab[27];
00580     out[ 5] = tab[20] + tab[28];
00581     out[21] = tab[21] + tab[29];
00582     out[13] = tab[22] + tab[30];
00583     out[29] = tab[23] + tab[31];
00584     out[ 3] = tab[24] + tab[20];
00585     out[19] = tab[25] + tab[21];
00586     out[11] = tab[26] + tab[22];
00587     out[27] = tab[27] + tab[23];
00588     out[ 7] = tab[28] + tab[18];
00589     out[23] = tab[29] + tab[19];
00590     out[15] = tab[30] + tab[17];
00591     out[31] = tab[31];
00592 }
00593 
00594 // 32 sub band synthesis filter. Input: 32 sub band samples, Output:
00595 // 32 samples.
00596 // XXX: optimize by avoiding ring buffer usage
00597 void ff_mpa_synth_filter(int16 *synth_buf_ptr, int *synth_buf_offset,
00598                          int16 *window, int *dither_state,
00599                          int16 *samples, int incr,
00600                          int32 sb_samples[32])
00601 {
00602     int16 *synth_buf;
00603     const int16 *w, *w2, *p;
00604     int j, offset;
00605     int16 *samples2;
00606     int32 tmp[32];
00607     int sum, sum2;
00608     int tmp_s;
00609 
00610     offset = *synth_buf_offset;
00611     synth_buf = synth_buf_ptr + offset;
00612 
00613     dct32(tmp, sb_samples);
00614     for(j = 0; j < 32; j++) {
00615         // NOTE: can cause a loss in precision if very high amplitude sound
00616         if (tmp[j] < (-0x7fff - 1))
00617             synth_buf[j] = (-0x7fff - 1);
00618         else if (tmp[j] > 0x7fff)
00619             synth_buf[j] = 0x7fff;
00620         else
00621             synth_buf[j] = tmp[j];
00622     }
00623 
00624     // copy to avoid wrap
00625     memcpy(synth_buf + 512, synth_buf, 32 * sizeof(int16));
00626 
00627     samples2 = samples + 31 * incr;
00628     w = window;
00629     w2 = window + 31;
00630 
00631     sum = *dither_state;
00632     p = synth_buf + 16;
00633     SUM8(MACS, sum, w, p);
00634     p = synth_buf + 48;
00635     SUM8(MLSS, sum, w + 32, p);
00636     *samples = round_sample(&sum);
00637     samples += incr;
00638     w++;
00639 
00640     // we calculate two samples at the same time to avoid one memory
00641     // access per two sample
00642     for(j = 1; j < 16; j++) {
00643         sum2 = 0;
00644         p = synth_buf + 16 + j;
00645         SUM8P2(sum, MACS, sum2, MLSS, w, w2, p);
00646         p = synth_buf + 48 - j;
00647         SUM8P2(sum, MLSS, sum2, MLSS, w + 32, w2 + 32, p);
00648 
00649         *samples = round_sample(&sum);
00650         samples += incr;
00651         sum += sum2;
00652         *samples2 = round_sample(&sum);
00653         samples2 -= incr;
00654         w++;
00655         w2--;
00656     }
00657 
00658     p = synth_buf + 32;
00659     SUM8(MLSS, sum, w + 32, p);
00660     *samples = round_sample(&sum);
00661     *dither_state= sum;
00662 
00663     offset = (offset - 32) & 511;
00664     *synth_buf_offset = offset;
00665 }
00666 
00675 static int getVlc2(Common::BitStreamMemory32LELSB *s, int16 (*table)[2], int bits, int maxDepth) {
00676     int index = s->peekBits(bits);
00677     int code = table[index][0];
00678     int n = table[index][1];
00679 
00680     if (maxDepth > 1 && n < 0) {
00681         s->skip(bits);
00682         int nbBits = -n;
00683         index = s->peekBits(-n) + code;
00684         code = table[index][0];
00685         n = table[index][1];
00686 
00687         if (maxDepth > 2 && n < 0) {
00688             s->skip(nbBits);
00689             index = s->getBits(-n) + code;
00690             code = table[index][0];
00691             n = table[index][1];
00692         }
00693     }
00694 
00695     s->skip(n);
00696     return code;
00697 }
00698 
00699 static int allocTable(VLC *vlc, int size, int use_static) {
00700     int index;
00701     int16 (*temp)[2] = NULL;
00702     index = vlc->table_size;
00703     vlc->table_size += size;
00704     if (vlc->table_size > vlc->table_allocated) {
00705         if(use_static)
00706             error("QDM2 cant do anything, init_vlc() is used with too little memory");
00707         vlc->table_allocated += (1 << vlc->bits);
00708         temp = (int16 (*)[2])realloc(vlc->table, sizeof(int16 *) * 2 * vlc->table_allocated);
00709         if (!temp) {
00710             free(vlc->table);
00711             vlc->table = NULL;
00712             return -1;
00713         }
00714         vlc->table = temp;
00715     }
00716     return index;
00717 }
00718 
00719 #define GET_DATA(v, table, i, wrap, size)\
00720 {\
00721     const uint8 *ptr = (const uint8 *)table + i * wrap;\
00722     switch(size) {\
00723         case 1:\
00724             v = *(const uint8 *)ptr;\
00725             break;\
00726         case 2:\
00727             v = *(const uint16 *)ptr;\
00728             break;\
00729         default:\
00730             v = *(const uint32 *)ptr;\
00731             break;\
00732     }\
00733 }
00734 
00735 static int build_table(VLC *vlc, int table_nb_bits,
00736                        int nb_codes,
00737                        const void *bits, int bits_wrap, int bits_size,
00738                        const void *codes, int codes_wrap, int codes_size,
00739                        const void *symbols, int symbols_wrap, int symbols_size,
00740                        int code_prefix, int n_prefix, int flags)
00741 {
00742     int i, j, k, n, table_size, table_index, nb, n1, index, code_prefix2, symbol;
00743     uint32 code;
00744     int16 (*table)[2];
00745 
00746     table_size = 1 << table_nb_bits;
00747     table_index = allocTable(vlc, table_size, flags & 4);
00748     if (table_index < 0)
00749         return -1;
00750     table = &vlc->table[table_index];
00751 
00752     for(i = 0; i < table_size; i++) {
00753         table[i][1] = 0; //bits
00754         table[i][0] = -1; //codes
00755     }
00756 
00757     // first pass: map codes and compute auxillary table sizes
00758     for(i = 0; i < nb_codes; i++) {
00759         GET_DATA(n, bits, i, bits_wrap, bits_size);
00760         GET_DATA(code, codes, i, codes_wrap, codes_size);
00761         // we accept tables with holes
00762         if (n <= 0)
00763             continue;
00764         if (!symbols)
00765             symbol = i;
00766         else
00767             GET_DATA(symbol, symbols, i, symbols_wrap, symbols_size);
00768         // if code matches the prefix, it is in the table
00769         n -= n_prefix;
00770         if(flags & 2)
00771             code_prefix2= code & (n_prefix>=32 ? 0xffffffff : (1 << n_prefix)-1);
00772         else
00773             code_prefix2= code >> n;
00774         if (n > 0 && code_prefix2 == code_prefix) {
00775             if (n <= table_nb_bits) {
00776                 // no need to add another table
00777                 j = (code << (table_nb_bits - n)) & (table_size - 1);
00778                 nb = 1 << (table_nb_bits - n);
00779                 for(k = 0; k < nb; k++) {
00780                     if(flags & 2)
00781                         j = (code >> n_prefix) + (k<<n);
00782                     if (table[j][1] /*bits*/ != 0) {
00783                         error("QDM2 incorrect codes");
00784                         return -1;
00785                     }
00786                     table[j][1] = n; //bits
00787                     table[j][0] = symbol;
00788                     j++;
00789                 }
00790             } else {
00791                 n -= table_nb_bits;
00792                 j = (code >> ((flags & 2) ? n_prefix : n)) & ((1 << table_nb_bits) - 1);
00793                 // compute table size
00794                 n1 = -table[j][1]; //bits
00795                 if (n > n1)
00796                     n1 = n;
00797                 table[j][1] = -n1; //bits
00798             }
00799         }
00800     }
00801 
00802     // second pass : fill auxillary tables recursively
00803     for(i = 0;i < table_size; i++) {
00804         n = table[i][1]; //bits
00805         if (n < 0) {
00806             n = -n;
00807             if (n > table_nb_bits) {
00808                 n = table_nb_bits;
00809                 table[i][1] = -n; //bits
00810             }
00811             index = build_table(vlc, n, nb_codes,
00812                                 bits, bits_wrap, bits_size,
00813                                 codes, codes_wrap, codes_size,
00814                                 symbols, symbols_wrap, symbols_size,
00815                                 (flags & 2) ? (code_prefix | (i << n_prefix)) : ((code_prefix << table_nb_bits) | i),
00816                                 n_prefix + table_nb_bits, flags);
00817             if (index < 0)
00818                 return -1;
00819             // note: realloc has been done, so reload tables
00820             table = &vlc->table[table_index];
00821             table[i][0] = index; //code
00822         }
00823     }
00824     return table_index;
00825 }
00826 
00827 /* Build VLC decoding tables suitable for use with get_vlc().
00828 
00829    'nb_bits' set thee decoding table size (2^nb_bits) entries. The
00830    bigger it is, the faster is the decoding. But it should not be too
00831    big to save memory and L1 cache. '9' is a good compromise.
00832 
00833    'nb_codes' : number of vlcs codes
00834 
00835    'bits' : table which gives the size (in bits) of each vlc code.
00836 
00837    'codes' : table which gives the bit pattern of of each vlc code.
00838 
00839    'symbols' : table which gives the values to be returned from get_vlc().
00840 
00841    'xxx_wrap' : give the number of bytes between each entry of the
00842    'bits' or 'codes' tables.
00843 
00844    'xxx_size' : gives the number of bytes of each entry of the 'bits'
00845    or 'codes' tables.
00846 
00847    'wrap' and 'size' allows to use any memory configuration and types
00848    (byte/word/long) to store the 'bits', 'codes', and 'symbols' tables.
00849 
00850    'use_static' should be set to 1 for tables, which should be freed
00851    with av_free_static(), 0 if free_vlc() will be used.
00852 */
00853 void initVlcSparse(VLC *vlc, int nb_bits, int nb_codes,
00854         const void *bits, int bits_wrap, int bits_size,
00855         const void *codes, int codes_wrap, int codes_size,
00856         const void *symbols, int symbols_wrap, int symbols_size) {
00857     vlc->bits = nb_bits;
00858 
00859     if (vlc->table_size && vlc->table_size == vlc->table_allocated) {
00860         return;
00861     } else if (vlc->table_size) {
00862         error("called on a partially initialized table");
00863     }
00864 
00865     if (build_table(vlc, nb_bits, nb_codes,
00866                     bits, bits_wrap, bits_size,
00867                     codes, codes_wrap, codes_size,
00868                     symbols, symbols_wrap, symbols_size,
00869                     0, 0, 4 | 2) < 0) {
00870         free(vlc->table);
00871         return; // Error
00872     }
00873 
00874     if(vlc->table_size != vlc->table_allocated)
00875         error("QDM2 needed %d had %d", vlc->table_size, vlc->table_allocated);
00876 }
00877 
00878 void QDM2Stream::softclipTableInit(void) {
00879     uint16 i;
00880     double dfl = SOFTCLIP_THRESHOLD - 32767;
00881     float delta = 1.0 / -dfl;
00882 
00883     for (i = 0; i < ARRAYSIZE(_softclipTable); i++)
00884         _softclipTable[i] = SOFTCLIP_THRESHOLD - ((int)(sin((float)i * delta) * dfl) & 0x0000FFFF);
00885 }
00886 
00887 // random generated table
00888 void QDM2Stream::rndTableInit(void) {
00889     uint16 i;
00890     uint16 j;
00891     uint32 ldw, hdw;
00892     int64 tmp64_1;
00893     int64 random_seed = 0;
00894     float delta = 1.0 / 16384.0;
00895 
00896     for(i = 0; i < ARRAYSIZE(_noiseTable); i++) {
00897         random_seed = random_seed * 214013 + 2531011;
00898         _noiseTable[i] = (delta * (float)(((int32)random_seed >> 16) & 0x00007FFF)- 1.0) * 1.3;
00899     }
00900 
00901     for (i = 0; i < 256; i++) {
00902         random_seed = 81;
00903         ldw = i;
00904         for (j = 0; j < 5; j++) {
00905             _randomDequantIndex[i][j] = (uint8)((ldw / random_seed) & 0xFF);
00906             ldw = (uint32)ldw % (uint32)random_seed;
00907             tmp64_1 = (random_seed * 0x55555556);
00908             hdw = (uint32)(tmp64_1 >> 32);
00909             random_seed = (int64)(hdw + (ldw >> 31));
00910         }
00911     }
00912 
00913     for (i = 0; i < 128; i++) {
00914         random_seed = 25;
00915         ldw = i;
00916         for (j = 0; j < 3; j++) {
00917             _randomDequantType24[i][j] = (uint8)((ldw / random_seed) & 0xFF);
00918             ldw = (uint32)ldw % (uint32)random_seed;
00919             tmp64_1 = (random_seed * 0x66666667);
00920             hdw = (uint32)(tmp64_1 >> 33);
00921             random_seed = hdw + (ldw >> 31);
00922         }
00923     }
00924 }
00925 
00926 void QDM2Stream::initNoiseSamples(void) {
00927     uint16 i;
00928     uint32 random_seed = 0;
00929     float delta = 1.0 / 16384.0;
00930 
00931     for (i = 0; i < ARRAYSIZE(_noiseSamples); i++) {
00932         random_seed = random_seed * 214013 + 2531011;
00933         _noiseSamples[i] = (delta * (float)((random_seed >> 16) & 0x00007fff) - 1.0);
00934     }
00935 }
00936 
00937 static const uint16 qdm2_vlc_offs[18] = {
00938     0, 260, 566, 598, 894, 1166, 1230, 1294, 1678, 1950, 2214, 2278, 2310, 2570, 2834, 3124, 3448, 3838
00939 };
00940 
00941 void QDM2Stream::initVlc(void) {
00942     static int16 qdm2_table[3838][2];
00943 
00944     if (!_vlcsInitialized) {
00945         _vlcTabLevel.table = &qdm2_table[qdm2_vlc_offs[0]];
00946         _vlcTabLevel.table_allocated = qdm2_vlc_offs[1] - qdm2_vlc_offs[0];
00947         _vlcTabLevel.table_size = 0;
00948         initVlcSparse(&_vlcTabLevel, 8, 24,
00949             vlc_tab_level_huffbits, 1, 1,
00950             vlc_tab_level_huffcodes, 2, 2, NULL, 0, 0);
00951 
00952         _vlcTabDiff.table = &qdm2_table[qdm2_vlc_offs[1]];
00953         _vlcTabDiff.table_allocated = qdm2_vlc_offs[2] - qdm2_vlc_offs[1];
00954         _vlcTabDiff.table_size = 0;
00955         initVlcSparse(&_vlcTabDiff, 8, 37,
00956             vlc_tab_diff_huffbits, 1, 1,
00957             vlc_tab_diff_huffcodes, 2, 2, NULL, 0, 0);
00958 
00959         _vlcTabRun.table = &qdm2_table[qdm2_vlc_offs[2]];
00960         _vlcTabRun.table_allocated = qdm2_vlc_offs[3] - qdm2_vlc_offs[2];
00961         _vlcTabRun.table_size = 0;
00962         initVlcSparse(&_vlcTabRun, 5, 6,
00963             vlc_tab_run_huffbits, 1, 1,
00964             vlc_tab_run_huffcodes, 1, 1, NULL, 0, 0);
00965 
00966         _fftLevelExpAltVlc.table = &qdm2_table[qdm2_vlc_offs[3]];
00967         _fftLevelExpAltVlc.table_allocated = qdm2_vlc_offs[4] - qdm2_vlc_offs[3];
00968         _fftLevelExpAltVlc.table_size = 0;
00969         initVlcSparse(&_fftLevelExpAltVlc, 8, 28,
00970             fft_level_exp_alt_huffbits, 1, 1,
00971             fft_level_exp_alt_huffcodes, 2, 2, NULL, 0, 0);
00972 
00973         _fftLevelExpVlc.table = &qdm2_table[qdm2_vlc_offs[4]];
00974         _fftLevelExpVlc.table_allocated = qdm2_vlc_offs[5] - qdm2_vlc_offs[4];
00975         _fftLevelExpVlc.table_size = 0;
00976         initVlcSparse(&_fftLevelExpVlc, 8, 20,
00977             fft_level_exp_huffbits, 1, 1,
00978             fft_level_exp_huffcodes, 2, 2, NULL, 0, 0);
00979 
00980         _fftStereoExpVlc.table = &qdm2_table[qdm2_vlc_offs[5]];
00981         _fftStereoExpVlc.table_allocated = qdm2_vlc_offs[6] - qdm2_vlc_offs[5];
00982         _fftStereoExpVlc.table_size = 0;
00983         initVlcSparse(&_fftStereoExpVlc, 6, 7,
00984             fft_stereo_exp_huffbits, 1, 1,
00985             fft_stereo_exp_huffcodes, 1, 1, NULL, 0, 0);
00986 
00987         _fftStereoPhaseVlc.table = &qdm2_table[qdm2_vlc_offs[6]];
00988         _fftStereoPhaseVlc.table_allocated = qdm2_vlc_offs[7] - qdm2_vlc_offs[6];
00989         _fftStereoPhaseVlc.table_size = 0;
00990         initVlcSparse(&_fftStereoPhaseVlc, 6, 9,
00991             fft_stereo_phase_huffbits, 1, 1,
00992             fft_stereo_phase_huffcodes, 1, 1, NULL, 0, 0);
00993 
00994         _vlcTabToneLevelIdxHi1.table = &qdm2_table[qdm2_vlc_offs[7]];
00995         _vlcTabToneLevelIdxHi1.table_allocated = qdm2_vlc_offs[8] - qdm2_vlc_offs[7];
00996         _vlcTabToneLevelIdxHi1.table_size = 0;
00997         initVlcSparse(&_vlcTabToneLevelIdxHi1, 8, 20,
00998             vlc_tab_tone_level_idx_hi1_huffbits, 1, 1,
00999             vlc_tab_tone_level_idx_hi1_huffcodes, 2, 2, NULL, 0, 0);
01000 
01001         _vlcTabToneLevelIdxMid.table = &qdm2_table[qdm2_vlc_offs[8]];
01002         _vlcTabToneLevelIdxMid.table_allocated = qdm2_vlc_offs[9] - qdm2_vlc_offs[8];
01003         _vlcTabToneLevelIdxMid.table_size = 0;
01004         initVlcSparse(&_vlcTabToneLevelIdxMid, 8, 24,
01005             vlc_tab_tone_level_idx_mid_huffbits, 1, 1,
01006             vlc_tab_tone_level_idx_mid_huffcodes, 2, 2, NULL, 0, 0);
01007 
01008         _vlcTabToneLevelIdxHi2.table = &qdm2_table[qdm2_vlc_offs[9]];
01009         _vlcTabToneLevelIdxHi2.table_allocated = qdm2_vlc_offs[10] - qdm2_vlc_offs[9];
01010         _vlcTabToneLevelIdxHi2.table_size = 0;
01011         initVlcSparse(&_vlcTabToneLevelIdxHi2, 8, 24,
01012             vlc_tab_tone_level_idx_hi2_huffbits, 1, 1,
01013             vlc_tab_tone_level_idx_hi2_huffcodes, 2, 2, NULL, 0, 0);
01014 
01015         _vlcTabType30.table = &qdm2_table[qdm2_vlc_offs[10]];
01016         _vlcTabType30.table_allocated = qdm2_vlc_offs[11] - qdm2_vlc_offs[10];
01017         _vlcTabType30.table_size = 0;
01018         initVlcSparse(&_vlcTabType30, 6, 9,
01019             vlc_tab_type30_huffbits, 1, 1,
01020             vlc_tab_type30_huffcodes, 1, 1, NULL, 0, 0);
01021 
01022         _vlcTabType34.table = &qdm2_table[qdm2_vlc_offs[11]];
01023         _vlcTabType34.table_allocated = qdm2_vlc_offs[12] - qdm2_vlc_offs[11];
01024         _vlcTabType34.table_size = 0;
01025         initVlcSparse(&_vlcTabType34, 5, 10,
01026             vlc_tab_type34_huffbits, 1, 1,
01027             vlc_tab_type34_huffcodes, 1, 1, NULL, 0, 0);
01028 
01029         _vlcTabFftToneOffset[0].table = &qdm2_table[qdm2_vlc_offs[12]];
01030         _vlcTabFftToneOffset[0].table_allocated = qdm2_vlc_offs[13] - qdm2_vlc_offs[12];
01031         _vlcTabFftToneOffset[0].table_size = 0;
01032         initVlcSparse(&_vlcTabFftToneOffset[0], 8, 23,
01033             vlc_tab_fft_tone_offset_0_huffbits, 1, 1,
01034             vlc_tab_fft_tone_offset_0_huffcodes, 2, 2, NULL, 0, 0);
01035 
01036         _vlcTabFftToneOffset[1].table = &qdm2_table[qdm2_vlc_offs[13]];
01037         _vlcTabFftToneOffset[1].table_allocated = qdm2_vlc_offs[14] - qdm2_vlc_offs[13];
01038         _vlcTabFftToneOffset[1].table_size = 0;
01039         initVlcSparse(&_vlcTabFftToneOffset[1], 8, 28,
01040             vlc_tab_fft_tone_offset_1_huffbits, 1, 1,
01041             vlc_tab_fft_tone_offset_1_huffcodes, 2, 2, NULL, 0, 0);
01042 
01043         _vlcTabFftToneOffset[2].table = &qdm2_table[qdm2_vlc_offs[14]];
01044         _vlcTabFftToneOffset[2].table_allocated = qdm2_vlc_offs[15] - qdm2_vlc_offs[14];
01045         _vlcTabFftToneOffset[2].table_size = 0;
01046         initVlcSparse(&_vlcTabFftToneOffset[2], 8, 32,
01047             vlc_tab_fft_tone_offset_2_huffbits, 1, 1,
01048             vlc_tab_fft_tone_offset_2_huffcodes, 2, 2, NULL, 0, 0);
01049 
01050         _vlcTabFftToneOffset[3].table = &qdm2_table[qdm2_vlc_offs[15]];
01051         _vlcTabFftToneOffset[3].table_allocated = qdm2_vlc_offs[16] - qdm2_vlc_offs[15];
01052         _vlcTabFftToneOffset[3].table_size = 0;
01053         initVlcSparse(&_vlcTabFftToneOffset[3], 8, 35,
01054             vlc_tab_fft_tone_offset_3_huffbits, 1, 1,
01055             vlc_tab_fft_tone_offset_3_huffcodes, 2, 2, NULL, 0, 0);
01056 
01057         _vlcTabFftToneOffset[4].table = &qdm2_table[qdm2_vlc_offs[16]];
01058         _vlcTabFftToneOffset[4].table_allocated = qdm2_vlc_offs[17] - qdm2_vlc_offs[16];
01059         _vlcTabFftToneOffset[4].table_size = 0;
01060         initVlcSparse(&_vlcTabFftToneOffset[4], 8, 38,
01061             vlc_tab_fft_tone_offset_4_huffbits, 1, 1,
01062             vlc_tab_fft_tone_offset_4_huffcodes, 2, 2, NULL, 0, 0);
01063 
01064         _vlcsInitialized = true;
01065     }
01066 }
01067 
01068 QDM2Stream::QDM2Stream(Common::SeekableReadStream *extraData, DisposeAfterUse::Flag disposeExtraData) {
01069     uint32 tmp;
01070     int tmp_val;
01071     int i;
01072 
01073     debug(1, "QDM2Stream::QDM2Stream() Call");
01074 
01075     _compressedData = NULL;
01076     _subPacket = 0;
01077     _superBlockStart = 0;
01078     memset(_quantizedCoeffs, 0, sizeof(_quantizedCoeffs));
01079     memset(_fftLevelExp, 0, sizeof(_fftLevelExp));
01080     _noiseIdx = 0;
01081     memset(_fftCoefsMinIndex, 0, sizeof(_fftCoefsMinIndex));
01082     memset(_fftCoefsMaxIndex, 0, sizeof(_fftCoefsMaxIndex));
01083     _fftToneStart = 0;
01084     _fftToneEnd = 0;
01085     for(i = 0; i < ARRAYSIZE(_subPacketListA); i++) {
01086         _subPacketListA[i].packet = NULL;
01087         _subPacketListA[i].next = NULL;
01088     }
01089     _subPacketsB = 0;
01090     for(i = 0; i < ARRAYSIZE(_subPacketListB); i++) {
01091         _subPacketListB[i].packet = NULL;
01092         _subPacketListB[i].next = NULL;
01093     }
01094     for(i = 0; i < ARRAYSIZE(_subPacketListC); i++) {
01095         _subPacketListC[i].packet = NULL;
01096         _subPacketListC[i].next = NULL;
01097     }
01098     for(i = 0; i < ARRAYSIZE(_subPacketListD); i++) {
01099         _subPacketListD[i].packet = NULL;
01100         _subPacketListD[i].next = NULL;
01101     }
01102     memset(_synthBuf, 0, sizeof(_synthBuf));
01103     memset(_synthBufOffset, 0, sizeof(_synthBufOffset));
01104     memset(_sbSamples, 0, sizeof(_sbSamples));
01105     memset(_outputBuffer, 0, sizeof(_outputBuffer));
01106     _vlcsInitialized = false;
01107     _superblocktype_2_3 = 0;
01108     _hasErrors = false;
01109 
01110     // The QDM2 "extra data" is really just an amalgam of three QuickTime
01111     // atoms needed to correctly set up the decoder.
01112 
01113     // Rewind extraData stream from any previous calls
01114     extraData->seek(0, SEEK_SET);
01115 
01116     // First, the frma atom
01117     uint32 frmaSize = extraData->readUint32BE();
01118     if (frmaSize != 12)
01119         error("Invalid QDM2 frma atom");
01120 
01121     if (extraData->readUint32BE() != MKTAG('f', 'r', 'm', 'a'))
01122         error("Failed to find frma atom for QDM2");
01123 
01124     uint32 version = extraData->readUint32BE();
01125     if (version == MKTAG('Q', 'D', 'M', 'C'))
01126         error("Unhandled QDMC sound");
01127     else if (version != MKTAG('Q', 'D', 'M', '2'))
01128         error("Failed to find QDM2 tag in frma atom");
01129 
01130     // Second, the QDCA atom
01131     uint32 qdcaSize = extraData->readUint32BE();
01132     if (qdcaSize > (uint32)(extraData->size() - extraData->pos()))
01133         error("Invalid QDM2 QDCA atom");
01134 
01135     if (extraData->readUint32BE() != MKTAG('Q', 'D', 'C', 'A'))
01136         error("Failed to find QDCA atom for QDM2");
01137 
01138     extraData->readUint32BE(); // unknown
01139 
01140     _channels = extraData->readUint32BE();
01141     _sampleRate = extraData->readUint32BE();
01142     _bitRate = extraData->readUint32BE();
01143     _blockSize = extraData->readUint32BE();
01144     _frameSize = extraData->readUint32BE();
01145     _packetSize = extraData->readUint32BE();
01146 
01147     // Third, we don't care about the QDCP atom
01148 
01149     _fftOrder = Common::intLog2(_frameSize) + 1;
01150     _fftFrameSize = 2 * _frameSize; // complex has two floats
01151 
01152     // something like max decodable tones
01153     _groupOrder = Common::intLog2(_blockSize) + 1;
01154     _sFrameSize = _blockSize / 16; // 16 iterations per super block
01155 
01156     _subSampling = _fftOrder - 7;
01157     _frequencyRange = 255 / (1 << (2 - _subSampling));
01158 
01159     switch (_subSampling * 2 + _channels - 1) {
01160         case 0:
01161             tmp = 40;
01162             break;
01163         case 1:
01164             tmp = 48;
01165             break;
01166         case 2:
01167             tmp = 56;
01168             break;
01169         case 3:
01170             tmp = 72;
01171             break;
01172         case 4:
01173             tmp = 80;
01174             break;
01175         case 5:
01176             tmp = 100;
01177             break;
01178         default:
01179             tmp = _subSampling;
01180             break;
01181     }
01182 
01183     tmp_val = 0;
01184     if ((tmp * 1000) < _bitRate)  tmp_val = 1;
01185     if ((tmp * 1440) < _bitRate)  tmp_val = 2;
01186     if ((tmp * 1760) < _bitRate)  tmp_val = 3;
01187     if ((tmp * 2240) < _bitRate)  tmp_val = 4;
01188     _cmTableSelect = tmp_val;
01189 
01190     if (_subSampling == 0)
01191         tmp = 7999;
01192     else
01193         tmp = ((-(_subSampling -1)) & 8000) + 20000;
01194 
01195     if (tmp < 8000)
01196         _coeffPerSbSelect = 0;
01197     else if (tmp <= 16000)
01198         _coeffPerSbSelect = 1;
01199     else
01200         _coeffPerSbSelect = 2;
01201 
01202     if (_fftOrder < 7 || _fftOrder > 9)
01203         error("QDM2Stream::QDM2Stream() Unsupported fft_order: %d", _fftOrder);
01204 
01205     _rdft = new Common::RDFT(_fftOrder, Common::RDFT::IDFT_C2R);
01206 
01207     initVlc();
01208     ff_mpa_synth_init(ff_mpa_synth_window);
01209     softclipTableInit();
01210     rndTableInit();
01211     initNoiseSamples();
01212 
01213     _compressedData = new uint8[_packetSize + FF_INPUT_BUFFER_PADDING_SIZE];
01214 
01215     if (disposeExtraData == DisposeAfterUse::YES)
01216         delete extraData;
01217 }
01218 
01219 QDM2Stream::~QDM2Stream() {
01220     delete _rdft;
01221     delete[] _compressedData;
01222 }
01223 
01224 static int qdm2_get_vlc(Common::BitStreamMemory32LELSB *gb, VLC *vlc, int flag, int depth) {
01225     int value = getVlc2(gb, vlc->table, vlc->bits, depth);
01226 
01227     // stage-2, 3 bits exponent escape sequence
01228     if (value-- == 0)
01229         value = gb->getBits(gb->getBits(3) + 1);
01230 
01231     // stage-3, optional
01232     if (flag) {
01233         int tmp = vlc_stage3_values[value];
01234 
01235         if ((value & ~3) > 0)
01236             tmp += gb->getBits(value >> 2);
01237         value = tmp;
01238     }
01239 
01240     return value;
01241 }
01242 
01243 static int qdm2_get_se_vlc(VLC *vlc, Common::BitStreamMemory32LELSB *gb, int depth)
01244 {
01245     int value = qdm2_get_vlc(gb, vlc, 0, depth);
01246 
01247     return (value & 1) ? ((value + 1) >> 1) : -(value >> 1);
01248 }
01249 
01259 static uint16 qdm2_packet_checksum(const uint8 *data, int length, int value) {
01260     int i;
01261 
01262     for (i = 0; i < length; i++)
01263         value -= data[i];
01264 
01265     return (uint16)(value & 0xffff);
01266 }
01267 
01275 static QDM2SubPNode* qdm2_search_subpacket_type_in_list(QDM2SubPNode *list, int type)
01276 {
01277     while (list != NULL && list->packet != NULL) {
01278         if (list->packet->type == type)
01279             return list;
01280         list = list->next;
01281     }
01282     return NULL;
01283 }
01284 
01289 void QDM2Stream::average_quantized_coeffs(void) {
01290     int i, j, n, ch, sum;
01291 
01292     n = coeff_per_sb_for_avg[_coeffPerSbSelect][QDM2_SB_USED(_subSampling) - 1] + 1;
01293 
01294     for (ch = 0; ch < _channels; ch++) {
01295         for (i = 0; i < n; i++) {
01296             sum = 0;
01297 
01298             for (j = 0; j < 8; j++)
01299                 sum += _quantizedCoeffs[ch][i][j];
01300 
01301             sum /= 8;
01302             if (sum > 0)
01303                 sum--;
01304 
01305             for (j = 0; j < 8; j++)
01306                 _quantizedCoeffs[ch][i][j] = sum;
01307         }
01308     }
01309 }
01310 
01317 void QDM2Stream::build_sb_samples_from_noise(int sb) {
01318     int ch, j;
01319 
01320     FIX_NOISE_IDX(_noiseIdx);
01321 
01322     if (!_channels)
01323         return;
01324 
01325     for (ch = 0; ch < _channels; ch++) {
01326         for (j = 0; j < 64; j++) {
01327             _sbSamples[ch][j * 2][sb] = (int32)(SB_DITHERING_NOISE(sb, _noiseIdx) * _toneLevel[ch][sb][j] + .5);
01328             _sbSamples[ch][j * 2 + 1][sb] = (int32)(SB_DITHERING_NOISE(sb, _noiseIdx) * _toneLevel[ch][sb][j] + .5);
01329         }
01330     }
01331 }
01332 
01341 void QDM2Stream::fix_coding_method_array(int sb, int channels, sb_int8_array coding_method)
01342 {
01343     int j, k;
01344     int ch;
01345     int run, case_val;
01346     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};
01347 
01348     for (ch = 0; ch < channels; ch++) {
01349         for (j = 0; j < 64; ) {
01350             if ((coding_method[ch][sb][j] - 8) > 22) {
01351                 run = 1;
01352                 case_val = 8;
01353             } else {
01354                 switch (switchtable[coding_method[ch][sb][j]-8]) {
01355                     case 0: run = 10; case_val = 10; break;
01356                     case 1: run = 1; case_val = 16; break;
01357                     case 2: run = 5; case_val = 24; break;
01358                     case 3: run = 3; case_val = 30; break;
01359                     case 4: run = 1; case_val = 30; break;
01360                     case 5: run = 1; case_val = 8; break;
01361                     default: run = 1; case_val = 8; break;
01362                 }
01363             }
01364             for (k = 0; k < run; k++)
01365                 if (j + k < 128)
01366                     if (coding_method[ch][sb + (j + k) / 64][(j + k) % 64] > coding_method[ch][sb][j])
01367                         if (k > 0) {
01368                             warning("QDM2 Untested Code: not debugged, almost never used");
01369                             memset(&coding_method[ch][sb][j + k], case_val, k * sizeof(int8));
01370                             memset(&coding_method[ch][sb][j + k], case_val, 3 * sizeof(int8));
01371                         }
01372             j += run;
01373         }
01374     }
01375 }
01376 
01383 void QDM2Stream::fill_tone_level_array(int flag) {
01384     int i, sb, ch, sb_used;
01385     int tmp, tab;
01386 
01387     // This should never happen
01388     if (_channels <= 0)
01389         return;
01390 
01391     for (ch = 0; ch < _channels; ch++) {
01392         for (sb = 0; sb < 30; sb++) {
01393             for (i = 0; i < 8; i++) {
01394                 if ((tab=coeff_per_sb_for_dequant[_coeffPerSbSelect][sb]) < (last_coeff[_coeffPerSbSelect] - 1))
01395                     tmp = _quantizedCoeffs[ch][tab + 1][i] * dequant_table[_coeffPerSbSelect][tab + 1][sb]+
01396                           _quantizedCoeffs[ch][tab][i] * dequant_table[_coeffPerSbSelect][tab][sb];
01397                 else
01398                     tmp = _quantizedCoeffs[ch][tab][i] * dequant_table[_coeffPerSbSelect][tab][sb];
01399                 if(tmp < 0)
01400                     tmp += 0xff;
01401                 _toneLevelIdxBase[ch][sb][i] = (tmp / 256) & 0xff;
01402             }
01403         }
01404     }
01405 
01406     sb_used = QDM2_SB_USED(_subSampling);
01407 
01408     if ((_superblocktype_2_3 != 0) && !flag) {
01409         for (sb = 0; sb < sb_used; sb++) {
01410             for (ch = 0; ch < _channels; ch++) {
01411                 for (i = 0; i < 64; i++) {
01412                     _toneLevelIdx[ch][sb][i] = _toneLevelIdxBase[ch][sb][i / 8];
01413                     if (_toneLevelIdx[ch][sb][i] < 0)
01414                         _toneLevel[ch][sb][i] = 0;
01415                     else
01416                         _toneLevel[ch][sb][i] = fft_tone_level_table[0][_toneLevelIdx[ch][sb][i] & 0x3f];
01417                 }
01418             }
01419         }
01420     } else {
01421         tab = _superblocktype_2_3 ? 0 : 1;
01422         for (sb = 0; sb < sb_used; sb++) {
01423             if ((sb >= 4) && (sb <= 23)) {
01424                 for (ch = 0; ch < _channels; ch++) {
01425                     for (i = 0; i < 64; i++) {
01426                         tmp = _toneLevelIdxBase[ch][sb][i / 8] -
01427                               _toneLevelIdxHi1[ch][sb / 8][i / 8][i % 8] -
01428                               _toneLevelIdxMid[ch][sb - 4][i / 8] -
01429                               _toneLevelIdxHi2[ch][sb - 4];
01430                         _toneLevelIdx[ch][sb][i] = tmp & 0xff;
01431                         if ((tmp < 0) || (!_superblocktype_2_3 && !tmp))
01432                             _toneLevel[ch][sb][i] = 0;
01433                         else
01434                             _toneLevel[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
01435                     }
01436                 }
01437             } else {
01438                 if (sb > 4) {
01439                     for (ch = 0; ch < _channels; ch++) {
01440                         for (i = 0; i < 64; i++) {
01441                             tmp = _toneLevelIdxBase[ch][sb][i / 8] -
01442                                   _toneLevelIdxHi1[ch][2][i / 8][i % 8] -
01443                                   _toneLevelIdxHi2[ch][sb - 4];
01444                             _toneLevelIdx[ch][sb][i] = tmp & 0xff;
01445                             if ((tmp < 0) || (!_superblocktype_2_3 && !tmp))
01446                                 _toneLevel[ch][sb][i] = 0;
01447                             else
01448                                 _toneLevel[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
01449                         }
01450                     }
01451                 } else {
01452                     for (ch = 0; ch < _channels; ch++) {
01453                         for (i = 0; i < 64; i++) {
01454                             tmp = _toneLevelIdx[ch][sb][i] = _toneLevelIdxBase[ch][sb][i / 8];
01455                             if ((tmp < 0) || (!_superblocktype_2_3 && !tmp))
01456                                 _toneLevel[ch][sb][i] = 0;
01457                             else
01458                                 _toneLevel[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
01459                         }
01460                     }
01461                 }
01462             }
01463         }
01464     }
01465 }
01466 
01481 void QDM2Stream::fill_coding_method_array(sb_int8_array tone_level_idx, sb_int8_array tone_level_idx_temp,
01482                 sb_int8_array coding_method, int nb_channels,
01483                 int c, int superblocktype_2_3, int cm_table_select) {
01484     int ch, sb, j;
01485     int tmp, acc, esp_40, comp;
01486     int add1, add2, add3, add4;
01487     int64 multres;
01488 
01489     // This should never happen
01490     if (nb_channels <= 0)
01491         return;
01492     if (!superblocktype_2_3) {
01493         warning("QDM2 This case is untested, no samples available");
01494         for (ch = 0; ch < nb_channels; ch++) {
01495             for (sb = 0; sb < 30; sb++) {
01496                 for (j = 1; j < 63; j++) {  // The loop only iterates to 63 so the code doesn't overflow the buffer
01497                     add1 = tone_level_idx[ch][sb][j] - 10;
01498                     if (add1 < 0)
01499                         add1 = 0;
01500                     add2 = add3 = add4 = 0;
01501                     if (sb > 1) {
01502                         add2 = tone_level_idx[ch][sb - 2][j] + tone_level_idx_offset_table[sb][0] - 6;
01503                         if (add2 < 0)
01504                             add2 = 0;
01505                     }
01506                     if (sb > 0) {
01507                         add3 = tone_level_idx[ch][sb - 1][j] + tone_level_idx_offset_table[sb][1] - 6;
01508                         if (add3 < 0)
01509                             add3 = 0;
01510                     }
01511                     if (sb < 29) {
01512                         add4 = tone_level_idx[ch][sb + 1][j] + tone_level_idx_offset_table[sb][3] - 6;
01513                         if (add4 < 0)
01514                             add4 = 0;
01515                     }
01516                     tmp = tone_level_idx[ch][sb][j + 1] * 2 - add4 - add3 - add2 - add1;
01517                     if (tmp < 0)
01518                         tmp = 0;
01519                     tone_level_idx_temp[ch][sb][j + 1] = tmp & 0xff;
01520                 }
01521                 tone_level_idx_temp[ch][sb][0] = tone_level_idx_temp[ch][sb][1];
01522             }
01523         }
01524         acc = 0;
01525         for (ch = 0; ch < nb_channels; ch++)
01526             for (sb = 0; sb < 30; sb++)
01527                 for (j = 0; j < 64; j++)
01528                     acc += tone_level_idx_temp[ch][sb][j];
01529 
01530         multres = 0x66666667 * (acc * 10);
01531         esp_40 = (multres >> 32) / 8 + ((multres & 0xffffffff) >> 31);
01532         for (ch = 0;  ch < nb_channels; ch++) {
01533             for (sb = 0; sb < 30; sb++) {
01534                 for (j = 0; j < 64; j++) {
01535                     comp = tone_level_idx_temp[ch][sb][j]* esp_40 * 10;
01536                     if (comp < 0)
01537                         comp += 0xff;
01538                     comp /= 256; // signed shift
01539                     switch(sb) {
01540                         case 0:
01541                             if (comp < 30)
01542                                 comp = 30;
01543                             comp += 15;
01544                             break;
01545                         case 1:
01546                             if (comp < 24)
01547                                 comp = 24;
01548                             comp += 10;
01549                             break;
01550                         case 2:
01551                         case 3:
01552                         case 4:
01553                             if (comp < 16)
01554                                 comp = 16;
01555                     }
01556                     if (comp <= 5)
01557                         tmp = 0;
01558                     else if (comp <= 10)
01559                         tmp = 10;
01560                     else if (comp <= 16)
01561                         tmp = 16;
01562                     else if (comp <= 24)
01563                         tmp = -1;
01564                     else
01565                         tmp = 0;
01566                     coding_method[ch][sb][j] = ((tmp & 0xfffa) + 30 )& 0xff;
01567                 }
01568             }
01569         }
01570         for (sb = 0; sb < 30; sb++)
01571             fix_coding_method_array(sb, nb_channels, coding_method);
01572         for (ch = 0; ch < nb_channels; ch++) {
01573             for (sb = 0; sb < 30; sb++) {
01574                 for (j = 0; j < 64; j++) {
01575                     if (sb >= 10) {
01576                         if (coding_method[ch][sb][j] < 10)
01577                             coding_method[ch][sb][j] = 10;
01578                     } else {
01579                         if (sb >= 2) {
01580                             if (coding_method[ch][sb][j] < 16)
01581                                 coding_method[ch][sb][j] = 16;
01582                         } else {
01583                             if (coding_method[ch][sb][j] < 30)
01584                                 coding_method[ch][sb][j] = 30;
01585                         }
01586                     }
01587                 }
01588             }
01589         }
01590     } else { // superblocktype_2_3 != 0
01591         for (ch = 0; ch < nb_channels; ch++)
01592             for (sb = 0; sb < 30; sb++)
01593                 for (j = 0; j < 64; j++)
01594                     coding_method[ch][sb][j] = coding_method_table[cm_table_select][sb];
01595     }
01596 }
01597 
01608 void QDM2Stream::synthfilt_build_sb_samples(Common::BitStreamMemory32LELSB *gb, int length, int sb_min, int sb_max) {
01609     int sb, j, k, n, ch, run, channels;
01610     int joined_stereo, zero_encoding, chs;
01611     int type34_first;
01612     float type34_div = 0;
01613     float type34_predictor;
01614     float samples[10], sign_bits[16];
01615 
01616     if (length == 0) {
01617         // If no data use noise
01618         for (sb = sb_min; sb < sb_max; sb++)
01619             build_sb_samples_from_noise(sb);
01620 
01621         return;
01622     }
01623 
01624     for (sb = sb_min; sb < sb_max; sb++) {
01625         FIX_NOISE_IDX(_noiseIdx);
01626 
01627         channels = _channels;
01628 
01629         if (_channels <= 1 || sb < 12)
01630             joined_stereo = 0;
01631         else if (sb >= 24)
01632             joined_stereo = 1;
01633         else
01634             joined_stereo = ((length - gb->pos()) >= 1) ? gb->getBit() : 0;
01635 
01636         if (joined_stereo) {
01637             if ((length - gb->pos()) >= 16)
01638                 for (j = 0; j < 16; j++)
01639                     sign_bits[j] = gb->getBit();
01640 
01641             for (j = 0; j < 64; j++)
01642                 if (_codingMethod[1][sb][j] > _codingMethod[0][sb][j])
01643                     _codingMethod[0][sb][j] = _codingMethod[1][sb][j];
01644 
01645             fix_coding_method_array(sb, _channels, _codingMethod);
01646             channels = 1;
01647         }
01648 
01649         for (ch = 0; ch < channels; ch++) {
01650             zero_encoding = ((length - gb->pos()) >= 1) ? gb->getBit() : 0;
01651             type34_predictor = 0.0;
01652             type34_first = 1;
01653 
01654             for (j = 0; j < 128; ) {
01655                 switch (_codingMethod[ch][sb][j / 2]) {
01656                     case 8:
01657                         if ((length - gb->pos()) >= 10) {
01658                             if (zero_encoding) {
01659                                 for (k = 0; k < 5; k++) {
01660                                     if ((j + 2 * k) >= 128)
01661                                         break;
01662                                     samples[2 * k] = gb->getBit() ? dequant_1bit[joined_stereo][2 * gb->getBit()] : 0;
01663                                 }
01664                             } else {
01665                                 n = gb->getBits(8);
01666                                 for (k = 0; k < 5; k++)
01667                                     samples[2 * k] = dequant_1bit[joined_stereo][_randomDequantIndex[n][k]];
01668                             }
01669                             for (k = 0; k < 5; k++)
01670                                 samples[2 * k + 1] = SB_DITHERING_NOISE(sb, _noiseIdx);
01671                         } else {
01672                             for (k = 0; k < 10; k++)
01673                                 samples[k] = SB_DITHERING_NOISE(sb, _noiseIdx);
01674                         }
01675                         run = 10;
01676                         break;
01677 
01678                     case 10:
01679                         if ((length - gb->pos()) >= 1) {
01680                             double f = 0.81;
01681 
01682                             if (gb->getBit())
01683                                 f = -f;
01684                             f -= _noiseSamples[((sb + 1) * (j +5 * ch + 1)) & 127] * 9.0 / 40.0;
01685                             samples[0] = f;
01686                         } else {
01687                             samples[0] = SB_DITHERING_NOISE(sb, _noiseIdx);
01688                         }
01689                         run = 1;
01690                         break;
01691 
01692                     case 16:
01693                         if ((length - gb->pos()) >= 10) {
01694                             if (zero_encoding) {
01695                                 for (k = 0; k < 5; k++) {
01696                                     if ((j + k) >= 128)
01697                                         break;
01698                                     samples[k] = (gb->getBit() == 0) ? 0 : dequant_1bit[joined_stereo][2 * gb->getBit()];
01699                                 }
01700                             } else {
01701                                 n = gb->getBits(8);
01702                                 for (k = 0; k < 5; k++)
01703                                     samples[k] = dequant_1bit[joined_stereo][_randomDequantIndex[n][k]];
01704                             }
01705                         } else {
01706                             for (k = 0; k < 5; k++)
01707                                 samples[k] = SB_DITHERING_NOISE(sb, _noiseIdx);
01708                         }
01709                         run = 5;
01710                         break;
01711 
01712                     case 24:
01713                         if ((length - gb->pos()) >= 7) {
01714                             n = gb->getBits(7);
01715                             for (k = 0; k < 3; k++)
01716                                 samples[k] = (_randomDequantType24[n][k] - 2.0) * 0.5;
01717                         } else {
01718                             for (k = 0; k < 3; k++)
01719                                 samples[k] = SB_DITHERING_NOISE(sb, _noiseIdx);
01720                         }
01721                         run = 3;
01722                         break;
01723 
01724                     case 30:
01725                         if ((length - gb->pos()) >= 4)
01726                             samples[0] = type30_dequant[qdm2_get_vlc(gb, &_vlcTabType30, 0, 1)];
01727                         else
01728                             samples[0] = SB_DITHERING_NOISE(sb, _noiseIdx);
01729 
01730                         run = 1;
01731                         break;
01732 
01733                     case 34:
01734                         if ((length - gb->pos()) >= 7) {
01735                             if (type34_first) {
01736                                 type34_div = (float)(1 << gb->getBits(2));
01737                                 samples[0] = ((float)gb->getBits(5) - 16.0) / 15.0;
01738                                 type34_predictor = samples[0];
01739                                 type34_first = 0;
01740                             } else {
01741                                 samples[0] = type34_delta[qdm2_get_vlc(gb, &_vlcTabType34, 0, 1)] / type34_div + type34_predictor;
01742                                 type34_predictor = samples[0];
01743                             }
01744                         } else {
01745                             samples[0] = SB_DITHERING_NOISE(sb, _noiseIdx);
01746                         }
01747                         run = 1;
01748                         break;
01749 
01750                     default:
01751                         samples[0] = SB_DITHERING_NOISE(sb, _noiseIdx);
01752                         run = 1;
01753                         break;
01754                 }
01755 
01756                 if (joined_stereo) {
01757                     float tmp[10][MPA_MAX_CHANNELS];
01758 
01759                     for (k = 0; k < run; k++) {
01760                         tmp[k][0] = samples[k];
01761                         tmp[k][1] = (sign_bits[(j + k) / 8]) ? -samples[k] : samples[k];
01762                     }
01763                     for (chs = 0; chs < _channels; chs++)
01764                         for (k = 0; k < run; k++)
01765                             if ((j + k) < 128)
01766                                 _sbSamples[chs][j + k][sb] = (int32)(_toneLevel[chs][sb][((j + k)/2)] * tmp[k][chs] + .5);
01767                 } else {
01768                     for (k = 0; k < run; k++)
01769                         if ((j + k) < 128)
01770                             _sbSamples[ch][j + k][sb] = (int32)(_toneLevel[ch][sb][(j + k)/2] * samples[k] + .5);
01771                 }
01772 
01773                 j += run;
01774             } // j loop
01775         } // channel loop
01776     } // subband loop
01777 }
01778 
01788 void QDM2Stream::init_quantized_coeffs_elem0(int8 *quantized_coeffs, Common::BitStreamMemory32LELSB *gb, int length) {
01789     int i, k, run, level, diff;
01790 
01791     if ((length - gb->pos()) < 16)
01792         return;
01793     level = qdm2_get_vlc(gb, &_vlcTabLevel, 0, 2);
01794 
01795     quantized_coeffs[0] = level;
01796 
01797     for (i = 0; i < 7; ) {
01798         if ((length - gb->pos()) < 16)
01799             break;
01800         run = qdm2_get_vlc(gb, &_vlcTabRun, 0, 1) + 1;
01801 
01802         if ((length - gb->pos()) < 16)
01803             break;
01804         diff = qdm2_get_se_vlc(&_vlcTabDiff, gb, 2);
01805 
01806         for (k = 1; k <= run; k++)
01807             quantized_coeffs[i + k] = (level + ((k * diff) / run));
01808 
01809         level += diff;
01810         i += run;
01811     }
01812 }
01813 
01822 void QDM2Stream::init_tone_level_dequantization(Common::BitStreamMemory32LELSB *gb, int length) {
01823     int sb, j, k, n, ch;
01824 
01825     for (ch = 0; ch < _channels; ch++) {
01826         init_quantized_coeffs_elem0(_quantizedCoeffs[ch][0], gb, length);
01827 
01828         if ((length - gb->pos()) < 16) {
01829             memset(_quantizedCoeffs[ch][0], 0, 8);
01830             break;
01831         }
01832     }
01833 
01834     n = _subSampling + 1;
01835 
01836     for (sb = 0; sb < n; sb++)
01837         for (ch = 0; ch < _channels; ch++)
01838             for (j = 0; j < 8; j++) {
01839                 if ((length - gb->pos()) < 1)
01840                     break;
01841                 if (gb->getBit()) {
01842                     for (k=0; k < 8; k++) {
01843                         if ((length - gb->pos()) < 16)
01844                             break;
01845                         _toneLevelIdxHi1[ch][sb][j][k] = qdm2_get_vlc(gb, &_vlcTabToneLevelIdxHi1, 0, 2);
01846                     }
01847                 } else {
01848                     for (k=0; k < 8; k++)
01849                         _toneLevelIdxHi1[ch][sb][j][k] = 0;
01850                 }
01851             }
01852 
01853     n = QDM2_SB_USED(_subSampling) - 4;
01854 
01855     for (sb = 0; sb < n; sb++)
01856         for (ch = 0; ch < _channels; ch++) {
01857             if ((length - gb->pos()) < 16)
01858                 break;
01859             _toneLevelIdxHi2[ch][sb] = qdm2_get_vlc(gb, &_vlcTabToneLevelIdxHi2, 0, 2);
01860             if (sb > 19)
01861                 _toneLevelIdxHi2[ch][sb] -= 16;
01862             else
01863                 for (j = 0; j < 8; j++)
01864                     _toneLevelIdxMid[ch][sb][j] = -16;
01865         }
01866 
01867     n = QDM2_SB_USED(_subSampling) - 5;
01868 
01869     for (sb = 0; sb < n; sb++) {
01870         for (ch = 0; ch < _channels; ch++) {
01871             for (j = 0; j < 8; j++) {
01872                 if ((length - gb->pos()) < 16)
01873                     break;
01874                 _toneLevelIdxMid[ch][sb][j] = qdm2_get_vlc(gb, &_vlcTabToneLevelIdxMid, 0, 2) - 32;
01875             }
01876         }
01877     }
01878 }
01879 
01885 void QDM2Stream::process_subpacket_9(QDM2SubPNode *node) {
01886     int i, j, k, n, ch, run, level, diff;
01887 
01888     Common::BitStreamMemoryStream d(node->packet->data, node->packet->size + FF_INPUT_BUFFER_PADDING_SIZE);
01889     Common::BitStreamMemory32LELSB gb(&d);
01890 
01891     n = coeff_per_sb_for_avg[_coeffPerSbSelect][QDM2_SB_USED(_subSampling) - 1] + 1; // same as averagesomething function
01892 
01893     for (i = 1; i < n; i++)
01894         for (ch = 0; ch < _channels; ch++) {
01895             level = qdm2_get_vlc(&gb, &_vlcTabLevel, 0, 2);
01896             _quantizedCoeffs[ch][i][0] = level;
01897 
01898             for (j = 0; j < (8 - 1); ) {
01899                 run = qdm2_get_vlc(&gb, &_vlcTabRun, 0, 1) + 1;
01900                 diff = qdm2_get_se_vlc(&_vlcTabDiff, &gb, 2);
01901 
01902                 for (k = 1; k <= run; k++)
01903                     _quantizedCoeffs[ch][i][j + k] = (level + ((k*diff) / run));
01904 
01905                 level += diff;
01906                 j += run;
01907             }
01908         }
01909 
01910     for (ch = 0; ch < _channels; ch++)
01911         for (i = 0; i < 8; i++)
01912             _quantizedCoeffs[ch][0][i] = 0;
01913 }
01914 
01921 void QDM2Stream::process_subpacket_10(QDM2SubPNode *node, int length) {
01922     Common::BitStreamMemoryStream d(((node == NULL) ? _emptyBuffer : node->packet->data), ((node == NULL) ? 0 : node->packet->size + FF_INPUT_BUFFER_PADDING_SIZE));
01923     Common::BitStreamMemory32LELSB gb(&d);
01924 
01925     if (length != 0) {
01926         init_tone_level_dequantization(&gb, length);
01927         fill_tone_level_array(1);
01928     } else {
01929         fill_tone_level_array(0);
01930     }
01931 }
01932 
01939 void QDM2Stream::process_subpacket_11(QDM2SubPNode *node, int length) {
01940     Common::BitStreamMemoryStream d(((node == NULL) ? _emptyBuffer : node->packet->data), ((node == NULL) ? 0 : node->packet->size + FF_INPUT_BUFFER_PADDING_SIZE));
01941     Common::BitStreamMemory32LELSB gb(&d);
01942 
01943     if (length >= 32) {
01944         int c = gb.getBits(13);
01945 
01946         if (c > 3)
01947             fill_coding_method_array(_toneLevelIdx, _toneLevelIdxTemp, _codingMethod,
01948                                      _channels, 8*c, _superblocktype_2_3, _cmTableSelect);
01949     }
01950 
01951     synthfilt_build_sb_samples(&gb, length, 0, 8);
01952 }
01953 
01960 void QDM2Stream::process_subpacket_12(QDM2SubPNode *node, int length) {
01961     Common::BitStreamMemoryStream d(((node == NULL) ? _emptyBuffer : node->packet->data), ((node == NULL) ? 0 : node->packet->size + FF_INPUT_BUFFER_PADDING_SIZE));
01962     Common::BitStreamMemory32LELSB gb(&d);
01963 
01964     synthfilt_build_sb_samples(&gb, length, 8, QDM2_SB_USED(_subSampling));
01965 }
01966 
01967 /*
01968  * Process new subpackets for synthesis filter
01969  *
01970  * @param list    list with synthesis filter packets (list D)
01971  */
01972 void QDM2Stream::process_synthesis_subpackets(QDM2SubPNode *list) {
01973     struct QDM2SubPNode *nodes[4];
01974 
01975     nodes[0] = qdm2_search_subpacket_type_in_list(list, 9);
01976     if (nodes[0] != NULL)
01977         process_subpacket_9(nodes[0]);
01978 
01979     nodes[1] = qdm2_search_subpacket_type_in_list(list, 10);
01980     if (nodes[1] != NULL)
01981         process_subpacket_10(nodes[1], nodes[1]->packet->size << 3);
01982     else
01983         process_subpacket_10(NULL, 0);
01984 
01985     nodes[2] = qdm2_search_subpacket_type_in_list(list, 11);
01986     if (nodes[0] != NULL && nodes[1] != NULL && nodes[2] != NULL)
01987         process_subpacket_11(nodes[2], (nodes[2]->packet->size << 3));
01988     else
01989         process_subpacket_11(NULL, 0);
01990 
01991     nodes[3] = qdm2_search_subpacket_type_in_list(list, 12);
01992     if (nodes[0] != NULL && nodes[1] != NULL && nodes[3] != NULL)
01993         process_subpacket_12(nodes[3], (nodes[3]->packet->size << 3));
01994     else
01995         process_subpacket_12(NULL, 0);
01996 }
01997 
01998 /*
01999  * Decode superblock, fill packet lists.
02000  *
02001  */
02002 void QDM2Stream::qdm2_decode_super_block(void) {
02003     struct QDM2SubPacket header, *packet;
02004     int i, packet_bytes, sub_packet_size, subPacketsD;
02005     unsigned int next_index = 0;
02006 
02007     memset(_toneLevelIdxHi1, 0, sizeof(_toneLevelIdxHi1));
02008     memset(_toneLevelIdxMid, 0, sizeof(_toneLevelIdxMid));
02009     memset(_toneLevelIdxHi2, 0, sizeof(_toneLevelIdxHi2));
02010 
02011     _subPacketsB = 0;
02012     subPacketsD = 0;
02013 
02014     average_quantized_coeffs(); // average elements in quantized_coeffs[max_ch][10][8]
02015 
02016     Common::BitStreamMemoryStream packetStream(_compressedData, _packetSize + FF_INPUT_BUFFER_PADDING_SIZE);
02017     Common::BitStreamMemory32LELSB packetBitStream(packetStream);
02018     //qdm2_decode_sub_packet_header
02019     header.type = packetBitStream.getBits(8);
02020 
02021     if (header.type == 0) {
02022         header.size = 0;
02023         header.data = NULL;
02024     } else {
02025         header.size = packetBitStream.getBits(8);
02026 
02027         if (header.type & 0x80) {
02028             header.size <<= 8;
02029             header.size |= packetBitStream.getBits(8);
02030             header.type &= 0x7f;
02031         }
02032 
02033         if (header.type == 0x7f)
02034             header.type |= (packetBitStream.getBits(8) << 8);
02035 
02036         header.data = &_compressedData[packetBitStream.pos() / 8];
02037     }
02038 
02039     if (header.type < 2 || header.type >= 8) {
02040         _hasErrors = true;
02041         error("QDM2 : bad superblock type");
02042         return;
02043     }
02044 
02045     _superblocktype_2_3 = (header.type == 2 || header.type == 3);
02046     packet_bytes = (_packetSize - packetBitStream.pos() / 8);
02047 
02048     Common::BitStreamMemoryStream headerStream(header.data, header.size + FF_INPUT_BUFFER_PADDING_SIZE);
02049     Common::BitStreamMemory32LELSB headerBitStream(headerStream);
02050 
02051     if (header.type == 2 || header.type == 4 || header.type == 5) {
02052         int csum = 257 * headerBitStream.getBits(8) + 2 * headerBitStream.getBits(8);
02053 
02054         csum = qdm2_packet_checksum(_compressedData, _packetSize, csum);
02055 
02056         if (csum != 0) {
02057             _hasErrors = true;
02058             error("QDM2 : bad packet checksum");
02059             return;
02060         }
02061     }
02062 
02063     _subPacketListB[0].packet = NULL;
02064     _subPacketListD[0].packet = NULL;
02065 
02066     for (i = 0; i < 6; i++)
02067         if (--_fftLevelExp[i] < 0)
02068             _fftLevelExp[i] = 0;
02069 
02070     for (i = 0; packet_bytes > 0; i++) {
02071         int j;
02072 
02073         _subPacketListA[i].next = NULL;
02074 
02075         if (i > 0) {
02076             _subPacketListA[i - 1].next = &_subPacketListA[i];
02077 
02078             if (next_index >= header.size)
02079                 break;
02080 
02081             // seek to next block
02082             headerBitStream.skip(next_index * 8 - headerBitStream.pos());
02083         }
02084 
02085         // decode subpacket
02086         packet = &_subPackets[i];
02087         //qdm2_decode_sub_packet_header
02088         packet->type = headerBitStream.getBits(8);
02089 
02090         if (packet->type == 0) {
02091             packet->size = 0;
02092             packet->data = NULL;
02093         } else {
02094             packet->size = headerBitStream.getBits(8);
02095 
02096             if (packet->type & 0x80) {
02097                 packet->size <<= 8;
02098                 packet->size |= headerBitStream.getBits(8);
02099                 packet->type &= 0x7f;
02100             }
02101 
02102             if (packet->type == 0x7f)
02103                 packet->type |= (headerBitStream.getBits(8) << 8);
02104 
02105             packet->data = &header.data[headerBitStream.pos() / 8];
02106         }
02107 
02108         next_index = packet->size + headerBitStream.pos() / 8;
02109         sub_packet_size = ((packet->size > 0xff) ? 1 : 0) + packet->size + 2;
02110 
02111         if (packet->type == 0)
02112             break;
02113 
02114         if (sub_packet_size > packet_bytes) {
02115             if (packet->type != 10 && packet->type != 11 && packet->type != 12)
02116                 break;
02117             packet->size += packet_bytes - sub_packet_size;
02118         }
02119 
02120         packet_bytes -= sub_packet_size;
02121 
02122         // add subpacket to 'all subpackets' list
02123         _subPacketListA[i].packet = packet;
02124 
02125         // add subpacket to related list
02126         if (packet->type == 8) {
02127             error("Unsupported packet type 8");
02128             return;
02129         } else if (packet->type >= 9 && packet->type <= 12) {
02130             // packets for MPEG Audio like Synthesis Filter
02131             QDM2_LIST_ADD(_subPacketListD, subPacketsD, packet);
02132         } else if (packet->type == 13) {
02133             for (j = 0; j < 6; j++)
02134                 _fftLevelExp[j] = headerBitStream.getBits(6);
02135         } else if (packet->type == 14) {
02136             for (j = 0; j < 6; j++)
02137                 _fftLevelExp[j] = qdm2_get_vlc(&headerBitStream, &_fftLevelExpVlc, 0, 2);
02138         } else if (packet->type == 15) {
02139             error("Unsupported packet type 15");
02140             return;
02141         } else if (packet->type >= 16 && packet->type < 48 && !fft_subpackets[packet->type - 16]) {
02142             // packets for FFT
02143             QDM2_LIST_ADD(_subPacketListB, _subPacketsB, packet);
02144         }
02145     } // Packet bytes loop
02146 
02147 // ****************************************************************
02148     if (_subPacketListD[0].packet != NULL) {
02149         process_synthesis_subpackets(_subPacketListD);
02150         _doSynthFilter = 1;
02151     } else if (_doSynthFilter) {
02152         process_subpacket_10(NULL, 0);
02153         process_subpacket_11(NULL, 0);
02154         process_subpacket_12(NULL, 0);
02155     }
02156 // ****************************************************************
02157 }
02158 
02159 void QDM2Stream::qdm2_fft_init_coefficient(int sub_packet, int offset, int duration,
02160                                            int channel, int exp, int phase) {
02161     if (_fftCoefsMinIndex[duration] < 0)
02162         _fftCoefsMinIndex[duration] = _fftCoefsIndex;
02163 
02164     _fftCoefs[_fftCoefsIndex].sub_packet = ((sub_packet >= 16) ? (sub_packet - 16) : sub_packet);
02165     _fftCoefs[_fftCoefsIndex].channel = channel;
02166     _fftCoefs[_fftCoefsIndex].offset = offset;
02167     _fftCoefs[_fftCoefsIndex].exp = exp;
02168     _fftCoefs[_fftCoefsIndex].phase = phase;
02169     _fftCoefsIndex++;
02170 }
02171 
02172 void QDM2Stream::qdm2_fft_decode_tones(int duration, Common::BitStreamMemory32LELSB *gb, int b) {
02173     int channel, stereo, phase, exp;
02174     int local_int_4,  local_int_8,  stereo_phase,  local_int_10;
02175     int local_int_14, stereo_exp, local_int_20, local_int_28;
02176     int n, offset;
02177 
02178     local_int_4 = 0;
02179     local_int_28 = 0;
02180     local_int_20 = 2;
02181     local_int_8 = (4 - duration);
02182     local_int_10 = 1 << (_groupOrder - duration - 1);
02183     offset = 1;
02184 
02185     while (1) {
02186         if (_superblocktype_2_3) {
02187             while ((n = qdm2_get_vlc(gb, &_vlcTabFftToneOffset[local_int_8], 1, 2)) < 2) {
02188                 offset = 1;
02189                 if (n == 0) {
02190                     local_int_4 += local_int_10;
02191                     local_int_28 += (1 << local_int_8);
02192                 } else {
02193                     local_int_4 += 8*local_int_10;
02194                     local_int_28 += (8 << local_int_8);
02195                 }
02196             }
02197             offset += (n - 2);
02198         } else {
02199             offset += qdm2_get_vlc(gb, &_vlcTabFftToneOffset[local_int_8], 1, 2);
02200             while (offset >= (local_int_10 - 1)) {
02201                 offset += (1 - (local_int_10 - 1));
02202                 local_int_4  += local_int_10;
02203                 local_int_28 += (1 << local_int_8);
02204             }
02205         }
02206 
02207         if (local_int_4 >= _blockSize)
02208             return;
02209 
02210         local_int_14 = (offset >> local_int_8);
02211 
02212         if (_channels > 1) {
02213             channel = gb->getBit();
02214             stereo = gb->getBit();
02215         } else {
02216             channel = 0;
02217             stereo = 0;
02218         }
02219 
02220         exp = qdm2_get_vlc(gb, (b ? &_fftLevelExpVlc : &_fftLevelExpAltVlc), 0, 2);
02221         exp += _fftLevelExp[fft_level_index_table[local_int_14]];
02222         exp = (exp < 0) ? 0 : exp;
02223 
02224         phase = gb->getBits(3);
02225         stereo_exp = 0;
02226         stereo_phase = 0;
02227 
02228         if (stereo) {
02229             stereo_exp = (exp - qdm2_get_vlc(gb, &_fftStereoExpVlc, 0, 1));
02230             stereo_phase = (phase - qdm2_get_vlc(gb, &_fftStereoPhaseVlc, 0, 1));
02231             if (stereo_phase < 0)
02232                 stereo_phase += 8;
02233         }
02234 
02235         if (_frequencyRange > (local_int_14 + 1)) {
02236             int sub_packet = (local_int_20 + local_int_28);
02237 
02238             qdm2_fft_init_coefficient(sub_packet, offset, duration, channel, exp, phase);
02239             if (stereo)
02240                 qdm2_fft_init_coefficient(sub_packet, offset, duration, (1 - channel), stereo_exp, stereo_phase);
02241         }
02242 
02243         offset++;
02244     }
02245 }
02246 
02247 void QDM2Stream::qdm2_decode_fft_packets(void) {
02248     int i, j, min, max, value, type, unknown_flag;
02249 
02250     if (_subPacketListB[0].packet == NULL)
02251         return;
02252 
02253     // reset minimum indexes for FFT coefficients
02254     _fftCoefsIndex = 0;
02255     for (i=0; i < 5; i++)
02256         _fftCoefsMinIndex[i] = -1;
02257 
02258     // process subpackets ordered by type, largest type first
02259     for (i = 0, max = 256; i < _subPacketsB; i++) {
02260         QDM2SubPacket *packet= NULL;
02261 
02262         // find subpacket with largest type less than max
02263         for (j = 0, min = 0; j < _subPacketsB; j++) {
02264             value = _subPacketListB[j].packet->type;
02265             if (value > min && value < max) {
02266                 min = value;
02267                 packet = _subPacketListB[j].packet;
02268             }
02269         }
02270 
02271         max = min;
02272 
02273         // check for errors (?)
02274         if (!packet)
02275             return;
02276 
02277         if (i == 0 && (packet->type < 16 || packet->type >= 48 || fft_subpackets[packet->type - 16]))
02278             return;
02279 
02280         // decode FFT tones
02281         Common::BitStreamMemoryStream d(packet->data, packet->size + FF_INPUT_BUFFER_PADDING_SIZE);
02282         Common::BitStreamMemory32LELSB gb(&d);
02283 
02284         if (packet->type >= 32 && packet->type < 48 && !fft_subpackets[packet->type - 16])
02285             unknown_flag = 1;
02286         else
02287             unknown_flag = 0;
02288 
02289         type = packet->type;
02290 
02291         if ((type >= 17 && type < 24) || (type >= 33 && type < 40)) {
02292             int duration = _subSampling + 5 - (type & 15);
02293 
02294             if (duration >= 0 && duration < 4) { // TODO: Should be <= 4?
02295                 qdm2_fft_decode_tones(duration, &gb, unknown_flag);
02296             }
02297         } else if (type == 31) {
02298             for (j=0; j < 4; j++) {
02299                 qdm2_fft_decode_tones(j, &gb, unknown_flag);
02300             }
02301         } else if (type == 46) {
02302             for (j=0; j < 6; j++)
02303                 _fftLevelExp[j] = gb.getBits(6);
02304             for (j=0; j < 4; j++) {
02305                 qdm2_fft_decode_tones(j, &gb, unknown_flag);
02306             }
02307         }
02308     } // Loop on B packets
02309 
02310     // calculate maximum indexes for FFT coefficients
02311     for (i = 0, j = -1; i < 5; i++)
02312         if (_fftCoefsMinIndex[i] >= 0) {
02313             if (j >= 0)
02314                 _fftCoefsMaxIndex[j] = _fftCoefsMinIndex[i];
02315             j = i;
02316         }
02317     if (j >= 0)
02318         _fftCoefsMaxIndex[j] = _fftCoefsIndex;
02319 }
02320 
02321 void QDM2Stream::qdm2_fft_generate_tone(FFTTone *tone)
02322 {
02323     float level, f[6];
02324     int i;
02325     QDM2Complex c;
02326     const double iscale = 2.0 * M_PI / 512.0;
02327 
02328     tone->phase += tone->phase_shift;
02329 
02330     // calculate current level (maximum amplitude) of tone
02331     level = fft_tone_envelope_table[tone->duration][tone->time_index] * tone->level;
02332     c.im = level * sin(tone->phase*iscale);
02333     c.re = level * cos(tone->phase*iscale);
02334 
02335     // generate FFT coefficients for tone
02336     if (tone->duration >= 3 || tone->cutoff >= 3) {
02337         tone->complex[0].im += c.im;
02338         tone->complex[0].re += c.re;
02339         tone->complex[1].im -= c.im;
02340         tone->complex[1].re -= c.re;
02341     } else {
02342         f[1] = -tone->table[4];
02343         f[0] =  tone->table[3] - tone->table[0];
02344         f[2] =  1.0 - tone->table[2] - tone->table[3];
02345         f[3] =  tone->table[1] + tone->table[4] - 1.0;
02346         f[4] =  tone->table[0] - tone->table[1];
02347         f[5] =  tone->table[2];
02348         for (i = 0; i < 2; i++) {
02349             tone->complex[fft_cutoff_index_table[tone->cutoff][i]].re += c.re * f[i];
02350             tone->complex[fft_cutoff_index_table[tone->cutoff][i]].im += c.im *((tone->cutoff <= i) ? -f[i] : f[i]);
02351         }
02352         for (i = 0; i < 4; i++) {
02353             tone->complex[i].re += c.re * f[i+2];
02354             tone->complex[i].im += c.im * f[i+2];
02355         }
02356     }
02357 
02358     // copy the tone if it has not yet died out
02359     if (++tone->time_index < ((1 << (5 - tone->duration)) - 1)) {
02360         memcpy(&_fftTones[_fftToneEnd], tone, sizeof(FFTTone));
02361         _fftToneEnd = (_fftToneEnd + 1) % 1000;
02362     }
02363 }
02364 
02365 void QDM2Stream::qdm2_fft_tone_synthesizer(uint8 sub_packet) {
02366     int i, j, ch;
02367     const double iscale = 0.25 * M_PI;
02368 
02369     for (ch = 0; ch < _channels; ch++) {
02370         memset(_fft.complex[ch], 0, _frameSize * sizeof(QDM2Complex));
02371     }
02372 
02373     // apply FFT tones with duration 4 (1 FFT period)
02374     if (_fftCoefsMinIndex[4] >= 0)
02375         for (i = _fftCoefsMinIndex[4]; i < _fftCoefsMaxIndex[4]; i++) {
02376             float level;
02377             QDM2Complex c;
02378 
02379             if (_fftCoefs[i].sub_packet != sub_packet)
02380                 break;
02381 
02382             ch = (_channels == 1) ? 0 : _fftCoefs[i].channel;
02383             level = (_fftCoefs[i].exp < 0) ? 0.0 : fft_tone_level_table[_superblocktype_2_3 ? 0 : 1][_fftCoefs[i].exp & 63];
02384 
02385             c.re = level * cos(_fftCoefs[i].phase * iscale);
02386             c.im = level * sin(_fftCoefs[i].phase * iscale);
02387             _fft.complex[ch][_fftCoefs[i].offset + 0].re += c.re;
02388             _fft.complex[ch][_fftCoefs[i].offset + 0].im += c.im;
02389             _fft.complex[ch][_fftCoefs[i].offset + 1].re -= c.re;
02390             _fft.complex[ch][_fftCoefs[i].offset + 1].im -= c.im;
02391         }
02392 
02393     // generate existing FFT tones
02394     for (i = _fftToneEnd; i != _fftToneStart; ) {
02395         qdm2_fft_generate_tone(&_fftTones[_fftToneStart]);
02396         _fftToneStart = (_fftToneStart + 1) % 1000;
02397     }
02398 
02399     // create and generate new FFT tones with duration 0 (long) to 3 (short)
02400     for (i = 0; i < 4; i++)
02401         if (_fftCoefsMinIndex[i] >= 0) {
02402             for (j = _fftCoefsMinIndex[i]; j < _fftCoefsMaxIndex[i]; j++) {
02403                 int offset, four_i;
02404                 FFTTone tone;
02405 
02406                 if (_fftCoefs[j].sub_packet != sub_packet)
02407                     break;
02408 
02409                 four_i = (4 - i);
02410                 offset = _fftCoefs[j].offset >> four_i;
02411                 ch = (_channels == 1) ? 0 : _fftCoefs[j].channel;
02412 
02413                 if (offset < _frequencyRange) {
02414                     if (offset < 2)
02415                         tone.cutoff = offset;
02416                     else
02417                         tone.cutoff = (offset >= 60) ? 3 : 2;
02418 
02419                     tone.level = (_fftCoefs[j].exp < 0) ? 0.0 : fft_tone_level_table[_superblocktype_2_3 ? 0 : 1][_fftCoefs[j].exp & 63];
02420                     tone.complex = &_fft.complex[ch][offset];
02421                     tone.table = fft_tone_sample_table[i][_fftCoefs[j].offset - (offset << four_i)];
02422                     tone.phase = 64 * _fftCoefs[j].phase - (offset << 8) - 128;
02423                     tone.phase_shift = (2 * _fftCoefs[j].offset + 1) << (7 - four_i);
02424                     tone.duration = i;
02425                     tone.time_index = 0;
02426 
02427                     qdm2_fft_generate_tone(&tone);
02428                 }
02429             }
02430             _fftCoefsMinIndex[i] = j;
02431         }
02432 }
02433 
02434 void QDM2Stream::qdm2_calculate_fft(int channel) {
02435     _fft.complex[channel][0].re *= 2.0f;
02436     _fft.complex[channel][0].im = 0.0f;
02437 
02438     _rdft->calc((float *)_fft.complex[channel]);
02439 
02440     // add samples to output buffer
02441     for (int i = 0; i < ((_fftFrameSize + 15) & ~15); i++)
02442         _outputBuffer[_channels * i + channel] += ((float *) _fft.complex[channel])[i];
02443 }
02444 
02448 void QDM2Stream::qdm2_synthesis_filter(uint8 index)
02449 {
02450     int16 samples[MPA_MAX_CHANNELS * MPA_FRAME_SIZE];
02451     int i, k, ch, sb_used, sub_sampling, dither_state = 0;
02452 
02453     // copy sb_samples
02454     sb_used = QDM2_SB_USED(_subSampling);
02455 
02456     for (ch = 0; ch < _channels; ch++)
02457         for (i = 0; i < 8; i++)
02458             for (k = sb_used; k < 32; k++)
02459                 _sbSamples[ch][(8 * index) + i][k] = 0;
02460 
02461     for (ch = 0; ch < _channels; ch++) {
02462         int16 *samples_ptr = samples + ch;
02463 
02464         for (i = 0; i < 8; i++) {
02465             ff_mpa_synth_filter(_synthBuf[ch], &(_synthBufOffset[ch]),
02466                                 ff_mpa_synth_window, &dither_state,
02467                                 samples_ptr, _channels,
02468                                 _sbSamples[ch][(8 * index) + i]);
02469             samples_ptr += 32 * _channels;
02470         }
02471     }
02472 
02473     // add samples to output buffer
02474     sub_sampling = (4 >> _subSampling);
02475 
02476     for (ch = 0; ch < _channels; ch++)
02477         for (i = 0; i < _sFrameSize; i++)
02478             _outputBuffer[_channels * i + ch] += (float)(samples[_channels * sub_sampling * i + ch] >> (sizeof(int16)*8-16));
02479 }
02480 
02481 bool QDM2Stream::qdm2_decodeFrame(Common::SeekableReadStream &in, QueuingAudioStream *audioStream) {
02482     debug(1, "QDM2Stream::qdm2_decodeFrame in.pos(): %d in.size(): %d", in.pos(), in.size());
02483     int ch, i;
02484     const int frame_size = (_sFrameSize * _channels);
02485 
02486     // If we're in any packet but the first, seek back to the first
02487     if (_subPacket == 0)
02488         _superBlockStart = in.pos();
02489     else
02490         in.seek(_superBlockStart);
02491 
02492     // select input buffer
02493     if (in.eos() || in.pos() >= in.size()) {
02494         debug(1, "QDM2Stream::qdm2_decodeFrame End of Input Stream");
02495         return false;
02496     }
02497 
02498     if ((in.size() - in.pos()) < _packetSize) {
02499         debug(1, "QDM2Stream::qdm2_decodeFrame Insufficient Packet Data in Input Stream Found: %d Need: %d", in.size() - in.pos(), _packetSize);
02500         return false;
02501     }
02502 
02503     if (!in.eos()) {
02504         in.read(_compressedData, _packetSize);
02505         memset(_compressedData + _packetSize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
02506         debug(1, "QDM2Stream::qdm2_decodeFrame constructed input data");
02507     }
02508 
02509     // copy old block, clear new block of output samples
02510     memmove(_outputBuffer, &_outputBuffer[frame_size], frame_size * sizeof(float));
02511     memset(&_outputBuffer[frame_size], 0, frame_size * sizeof(float));
02512     debug(1, "QDM2Stream::qdm2_decodeFrame cleared outputBuffer");
02513 
02514     if (!in.eos()) {
02515         // decode block of QDM2 compressed data
02516         debug(1, "QDM2Stream::qdm2_decodeFrame decode block of QDM2 compressed data");
02517         if (_subPacket == 0) {
02518             _hasErrors = false; // reset it for a new super block
02519             debug(1, "QDM2 : Superblock follows");
02520             qdm2_decode_super_block();
02521         }
02522 
02523         // parse subpackets
02524         debug(1, "QDM2Stream::qdm2_decodeFrame parse subpackets");
02525         if (!_hasErrors) {
02526             if (_subPacket == 2) {
02527                 debug(1, "QDM2Stream::qdm2_decodeFrame qdm2_decode_fft_packets()");
02528                 qdm2_decode_fft_packets();
02529             }
02530 
02531             debug(1, "QDM2Stream::qdm2_decodeFrame qdm2_fft_tone_synthesizer(%d)", _subPacket);
02532             qdm2_fft_tone_synthesizer(_subPacket);
02533         }
02534 
02535         // sound synthesis stage 1 (FFT)
02536         debug(1, "QDM2Stream::qdm2_decodeFrame sound synthesis stage 1 (FFT)");
02537         for (ch = 0; ch < _channels; ch++) {
02538             qdm2_calculate_fft(ch);
02539 
02540             if (!_hasErrors && _subPacketListC[0].packet != NULL) {
02541                 error("QDM2 : has errors, and C list is not empty");
02542                 return false;
02543             }
02544         }
02545 
02546         // sound synthesis stage 2 (MPEG audio like synthesis filter)
02547         debug(1, "QDM2Stream::qdm2_decodeFrame sound synthesis stage 2 (MPEG audio like synthesis filter)");
02548         if (!_hasErrors && _doSynthFilter)
02549             qdm2_synthesis_filter(_subPacket);
02550 
02551         _subPacket = (_subPacket + 1) % 16;
02552 
02553         if(_hasErrors)
02554             warning("QDM2 Packet error...");
02555 
02556         // clip and convert output float[] to 16bit signed samples
02557         debug(1, "QDM2Stream::qdm2_decodeFrame clip and convert output float[] to 16bit signed samples");
02558     }
02559 
02560     if (frame_size == 0)
02561         return false;
02562 
02563     // Prepare a buffer for queuing
02564     uint16 *outputBuffer = (uint16 *)malloc(frame_size * 2);
02565 
02566     for (i = 0; i < frame_size; i++) {
02567         int value = (int)_outputBuffer[i];
02568 
02569         if (value > SOFTCLIP_THRESHOLD)
02570             value = (value >  HARDCLIP_THRESHOLD) ?  32767 :  _softclipTable[ value - SOFTCLIP_THRESHOLD];
02571         else if (value < -SOFTCLIP_THRESHOLD)
02572             value = (value < -HARDCLIP_THRESHOLD) ? -32767 : -_softclipTable[-value - SOFTCLIP_THRESHOLD];
02573 
02574         outputBuffer[i] = value;
02575     }
02576 
02577     // Queue the translated buffer to our stream
02578     byte flags = FLAG_16BITS;
02579 
02580     if (_channels == 2)
02581         flags |= FLAG_STEREO;
02582 
02583 #ifdef SCUMM_LITTLE_ENDIAN
02584     flags |= FLAG_LITTLE_ENDIAN;
02585 #endif
02586 
02587     audioStream->queueBuffer((byte *)outputBuffer, frame_size * 2, DisposeAfterUse::YES, flags);
02588 
02589     return true;
02590 }
02591 
02592 AudioStream *QDM2Stream::decodeFrame(Common::SeekableReadStream &stream) {
02593     QueuingAudioStream *audioStream = makeQueuingAudioStream(_sampleRate, _channels == 2);
02594 
02595     while (qdm2_decodeFrame(stream, audioStream))
02596         ;
02597 
02598     audioStream->finish();
02599     return audioStream;
02600 }
02601 
02602 Codec *makeQDM2Decoder(Common::SeekableReadStream *extraData, DisposeAfterUse::Flag disposeExtraData) {
02603     return new QDM2Stream(extraData, disposeExtraData);
02604 }
02605 
02606 } // End of namespace Audio
02607 
02608 #endif


Generated on Sat Feb 16 2019 05:01:01 for ResidualVM by doxygen 1.7.1
curved edge   curved edge