xoreos  0.0.5
wma.cpp
Go to the documentation of this file.
1 /* xoreos - A reimplementation of BioWare's Aurora engine
2  *
3  * xoreos is the legal property of its developers, whose names
4  * can be found in the AUTHORS file distributed with this source
5  * distribution.
6  *
7  * xoreos is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 3
10  * of the License, or (at your option) any later version.
11  *
12  * xoreos is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with xoreos. If not, see <http://www.gnu.org/licenses/>.
19  */
20 
25 /* Based on the WMA implementation in FFmpeg (<https://ffmpeg.org/)>,
26  * which is released under the terms of version 2 or later of the GNU
27  * Lesser General Public License.
28  *
29  * The original copyright note in libavcodec/wma.c reads as follows:
30  *
31  * WMA compatible codec
32  * Copyright (c) 2002-2007 The FFmpeg Project
33  *
34  * This file is part of FFmpeg.
35  *
36  * FFmpeg is free software; you can redistribute it and/or
37  * modify it under the terms of the GNU Lesser General Public
38  * License as published by the Free Software Foundation; either
39  * version 2.1 of the License, or (at your option) any later version.
40  *
41  * FFmpeg is distributed in the hope that it will be useful,
42  * but WITHOUT ANY WARRANTY; without even the implied warranty of
43  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
44  * Lesser General Public License for more details.
45  *
46  * You should have received a copy of the GNU Lesser General Public
47  * License along with FFmpeg; if not, write to the Free Software
48  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
49  */
50 
51 #include <cassert>
52 #include <cstring>
53 
54 #include <vector>
55 
56 #include "src/common/util.h"
57 #include "src/common/debug.h"
58 #include "src/common/error.h"
59 #include "src/common/maths.h"
60 #include "src/common/sinewindows.h"
62 #include "src/common/mdct.h"
63 #include "src/common/bitstream.h"
64 #include "src/common/huffman.h"
65 #include "src/common/types.h"
66 #include "src/common/scopedptr.h"
67 #include "src/common/ptrvector.h"
68 
69 #include "src/sound/audiostream.h"
70 
72 #include "src/sound/decoders/pcm.h"
73 #include "src/sound/decoders/wma.h"
75 
76 namespace Sound {
77 
78 static inline void butterflyFloats(float *v1, float *v2, int len) {
79  while (len-- > 0) {
80  float t = *v1 - *v2;
81 
82  *v1++ += *v2;
83  *v2++ = t;
84  }
85 }
86 
87 static inline void vectorFMulAdd(float *dst, const float *src0,
88  const float *src1, const float *src2, int len) {
89  while (len-- > 0)
90  *dst++ = *src0++ * *src1++ + *src2++;
91 }
92 
93 static inline void vectorFMulReverse(float *dst, const float *src0,
94  const float *src1, int len) {
95  src1 += len - 1;
96 
97  while (len-- > 0)
98  *dst++ = *src0++ * *src1--;
99 }
100 
101 struct WMACoefHuffmanParam;
102 
104 public:
105  WMACodec(int version, uint32 sampleRate, uint8 channels,
106  uint32 bitRate, uint32 blockAlign, Common::SeekableReadStream *extraData = 0);
107  ~WMACodec();
108 
109  // AudioStream API
110  int getChannels() const { return _channels; }
111  int getRate() const { return _sampleRate; }
112  bool endOfData() const { return _audStream->endOfData(); }
113  bool endOfStream() const { return _audStream->endOfStream(); }
114  size_t readBuffer(int16 *buffer, const size_t numSamples) { return _audStream->readBuffer(buffer, numSamples); }
115 
116  // PacketizedAudioStream API
117  void finish() { _audStream->finish(); }
118  bool isFinished() const { return _audStream->isFinished(); }
120 
121 private:
122  static const int kChannelsMax = 2;
123 
124  static const int kBlockBitsMin = 7;
125  static const int kBlockBitsMax = 11;
126 
128  static const int kBlockSizeMax = (1 << kBlockBitsMax);
129 
130  static const int kBlockNBSizes = (kBlockBitsMax - kBlockBitsMin + 1);
131 
133  static const int kSuperframeSizeMax = 16384;
134 
136  static const int kHighBandSizeMax = 16;
137 
139  static const int kNoiseTabSize = 8192;
140 
142  static const int kLSPPowBits = 7;
143 
144  int _version;
145 
151 
156 
158 
159  int _curFrame;
160  int _frameLen;
163  int _framePos;
164 
165  int _curBlock;
166  int _blockLen;
170 
172 
173  // Coefficients
181 
183 
185 
189 
190  // Noise
191  float _noiseMult;
194 
196 
197  // Exponents
201 
203 
204  // Coded values in high bands
207 
208  // Coefficients
211 
212  // Line spectral pairs
214  float _lspPowETable[256];
217 
218  // MDCT
220  std::vector<const float *> _mdctWindow;
221 
226 
227  // Output
228  float _output[kBlockSizeMax * 2];
230 
231  // Backing stream for PacketizedAudioStream
233 
234  // Init helpers
235 
236  void init(Common::SeekableReadStream *extraData);
237 
239  void evalFlags(uint16 flags, Common::SeekableReadStream *extraData);
240  int getFrameBitLength();
241  int getBlockSizeCount(uint16 flags);
243  bool useNoiseCoding(float &highFreq, float &bps);
244  void evalMDCTScales(float highFreq);
245  void initNoise();
246  void initCoefHuffman(float bps);
247  void initMDCT();
248  void initExponents();
249 
251  Common::ScopedArray<float> &levelTable,
252  Common::ScopedArray<uint16> &intTable,
253  const WMACoefHuffmanParam &params);
254  void initLSPToCurve();
255 
256  // Decoding
257 
259  bool decodeFrame(Common::BitStream &bits, int16 *outputData);
260  int decodeBlock(Common::BitStream &bits);
262 
263  // Decoding helpers
264 
266  bool decodeChannels(Common::BitStream &bits, int bSize, bool msStereo, bool *hasChannel);
267  bool calculateIMDCT(int bSize, bool msStereo, bool *hasChannel);
268 
269  void calculateCoefCount(int *coefCount, int bSize) const;
270  bool decodeNoise(Common::BitStream &bits, int bSize, bool *hasChannel, int *coefCount);
271  bool decodeExponents(Common::BitStream &bits, int bSize, bool *hasChannel);
272  bool decodeSpectralCoef(Common::BitStream &bits, bool msStereo, bool *hasChannel,
273  int *coefCount, int coefBitCount);
274  float getNormalizedMDCTLength() const;
275  void calculateMDCTCoefficients(int bSize, bool *hasChannel,
276  int *coefCount, int totalGain, float mdctNorm);
277 
278  bool decodeExpHuffman(Common::BitStream &bits, int ch);
279  bool decodeExpLSP(Common::BitStream &bits, int ch);
280  bool decodeRunLevel(Common::BitStream &bits, const Common::Huffman &huffman,
281  const float *levelTable, const uint16 *runTable, int version, float *ptr,
282  int offset, int numCoefs, int blockLen, int frameLenBits, int coefNbBits);
283 
284  void lspToCurve(float *out, float *val_max_ptr, int n, float *lsp);
285 
286  void window(float *out) const;
287 
288  float pow_m1_4(float x) const;
289 
290  static int readTotalGain(Common::BitStream &bits);
291  static int totalGainToBits(int totalGain);
292  static uint32 getLargeVal(Common::BitStream &bits);
293 };
294 
295 
296 WMACodec::WMACodec(int version, uint32 sampleRate, uint8 channels,
297  uint32 bitRate, uint32 blockAlign, Common::SeekableReadStream *extraData) :
298  _version(version), _sampleRate(sampleRate), _channels(channels),
299  _bitRate(bitRate), _blockAlign(blockAlign), _audioFlags(0),
300  _resetBlockLengths(true), _curFrame(0), _frameLen(0), _frameLenBits(0),
301  _blockSizeCount(0), _framePos(0), _curBlock(0), _blockLen(0), _blockLenBits(0),
302  _nextBlockLenBits(0), _prevBlockLenBits(0), _byteOffsetBits(0),
303  _lastSuperframeLen(0), _lastBitoffset(0) {
304 
305  for (int i = 0; i < 2; i++)
306  _coefHuffmanParam[i] = 0;
307 
308  if ((_version != 1) && (_version != 2))
309  throw Common::Exception("WMACodec::init(): Unsupported WMA version %d", _version);
310 
311  if ((_sampleRate == 0) || (_sampleRate > 50000))
312  throw Common::Exception("WMACodec::init(): Invalid sample rate %d", _sampleRate);
313  if ((_channels == 0) || (_channels > kChannelsMax))
314  throw Common::Exception("WMACodec::init(): Unsupported number of channels %d",
315  _channels);
316 
318 
319 #ifdef XOREOS_LITTLE_ENDIAN
321 #endif
322 
323  init(extraData);
324 
326 }
327 
329 }
330 
332  // Flags
333  uint16 flags = getFlags(extraData);
334  evalFlags(flags, extraData);
335 
336  // Frame length
338  _frameLen = 1 << _frameLenBits;
339 
340  // Number of MDCT block sizes
342 
343  float bps = ((float) _bitRate) / ((float) (_channels * _sampleRate));
344 
345  _byteOffsetBits = Common::intLog2((int) (bps * _frameLen / 8.0 + 0.05)) + 2;
346 
347  // Compute high frequency value and choose if noise coding should be activated
348  float highFreq;
349  _useNoiseCoding = useNoiseCoding(highFreq, bps);
350 
351  // Compute the scale factor band sizes for each MDCT block size
352  evalMDCTScales(highFreq);
353 
354  // Init the noise generator
355  initNoise();
356 
357  // Init the coefficient Huffman codes
358  initCoefHuffman(bps);
359 
360  // Init MDCTs
361  initMDCT();
362 
363  // Init exponent codes
364  initExponents();
365 
366  // Clear the sample output buffers
367  std::memset(_output , 0, sizeof(_output));
368  std::memset(_frameOut, 0, sizeof(_frameOut));
369 }
370 
372  if ((_version == 1) && extraData && (extraData->size() >= 4)) {
373  extraData->seek(2);
374  return extraData->readUint16LE();
375  }
376 
377  if ((_version == 2) && extraData && (extraData->size() >= 6)) {
378  extraData->seek(4);
379  return extraData->readUint16LE();
380  }
381 
382  return 0;
383 }
384 
386  _useExpHuffman = (flags & 0x0001) != 0;
387  _useBitReservoir = (flags & 0x0002) != 0;
388  _useVariableBlockLen = (flags & 0x0004) != 0;
389 
390  if ((_version == 2) && extraData && (extraData->size() >= 8)) {
391  extraData->seek(4);
392  if ((extraData->readUint16LE() == 0x000D) && _useVariableBlockLen) {
393  // Apparently, this fixes ffmpeg "issue1503"
394 
395  _useVariableBlockLen = false;
396  }
397  }
398 }
399 
401  if (_sampleRate <= 16000)
402  return 9;
403 
404  if ((_sampleRate <= 22050) || (_sampleRate <= 32000 && _version == 1))
405  return 10;
406 
407  if (_sampleRate <= 48000)
408  return 11;
409 
410  if (_sampleRate <= 96000)
411  return 12;
412 
413  return 13;
414 }
415 
418  return 1;
419 
420  int count = ((flags >> 3) & 3) + 1;
421 
422  if ((_bitRate / _channels) >= 32000)
423  count += 2;
424 
425  const int maxCount = _frameLenBits - kBlockBitsMin;
426 
427  return MIN(count, maxCount) + 1;
428 }
429 
431  // Sample rates are only normalized in WMAv2
432  if (_version != 2)
433  return _sampleRate;
434 
435  if (_sampleRate>= 44100)
436  return 44100;
437 
438  if (_sampleRate >= 22050)
439  return 22050;
440 
441  if (_sampleRate >= 16000)
442  return 16000;
443 
444  if (_sampleRate >= 11025)
445  return 11025;
446 
447  if (_sampleRate >= 8000)
448  return 8000;
449 
450  return _sampleRate;
451 }
452 
453 bool WMACodec::useNoiseCoding(float &highFreq, float &bps) {
454  highFreq = _sampleRate * 0.5f;
455 
456  uint32 rateNormalized = getNormalizedSampleRate();
457 
458  float bpsOrig = bps;
459  if (_channels == 2)
460  bps = bpsOrig * 1.6f;
461 
462  if (rateNormalized == 44100) {
463  if (bps >= 0.61f)
464  return false;
465 
466  highFreq = highFreq * 0.4f;
467  return true;
468  }
469 
470  if (rateNormalized == 22050) {
471  if (bps >= 1.16f)
472  return false;
473 
474  if (bps >= 0.72f)
475  highFreq = highFreq * 0.7f;
476  else
477  highFreq = highFreq * 0.6f;
478 
479  return true;
480  }
481 
482  if (rateNormalized == 16000) {
483  if (bpsOrig > 0.5f)
484  highFreq = highFreq * 0.5f;
485  else
486  highFreq = highFreq * 0.3f;
487 
488  return true;
489  }
490 
491  if (rateNormalized == 11025) {
492  highFreq = highFreq * 0.7f;
493  return true;
494  }
495 
496  if (rateNormalized == 8000) {
497  if (bpsOrig > 0.75f)
498  return false;
499 
500  if (bpsOrig <= 0.625f)
501  highFreq = highFreq * 0.5f;
502  else
503  highFreq = highFreq * 0.65f;
504 
505  return true;
506  }
507 
508 
509  if (bpsOrig >= 0.8f)
510  highFreq = highFreq * 0.75f;
511  else if (bpsOrig >= 0.6f)
512  highFreq = highFreq * 0.6f;
513  else
514  highFreq = highFreq * 0.5f;
515 
516  return true;
517 }
518 
519 void WMACodec::evalMDCTScales(float highFreq) {
520  if (_version == 1)
521  _coefsStart = 3;
522  else
523  _coefsStart = 0;
524 
525  for (int k = 0; k < _blockSizeCount; k++) {
526  int blockLen = _frameLen >> k;
527 
528  if (_version == 1) {
529  int i, lpos = 0;
530 
531  for (i = 0; i < 25; i++) {
532  int a = wmaCriticalFreqs[i];
533  int b = _sampleRate;
534  int pos = ((blockLen * 2 * a) + (b >> 1)) / b;
535 
536  if (pos > blockLen)
537  pos = blockLen;
538 
539  _exponentBands[0][i] = pos - lpos;
540  if (pos >= blockLen) {
541  i++;
542  break;
543  }
544  lpos = pos;
545  }
546 
547  _exponentSizes[0] = i;
548 
549  } else {
550  // Hardcoded tables
551  const uint8 *table = 0;
552 
553  int t = _frameLenBits - kBlockBitsMin - k;
554  if (t < 3) {
555  if (_sampleRate >= 44100)
556  table = exponentBand44100[t];
557  else if (_sampleRate >= 32000)
558  table = exponentBand32000[t];
559  else if (_sampleRate >= 22050)
560  table = exponentBand22050[t];
561  }
562 
563  if (table) {
564  int n = *table++;
565 
566  for (int i = 0; i < n; i++)
567  _exponentBands[k][i] = table[i];
568 
569  _exponentSizes[k] = n;
570 
571  } else {
572  int j = 0, lpos = 0;
573 
574  for (int i = 0; i < 25; i++) {
575  int a = wmaCriticalFreqs[i];
576  int b = _sampleRate;
577  int pos = ((blockLen * 2 * a) + (b << 1)) / (4 * b);
578 
579  pos <<= 2;
580  if (pos > blockLen)
581  pos = blockLen;
582 
583  if (pos > lpos)
584  _exponentBands[k][j++] = pos - lpos;
585 
586  if (pos >= blockLen)
587  break;
588 
589  lpos = pos;
590  }
591 
592  _exponentSizes[k] = j;
593  }
594 
595  }
596 
597  // Max number of coefs
598  _coefsEnd[k] = (_frameLen - ((_frameLen * 9) / 100)) >> k;
599 
600  // High freq computation
601  _highBandStart[k] = (int)((blockLen * 2 * highFreq) / _sampleRate + 0.5f);
602 
603  int n = _exponentSizes[k];
604  int j = 0;
605  int pos = 0;
606 
607  for (int i = 0; i < n; i++) {
608  int start, end;
609 
610  start = pos;
611  pos += _exponentBands[k][i];
612  end = pos;
613 
614  if (start < _highBandStart[k])
615  start = _highBandStart[k];
616 
617  if (end > _coefsEnd[k])
618  end = _coefsEnd[k];
619 
620  if (end > start)
621  _exponentHighBands[k][j++] = end - start;
622 
623  }
624 
625  _exponentHighSizes[k] = j;
626  }
627 }
628 
630  if (!_useNoiseCoding)
631  return;
632 
633  _noiseMult = _useExpHuffman ? 0.02f : 0.04f;
634  _noiseIndex = 0;
635 
636  uint seed = 1;
637  float norm = (1.0f / (float)(1LL << 31)) * sqrt(3.0) * _noiseMult;
638 
639  for (int i = 0; i < kNoiseTabSize; i++) {
640  seed = seed * 314159 + 1;
641 
642  _noiseTable[i] = (float)((int)seed) * norm;
643  }
644 
646 }
647 
648 void WMACodec::initCoefHuffman(float bps) {
649  // Choose the parameter table
650  int coefHuffTable = 2;
651  if (_sampleRate >= 32000) {
652  if (bps < 0.72f) {
653  coefHuffTable = 0;
654  } else if (bps < 1.16f) {
655  coefHuffTable = 1;
656  }
657  }
658 
659  _coefHuffmanParam[0] = &coefHuffmanParam[coefHuffTable * 2 ];
660  _coefHuffmanParam[1] = &coefHuffmanParam[coefHuffTable * 2 + 1];
661 
666 }
667 
669  _mdct.reserve(_blockSizeCount);
670  for (int i = 0; i < _blockSizeCount; i++)
671  _mdct.push_back(new Common::MDCT(_frameLenBits - i + 1, true, 1.0f));
672 
673  // Init MDCT windows (simple sine window)
674  _mdctWindow.reserve(_blockSizeCount);
675  for (int i = 0; i < _blockSizeCount; i++)
677 }
678 
680  if (_useExpHuffman)
682  else
683  initLSPToCurve();
684 }
685 
687  Common::ScopedArray<float> &levelTable,
688  Common::ScopedArray<uint16> &intTable,
689  const WMACoefHuffmanParam &params) {
690 
691  Common::Huffman *huffman =
692  new Common::Huffman(0, params.n, params.huffCodes, params.huffBits);
693 
694  runTable.reset (new uint16[params.n]);
695  levelTable.reset(new float[params.n]);
696  intTable.reset (new uint16[params.n]);
697 
698  Common::ScopedArray<uint16> iLevelTable(new uint16[params.n]);
699 
700  int i = 2;
701  int level = 1;
702  int k = 0;
703 
704  while (i < params.n) {
705  intTable[k] = i;
706 
707  int l = params.levels[k++];
708 
709  for (int j = 0; j < l; j++) {
710  runTable [i] = j;
711  iLevelTable[i] = level;
712  levelTable [i] = level;
713 
714  i++;
715  }
716 
717  level++;
718  }
719 
720  return huffman;
721 }
722 
724  float wdel = M_PI / _frameLen;
725 
726  for (int i = 0; i < _frameLen; i++)
727  _lspCosTable[i] = 2.0f * cosf(wdel * i);
728 
729  // Tables for x^-0.25 computation
730  for (int i = 0; i < 256; i++) {
731  int e = i - 126;
732 
733  _lspPowETable[i] = powf(2.0f, e * -0.25f);
734  }
735 
736  // NOTE: These two tables are needed to avoid two operations in pow_m1_4
737  float b = 1.0f;
738  for (int i = (1 << kLSPPowBits) - 1; i >= 0; i--) {
739  int m = (1 << kLSPPowBits) + i;
740  float a = (float) m * (0.5f / (1 << kLSPPowBits));
741 
742  a = pow(a, -0.25f);
743 
744  _lspPowMTable1[i] = 2 * a - b;
745  _lspPowMTable2[i] = b - a;
746 
747  b = a;
748  }
749 }
750 
753  if (!stream)
754  return 0;
755 
756  return makePCMStream(stream, _sampleRate, _audioFlags, _channels, true);
757 }
758 
760  uint32 size = data.size();
761  if (size < _blockAlign) {
762  warning("WMACodec::decodeSuperFrame(): size < _blockAlign");
763  return 0;
764  }
765 
766  if (_blockAlign)
767  size = _blockAlign;
768 
769  Common::BitStream8MSB bits(data);
770 
771  int outputDataSize = 0;
772  Common::ScopedArray<int16> outputData;
773 
774  _curFrame = 0;
775 
776  if (_useBitReservoir) {
777  // This superframe consists of more than just one frame
778 
779  bits.skip(4); // Super frame index
780 
781  // Number of frames in this superframe
782  int newFrameCount = bits.getBits(4) - 1;
783  if (newFrameCount < 0) {
784  debugC(Common::kDebugSound, 1, "WMACodec::decodeSuperFrame(): newFrameCount == %d", newFrameCount);
785 
786  _resetBlockLengths = true;
787  _lastSuperframeLen = 0;
788  _lastBitoffset = 0;
789 
790  return 0;
791  }
792 
793  // Number of frames in this superframe + overhang from the last superframe
794  int frameCount = newFrameCount;
795  if (_lastSuperframeLen > 0)
796  frameCount++;
797 
798  // PCM output data
799  outputDataSize = frameCount * _channels * _frameLen;
800  outputData.reset(new int16[outputDataSize]);
801 
802  std::memset(outputData.get(), 0, outputDataSize * 2);
803 
804  // Number of bits data that completes the last superframe's overhang.
805  int bitOffset = bits.getBits(_byteOffsetBits + 3);
806 
807  if (_lastSuperframeLen > 0) {
808  // We have overhang data from the last superframe. Paste the
809  // complementary data from this superframe at the end and
810  // decode it as another frame.
811 
812  byte *lastSuperframeEnd = _lastSuperframe + _lastSuperframeLen;
813 
814  while (bitOffset > 7) { // Full bytes
815  *lastSuperframeEnd++ = bits.getBits(8);
816 
817  bitOffset -= 8;
818  _lastSuperframeLen += 1;
819  }
820 
821  if (bitOffset > 0) { // Remaining bits
822  *lastSuperframeEnd++ = bits.getBits(bitOffset) << (8 - bitOffset);
823 
824  bitOffset = 0;
825  _lastSuperframeLen += 1;
826  }
827 
829  Common::BitStream8MSB lastBits(lastSuperframe);
830 
831  lastBits.skip(_lastBitoffset);
832 
833  decodeFrame(lastBits, outputData.get());
834 
835  _curFrame++;
836  }
837 
838  // Skip any complementary data we haven't used
839  bits.skip(bitOffset);
840 
841  // New superframe = New block lengths
842  _resetBlockLengths = true;
843 
844  // Decode the frames
845  for (int i = 0; i < newFrameCount; i++, _curFrame++)
846  if (!decodeFrame(bits, outputData.get()))
847  return 0;
848 
849  // Check if we've got new overhang data
850  int remainingBits = bits.size() - bits.pos();
851  if (remainingBits > 0) {
852  // We do: Save it
853 
854  _lastSuperframeLen = remainingBits >> 3;
855  _lastBitoffset = 8 - (remainingBits - (_lastSuperframeLen << 3));
856 
857  if (_lastBitoffset > 0)
859 
860  data.seek(data.size() - _lastSuperframeLen);
862  } else {
863  // We don't
864 
865  _lastSuperframeLen = 0;
866  _lastBitoffset = 0;
867  }
868 
869  } else {
870  // This superframe has only one frame
871 
872  // PCM output data
873  outputDataSize = _channels * _frameLen;
874  outputData.reset(new int16[outputDataSize]);
875 
876  std::memset(outputData.get(), 0, outputDataSize * 2);
877 
878  // Decode the frame
879  if (!decodeFrame(bits, outputData.get()))
880  return 0;
881  }
882 
883  // And return our PCM output data as a stream, if available
884 
885  if (!outputData)
886  return 0;
887 
888  // TODO: This might be a problem alignment-wise?
889  return new Common::MemoryReadStream(reinterpret_cast<byte *>(outputData.release()), outputDataSize * 2, true);
890 }
891 
893  _framePos = 0;
894  _curBlock = 0;
895 
896  // Decode all blocks
897  int finished = 0;
898  while (finished == 0)
899  finished = decodeBlock(bits);
900 
901  // Check for error
902  if (finished < 0)
903  return false;
904 
905  // Convert output into interleaved PCM data
906 
907  const float *floatOut[kChannelsMax];
908  for (int i = 0; i < kChannelsMax; i++)
909  floatOut[i] = _frameOut[i];
910 
911  int16 *pcmOut = outputData + _curFrame * _channels * _frameLen;
912 
913  floatToInt16Interleave(pcmOut, floatOut, _frameLen, _channels);
914 
915  // Prepare for the next frame
916  for (int i = 0; i < _channels; i++)
917  memmove(&_frameOut[i][0], &_frameOut[i][_frameLen], _frameLen * sizeof(float));
918 
919  return true;
920 }
921 
923  // Computer new block length
924  if (!evalBlockLength(bits))
925  return -1;
926 
927  // Block size
928 
929  int bSize = _frameLenBits - _blockLenBits;
930  assert((bSize >= 0) && (bSize < _blockSizeCount));
931 
932  // MS Stereo?
933 
934  bool msStereo = false;
935  if (_channels == 2)
936  msStereo = bits.getBit() != 0;
937 
938  // Which channels are encoded?
939 
940  bool hasChannels = false;
941  bool hasChannel[kChannelsMax];
942  for (int i = 0; i < kChannelsMax; i++)
943  hasChannel[i] = false;
944 
945  for (int i = 0; i < _channels; i++) {
946  hasChannel[i] = bits.getBit() != 0;
947  if (hasChannel[i])
948  hasChannels = true;
949  }
950 
951  // Decode channels
952 
953  if (hasChannels)
954  if (!decodeChannels(bits, bSize, msStereo, hasChannel))
955  return -1;
956 
957  // Calculate IMDCTs
958 
959  if (!calculateIMDCT(bSize, msStereo, hasChannel))
960  return -1;
961 
962  // Update block number
963 
964  _curBlock += 1;
965  _framePos += _blockLen;
966 
967  // Finished
968  if (_framePos >= _frameLen)
969  return 1;
970 
971  // Need more blocks
972  return 0;
973 }
974 
976  bool msStereo, bool *hasChannel) {
977 
978  int totalGain = readTotalGain(bits);
979  int coefBitCount = totalGainToBits(totalGain);
980 
981  int coefCount[kChannelsMax];
982  calculateCoefCount(coefCount, bSize);
983 
984  if (!decodeNoise(bits, bSize, hasChannel, coefCount))
985  return false;
986 
987  if (!decodeExponents(bits, bSize, hasChannel))
988  return false;
989 
990  if (!decodeSpectralCoef(bits, msStereo, hasChannel, coefCount, coefBitCount))
991  return false;
992 
993  float mdctNorm = getNormalizedMDCTLength();
994 
995  calculateMDCTCoefficients(bSize, hasChannel, coefCount, totalGain, mdctNorm);
996 
997  if (msStereo && hasChannel[1]) {
998  // Nominal case for ms stereo: we do it before MDCT
999  // No need to optimize this case because it should almost never happen
1000 
1001  if (!hasChannel[0]) {
1002  std::memset(_coefs[0], 0, sizeof(float) * _blockLen);
1003  hasChannel[0] = true;
1004  }
1005 
1007  }
1008 
1009  return true;
1010 }
1011 
1012 bool WMACodec::calculateIMDCT(int bSize, bool msStereo, bool *hasChannel) {
1013  Common::MDCT &mdct = *_mdct[bSize];
1014 
1015  for (int i = 0; i < _channels; i++) {
1016  int n4 = _blockLen / 2;
1017 
1018  if (hasChannel[i])
1019  mdct.calcIMDCT(_output, _coefs[i]);
1020  else if (!(msStereo && (i == 1)))
1021  std::memset(_output, 0, sizeof(_output));
1022 
1023  // Multiply by the window and add in the frame
1024  int index = (_frameLen / 2) + _framePos - n4;
1025  window(&_frameOut[i][index]);
1026  }
1027 
1028  return true;
1029 }
1030 
1032  if (_useVariableBlockLen) {
1033  // Variable block lengths
1034 
1035  int n = Common::intLog2(_blockSizeCount - 1) + 1;
1036 
1037  if (_resetBlockLengths) {
1038  // Completely new block lengths
1039 
1040  _resetBlockLengths = false;
1041 
1042  const int prev = bits.getBits(n);
1043  const int prevBits = _frameLenBits - prev;
1044  if (prev >= _blockSizeCount) {
1045  warning("WMACodec::evalBlockLength(): _prevBlockLenBits %d out of range", prevBits);
1046  return false;
1047  }
1048 
1049  _prevBlockLenBits = prevBits;
1050 
1051  const int cur = bits.getBits(n);
1052  const int curBits = _frameLenBits - cur;
1053  if (cur >= _blockSizeCount) {
1054  warning("WMACodec::evalBlockLength(): _blockLenBits %d out of range", curBits);
1055  return false;
1056  }
1057 
1058  _blockLenBits = curBits;
1059 
1060  } else {
1061  // Update block lengths
1062 
1065  }
1066 
1067  const int next = bits.getBits(n);
1068  const int nextBits = _frameLenBits - next;
1069  if (next >= _blockSizeCount) {
1070  warning("WMACodec::evalBlockLength(): _nextBlockLenBits %d out of range", nextBits);
1071  return false;
1072  }
1073 
1074  _nextBlockLenBits = nextBits;
1075 
1076  } else {
1077  // Fixed block length
1078 
1082  }
1083 
1084  // Sanity checks
1085 
1087  warning("WMACodec::evalBlockLength(): _blockLenBits not initialized to a valid value");
1088  return false;
1089  }
1090 
1091  _blockLen = 1 << _blockLenBits;
1092  if ((_framePos + _blockLen) > _frameLen) {
1093  warning("WMACodec::evalBlockLength(): frame length overflow");
1094  return false;
1095  }
1096 
1097  return true;
1098 }
1099 
1100 void WMACodec::calculateCoefCount(int *coefCount, int bSize) const {
1101  const int coefN = _coefsEnd[bSize] - _coefsStart;
1102 
1103  for (int i = 0; i < _channels; i++)
1104  coefCount[i] = coefN;
1105 }
1106 
1108  bool *hasChannel, int *coefCount) {
1109  if (!_useNoiseCoding)
1110  return true;
1111 
1112  for (int i = 0; i < _channels; i++) {
1113  if (!hasChannel[i])
1114  continue;
1115 
1116  const int n = _exponentHighSizes[bSize];
1117  for (int j = 0; j < n; j++) {
1118  bool a = bits.getBit() != 0;
1119  _highBandCoded[i][j] = a;
1120 
1121  // With noise coding, the coefficients are not transmitted
1122  if (a)
1123  coefCount[i] -= _exponentHighBands[bSize][j];
1124  }
1125  }
1126 
1127  for (int i = 0; i < _channels; i++) {
1128  if (!hasChannel[i])
1129  continue;
1130 
1131  const int n = _exponentHighSizes[bSize];
1132  int val = (int) 0x80000000;
1133 
1134  for (int j = 0; j < n; j++) {
1135  if (!_highBandCoded[i][j])
1136  continue;
1137 
1138  if (val != (int) 0x80000000) {
1139  int code = _hgainHuffman->getSymbol(bits);
1140  if (code < 0) {
1141  warning("WMACodec::decodeNoise(): HGain Huffman invalid");
1142  return false;
1143  }
1144 
1145  val += code - 18;
1146 
1147  } else
1148  val = bits.getBits(7) - 19;
1149 
1150  _highBandValues[i][j] = val;
1151 
1152  }
1153  }
1154 
1155  return true;
1156 }
1157 
1158 bool WMACodec::decodeExponents(Common::BitStream &bits, int bSize, bool *hasChannel) {
1159  // Exponents can be reused in short blocks
1160  if (!((_blockLenBits == _frameLenBits) || bits.getBit()))
1161  return true;
1162 
1163  for (int i = 0; i < _channels; i++) {
1164  if (!hasChannel[i])
1165  continue;
1166 
1167  if (_useExpHuffman) {
1168  if (!decodeExpHuffman(bits, i))
1169  return false;
1170  } else {
1171  if (!decodeExpLSP(bits, i))
1172  return false;
1173  }
1174 
1175  _exponentsBSize[i] = bSize;
1176  }
1177 
1178  return true;
1179 }
1180 
1181 bool WMACodec::decodeSpectralCoef(Common::BitStream &bits, bool msStereo, bool *hasChannel,
1182  int *coefCount, int coefBitCount) {
1183  // Simple RLE encoding
1184 
1185  for (int i = 0; i < _channels; i++) {
1186  if (hasChannel[i]) {
1187  // Special Huffman tables are used for MS stereo
1188  // because there is potentially less energy there.
1189  const int tindex = ((i == 1) && msStereo);
1190 
1191  float *ptr = &_coefs1[i][0];
1192  std::memset(ptr, 0, _blockLen * sizeof(float));
1193 
1194  if (!decodeRunLevel(bits, *_coefHuffman[tindex],
1195  _coefHuffmanLevelTable[tindex].get(), _coefHuffmanRunTable[tindex].get(),
1196  0, ptr, 0, coefCount[i], _blockLen, _frameLenBits, coefBitCount))
1197  return false;
1198  }
1199 
1200  if ((_version == 1) && (_channels >= 2))
1201  bits.skip(-((ptrdiff_t)(bits.pos() & 7)));
1202  }
1203 
1204  return true;
1205 }
1206 
1208  const int n4 = _blockLen / 2;
1209 
1210  float mdctNorm = 1.0f / (float) n4;
1211  if (_version == 1)
1212  mdctNorm *= sqrt((float) n4);
1213 
1214  return mdctNorm;
1215 }
1216 
1217 void WMACodec::calculateMDCTCoefficients(int bSize, bool *hasChannel,
1218  int *coefCount, int totalGain, float mdctNorm) {
1219 
1220  for (int i = 0; i < _channels; i++) {
1221  if (!hasChannel[i])
1222  continue;
1223 
1224  float *coefs = _coefs[i];
1225  const float *coefs1 = _coefs1[i];
1226  const float *exponents = _exponents[i];
1227 
1228  const int eSize = _exponentsBSize[i];
1229 
1230  const float mult = (pow(10, totalGain * 0.05f) / _maxExponent[i]) * mdctNorm;
1231 
1232  if (_useNoiseCoding) {
1233 
1234  // Very low freqs: noise
1235  for (int j = 0; j < _coefsStart; j++) {
1236  *coefs++ = _noiseTable[_noiseIndex] * exponents[(j << bSize) >> eSize] * mult;
1237 
1238  _noiseIndex = (_noiseIndex + 1) & (kNoiseTabSize - 1);
1239  }
1240 
1241  // Compute power of high bands
1242  float expPower[kHighBandSizeMax] = {
1243  1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f
1244  };
1245 
1246  const int n1 = _exponentHighSizes[bSize];
1247  exponents = _exponents[i] + ((_highBandStart[bSize] << bSize) >> eSize);
1248 
1249  int lastHighBand = 0;
1250  for (int k = 0; k < n1; k++) {
1251  const int n = _exponentHighBands[_frameLenBits - _blockLenBits][k];
1252 
1253  if (_highBandCoded[i][k]) {
1254  float e2 = 0;
1255 
1256  for (int j = 0; j < n; j++) {
1257  const float v = exponents[(j << bSize) >> eSize];
1258 
1259  e2 += v * v;
1260  }
1261 
1262  expPower[k] = e2 / n;
1263  lastHighBand = k;
1264  }
1265 
1266  exponents += (n << bSize) >> eSize;
1267  }
1268 
1269  // Main freqs and high freqs
1270  exponents = _exponents[i] + ((_coefsStart << bSize) >> eSize);
1271 
1272  for (int k = -1; k < n1; k++) {
1273 
1274  int n;
1275  if (k < 0)
1276  n = _highBandStart[bSize] - _coefsStart;
1277  else
1279 
1280  if (k >= 0 && _highBandCoded[i][k]) {
1281  // Use noise with specified power
1282 
1283  float mult1 = sqrt(expPower[k] / expPower[lastHighBand]);
1284 
1285  mult1 *= pow(10, _highBandValues[i][k] * 0.05f);
1286  mult1 /= _maxExponent[i] * _noiseMult;
1287  mult1 *= mdctNorm;
1288 
1289  for (int j = 0; j < n; j++) {
1290  float noise = _noiseTable[_noiseIndex];
1291 
1292  _noiseIndex = (_noiseIndex + 1) & (kNoiseTabSize - 1);
1293  *coefs++ = noise * exponents[(j << bSize) >> eSize] * mult1;
1294  }
1295 
1296  exponents += (n << bSize) >> eSize;
1297 
1298  } else {
1299  // Coded values + small noise
1300 
1301  for (int j = 0; j < n; j++) {
1302  float noise = _noiseTable[_noiseIndex];
1303 
1304  _noiseIndex = (_noiseIndex + 1) & (kNoiseTabSize - 1);
1305  *coefs++ = ((*coefs1++) + noise) * exponents[(j << bSize) >> eSize] * mult;
1306  }
1307 
1308  exponents += (n << bSize) >> eSize;
1309  }
1310 
1311  }
1312 
1313  // Very high freqs: Noise
1314  const int n = _blockLen - _coefsEnd[bSize];
1315  const float mult1 = mult * exponents[(-(1 << bSize)) >> eSize];
1316 
1317  for (int j = 0; j < n; j++) {
1318  *coefs++ = _noiseTable[_noiseIndex] * mult1;
1319  _noiseIndex = (_noiseIndex + 1) & (kNoiseTabSize - 1);
1320  }
1321 
1322  } else {
1323 
1324  for (int j = 0; j < _coefsStart; j++)
1325  *coefs++ = 0.0f;
1326 
1327  for (int j = 0;j < coefCount[i]; j++) {
1328  *coefs = coefs1[j] * exponents[(j << bSize) >> eSize] * mult;
1329  coefs++;
1330  }
1331 
1332  int n = _blockLen - _coefsEnd[bSize];
1333  for (int j = 0; j < n; j++)
1334  *coefs++ = 0.0f;
1335 
1336  }
1337 
1338  }
1339 
1340 }
1341 
1342 static const float powTab[] = {
1343  1.7782794100389e-04f, 2.0535250264571e-04f,
1344  2.3713737056617e-04f, 2.7384196342644e-04f,
1345  3.1622776601684e-04f, 3.6517412725484e-04f,
1346  4.2169650342858e-04f, 4.8696752516586e-04f,
1347  5.6234132519035e-04f, 6.4938163157621e-04f,
1348  7.4989420933246e-04f, 8.6596432336006e-04f,
1349  1.0000000000000e-03f, 1.1547819846895e-03f,
1350  1.3335214321633e-03f, 1.5399265260595e-03f,
1351  1.7782794100389e-03f, 2.0535250264571e-03f,
1352  2.3713737056617e-03f, 2.7384196342644e-03f,
1353  3.1622776601684e-03f, 3.6517412725484e-03f,
1354  4.2169650342858e-03f, 4.8696752516586e-03f,
1355  5.6234132519035e-03f, 6.4938163157621e-03f,
1356  7.4989420933246e-03f, 8.6596432336006e-03f,
1357  1.0000000000000e-02f, 1.1547819846895e-02f,
1358  1.3335214321633e-02f, 1.5399265260595e-02f,
1359  1.7782794100389e-02f, 2.0535250264571e-02f,
1360  2.3713737056617e-02f, 2.7384196342644e-02f,
1361  3.1622776601684e-02f, 3.6517412725484e-02f,
1362  4.2169650342858e-02f, 4.8696752516586e-02f,
1363  5.6234132519035e-02f, 6.4938163157621e-02f,
1364  7.4989420933246e-02f, 8.6596432336007e-02f,
1365  1.0000000000000e-01f, 1.1547819846895e-01f,
1366  1.3335214321633e-01f, 1.5399265260595e-01f,
1367  1.7782794100389e-01f, 2.0535250264571e-01f,
1368  2.3713737056617e-01f, 2.7384196342644e-01f,
1369  3.1622776601684e-01f, 3.6517412725484e-01f,
1370  4.2169650342858e-01f, 4.8696752516586e-01f,
1371  5.6234132519035e-01f, 6.4938163157621e-01f,
1372  7.4989420933246e-01f, 8.6596432336007e-01f,
1373  1.0000000000000e+00f, 1.1547819846895e+00f,
1374  1.3335214321633e+00f, 1.5399265260595e+00f,
1375  1.7782794100389e+00f, 2.0535250264571e+00f,
1376  2.3713737056617e+00f, 2.7384196342644e+00f,
1377  3.1622776601684e+00f, 3.6517412725484e+00f,
1378  4.2169650342858e+00f, 4.8696752516586e+00f,
1379  5.6234132519035e+00f, 6.4938163157621e+00f,
1380  7.4989420933246e+00f, 8.6596432336007e+00f,
1381  1.0000000000000e+01f, 1.1547819846895e+01f,
1382  1.3335214321633e+01f, 1.5399265260595e+01f,
1383  1.7782794100389e+01f, 2.0535250264571e+01f,
1384  2.3713737056617e+01f, 2.7384196342644e+01f,
1385  3.1622776601684e+01f, 3.6517412725484e+01f,
1386  4.2169650342858e+01f, 4.8696752516586e+01f,
1387  5.6234132519035e+01f, 6.4938163157621e+01f,
1388  7.4989420933246e+01f, 8.6596432336007e+01f,
1389  1.0000000000000e+02f, 1.1547819846895e+02f,
1390  1.3335214321633e+02f, 1.5399265260595e+02f,
1391  1.7782794100389e+02f, 2.0535250264571e+02f,
1392  2.3713737056617e+02f, 2.7384196342644e+02f,
1393  3.1622776601684e+02f, 3.6517412725484e+02f,
1394  4.2169650342858e+02f, 4.8696752516586e+02f,
1395  5.6234132519035e+02f, 6.4938163157621e+02f,
1396  7.4989420933246e+02f, 8.6596432336007e+02f,
1397  1.0000000000000e+03f, 1.1547819846895e+03f,
1398  1.3335214321633e+03f, 1.5399265260595e+03f,
1399  1.7782794100389e+03f, 2.0535250264571e+03f,
1400  2.3713737056617e+03f, 2.7384196342644e+03f,
1401  3.1622776601684e+03f, 3.6517412725484e+03f,
1402  4.2169650342858e+03f, 4.8696752516586e+03f,
1403  5.6234132519035e+03f, 6.4938163157621e+03f,
1404  7.4989420933246e+03f, 8.6596432336007e+03f,
1405  1.0000000000000e+04f, 1.1547819846895e+04f,
1406  1.3335214321633e+04f, 1.5399265260595e+04f,
1407  1.7782794100389e+04f, 2.0535250264571e+04f,
1408  2.3713737056617e+04f, 2.7384196342644e+04f,
1409  3.1622776601684e+04f, 3.6517412725484e+04f,
1410  4.2169650342858e+04f, 4.8696752516586e+04f,
1411  5.6234132519035e+04f, 6.4938163157621e+04f,
1412  7.4989420933246e+04f, 8.6596432336007e+04f,
1413  1.0000000000000e+05f, 1.1547819846895e+05f,
1414  1.3335214321633e+05f, 1.5399265260595e+05f,
1415  1.7782794100389e+05f, 2.0535250264571e+05f,
1416  2.3713737056617e+05f, 2.7384196342644e+05f,
1417  3.1622776601684e+05f, 3.6517412725484e+05f,
1418  4.2169650342858e+05f, 4.8696752516586e+05f,
1419  5.6234132519035e+05f, 6.4938163157621e+05f,
1420  7.4989420933246e+05f, 8.6596432336007e+05f,
1421 };
1422 
1424  const float *ptab = powTab + 60;
1425  const uint32 *iptab = reinterpret_cast<const uint32 *>(ptab);
1426 
1428 
1429  uint32 *q = reinterpret_cast<uint32 *>(_exponents[ch]);
1430  uint32 *qEnd = q + _blockLen;
1431 
1432  float maxScale = 0;
1433 
1434  int lastExp;
1435  if (_version == 1) {
1436 
1437  lastExp = bits.getBits(5) + 10;
1438 
1439  float v = ptab[lastExp];
1440  uint32 iv = iptab[lastExp];
1441 
1442  maxScale = v;
1443 
1444  int n = *ptr++;
1445 
1446  switch (n & 3) do {
1448  case 0: *q++ = iv; XOREOS_FALLTHROUGH;
1449  case 3: *q++ = iv; XOREOS_FALLTHROUGH;
1450  case 2: *q++ = iv; XOREOS_FALLTHROUGH;
1451  case 1: *q++ = iv;
1452  } while ((n -= 4) > 0);
1453 
1454  } else
1455  lastExp = 36;
1456 
1457  while (q < qEnd) {
1458  int code = _expHuffman->getSymbol(bits);
1459  if (code < 0) {
1460  warning("WMACodec::decodeExpHuffman(): Exponent invalid");
1461  return false;
1462  }
1463 
1464  // NOTE: This offset is the same as MPEG4 AAC!
1465  lastExp += code - 60;
1466  if ((unsigned) lastExp + 60 >= ARRAYSIZE(powTab)) {
1467  warning("WMACodec::decodeExpHuffman(): Exponent out of range: %d", lastExp);
1468  return false;
1469  }
1470 
1471  float v = ptab[lastExp];
1472  uint32 iv = iptab[lastExp];
1473 
1474  if (v > maxScale)
1475  maxScale = v;
1476 
1477  int n = *ptr++;
1478 
1479  switch (n & 3) do {
1481  case 0: *q++ = iv; XOREOS_FALLTHROUGH;
1482  case 3: *q++ = iv; XOREOS_FALLTHROUGH;
1483  case 2: *q++ = iv; XOREOS_FALLTHROUGH;
1484  case 1: *q++ = iv;
1485  } while ((n -= 4) > 0);
1486 
1487  }
1488 
1489  _maxExponent[ch] = maxScale;
1490 
1491  return true;
1492 }
1493 
1494 void WMACodec::lspToCurve(float *out, float *val_max_ptr, int n, float *lsp) {
1495  float val_max = 0;
1496 
1497  for (int i = 0; i < n; i++) {
1498  float p = 0.5f;
1499  float q = 0.5f;
1500  float w = _lspCosTable[i];
1501 
1502  for (int j = 1; j < kLSPCoefCount; j += 2) {
1503  q *= w - lsp[j - 1];
1504  p *= w - lsp[j];
1505  }
1506 
1507  p *= p * (2.0f - w);
1508  q *= q * (2.0f + w);
1509 
1510  float v = p + q;
1511  v = pow_m1_4(v);
1512 
1513  if (v > val_max)
1514  val_max = v;
1515 
1516  out[i] = v;
1517  }
1518 
1519  *val_max_ptr = val_max;
1520 }
1521 
1522 // Decode exponents coded with LSP coefficients (same idea as Vorbis)
1524  float lspCoefs[kLSPCoefCount];
1525 
1526  for (int i = 0; i < kLSPCoefCount; i++) {
1527  int val;
1528 
1529  if (i == 0 || i >= 8)
1530  val = bits.getBits(3);
1531  else
1532  val = bits.getBits(4);
1533 
1534  lspCoefs[i] = lspCodebook[i][val];
1535  }
1536 
1537  lspToCurve(_exponents[ch], &_maxExponent[ch], _blockLen, lspCoefs);
1538  return true;
1539 }
1540 
1542  const float *levelTable, const uint16 *runTable, int version, float *ptr,
1543  int offset, int numCoefs, int blockLen, int frameLenBits, int coefNbBits) {
1544 
1545  const unsigned int coefMask = blockLen - 1;
1546 
1547  for (; offset < numCoefs; offset++) {
1548  const int code = huffman.getSymbol(bits);
1549 
1550  if (code > 1) {
1551  // Normal code
1552 
1553  const float sign = bits.getBit() ? 1.0f : -1.0f;
1554 
1555  offset += runTable[code];
1556 
1557  ptr[offset & coefMask] = levelTable[code] * sign;
1558 
1559  } else if (code == 1) {
1560  // EOB
1561 
1562  break;
1563 
1564  } else {
1565  // Escape
1566 
1567  int level;
1568 
1569  if (!version) {
1570 
1571  level = bits.getBits(coefNbBits);
1572  // NOTE: This is rather suboptimal. reading blockLenBits would be better
1573  offset += bits.getBits(frameLenBits);
1574 
1575  } else {
1576  level = getLargeVal(bits);
1577 
1578  // Escape decode
1579  if (bits.getBit()) {
1580  if (bits.getBit()) {
1581  if (bits.getBit()) {
1582  warning("WMACodec::decodeRunLevel(): Broken escape sequence");
1583  return false;
1584  } else
1585  offset += bits.getBits(frameLenBits) + 4;
1586  } else
1587  offset += bits.getBits(2) + 1;
1588  }
1589 
1590  }
1591 
1592  const int sign = bits.getBit() - 1;
1593 
1594  ptr[offset & coefMask] = (level ^ sign) - sign;
1595 
1596  }
1597  }
1598 
1599  // NOTE: EOB can be omitted
1600  if (offset > numCoefs) {
1601  warning("WMACodec::decodeRunLevel(): Overflow in spectral RLE, ignoring");
1602  return true;
1603  }
1604 
1605  return true;
1606 }
1607 
1613 void WMACodec::window(float *out) const {
1614  const float *in = _output;
1615 
1616  // Left part
1618 
1619  const int bSize = _frameLenBits - _blockLenBits;
1620 
1621  vectorFMulAdd(out, in, _mdctWindow[bSize], out, _blockLen);
1622 
1623  } else {
1624 
1625  const int blockLen = 1 << _prevBlockLenBits;
1626  const int n = (_blockLen - blockLen) / 2;
1627 
1628  const int bSize = _frameLenBits - _prevBlockLenBits;
1629 
1630  vectorFMulAdd(out + n, in + n, _mdctWindow[bSize], out + n, blockLen);
1631 
1632  std::memcpy(out + n + blockLen, in + n + blockLen, n * sizeof(float));
1633  }
1634 
1635  out += _blockLen;
1636  in += _blockLen;
1637 
1638  // Right part
1640 
1641  const int bSize = _frameLenBits - _blockLenBits;
1642 
1643  vectorFMulReverse(out, in, _mdctWindow[bSize], _blockLen);
1644 
1645  } else {
1646 
1647  const int blockLen = 1 << _nextBlockLenBits;
1648  const int n = (_blockLen - blockLen) / 2;
1649 
1650  const int bSize = _frameLenBits - _nextBlockLenBits;
1651 
1652  std::memcpy(out, in, n*sizeof(float));
1653 
1654  vectorFMulReverse(out + n, in + n, _mdctWindow[bSize], blockLen);
1655 
1656  std::memset(out + n + blockLen, 0, n * sizeof(float));
1657  }
1658 }
1659 
1660 float WMACodec::pow_m1_4(float x) const {
1661  union {
1662  float f;
1663  unsigned int v;
1664  } u, t;
1665 
1666  u.f = x;
1667 
1668  const unsigned int e = u.v >> 23;
1669  const unsigned int m = (u.v >> (23 - kLSPPowBits)) & ((1 << kLSPPowBits) - 1);
1670 
1671  // Build interpolation scale: 1 <= t < 2
1672  t.v = ((u.v << kLSPPowBits) & ((1 << 23) - 1)) | (127 << 23);
1673 
1674  const float a = _lspPowMTable1[m];
1675  const float b = _lspPowMTable2[m];
1676 
1677  return _lspPowETable[e] * (a + b * t.f);
1678 }
1679 
1681  int totalGain = 1;
1682 
1683  int v = 127;
1684  while (v == 127) {
1685  v = bits.getBits(7);
1686 
1687  totalGain += v;
1688  }
1689 
1690  return totalGain;
1691 }
1692 
1693 int WMACodec::totalGainToBits(int totalGain) {
1694  if (totalGain < 15) return 13;
1695  else if (totalGain < 32) return 12;
1696  else if (totalGain < 40) return 11;
1697  else if (totalGain < 45) return 10;
1698  else return 9;
1699 }
1700 
1702  // Consumes up to 34 bits
1703 
1704  int count = 8;
1705  if (bits.getBit()) {
1706  count += 8;
1707 
1708  if (bits.getBit()) {
1709  count += 8;
1710 
1711  if (bits.getBit())
1712  count += 7;
1713  }
1714  }
1715 
1716  return bits.getBits(count);
1717 }
1718 
1721  AudioStream* stream = decodeFrame(*data);
1722  if (stream)
1723  _audStream->queueAudioStream(stream);
1724 }
1725 
1726 PacketizedAudioStream *makeWMAStream(int version, uint32 sampleRate, uint8 channels, uint32 bitRate, uint32 blockAlign, Common::SeekableReadStream &extraData) {
1727  return new WMACodec(version, sampleRate, channels, bitRate, blockAlign, &extraData);
1728 }
1729 
1730 } // End of namespace Sound
Static sine windows.
(Inverse) Modified Discrete Cosine Transforms.
float pow_m1_4(float x) const
Definition: wma.cpp:1660
const uint32 hgainHuffCodes[37]
Definition: wmadata.h:1391
int _curBlock
The number of the block we&#39;re currently in.
Definition: wma.cpp:165
const uint16 * levels
Table to build run/level tables.
Definition: wmadata.h:1379
uint16 readUint16LE()
Read an unsigned 16-bit word stored in little endian (LSB first) order from the stream and return it...
Definition: readstream.h:122
bool evalBlockLength(Common::BitStream &bits)
Definition: wma.cpp:1031
int decodeBlock(Common::BitStream &bits)
Definition: wma.cpp:922
int _frameLen
The frame length.
Definition: wma.cpp:160
float _noiseMult
Noise multiplier.
Definition: wma.cpp:191
void finish()
Mark this stream as finished.
Definition: wma.cpp:117
"GSound", global, non-engine sound.
Definition: debugman.h:43
QueuingAudioStream * makeQueuingAudioStream(int rate, int channels)
Factory function for an QueuingAudioStream.
float _frameOut[kChannelsMax][kBlockSizeMax *2]
Definition: wma.cpp:229
static int intLog2(uint32 v)
Definition: maths.h:83
bool isFinished() const
Is the stream marked as finished?
Definition: wma.cpp:118
float _noiseTable[kNoiseTabSize]
Noise table.
Definition: wma.cpp:192
void debugC(Common::DebugChannel channel, uint32 level, const char *s,...)
Definition: debug.cpp:34
bool decodeChannels(Common::BitStream &bits, int bSize, bool msStereo, bool *hasChannel)
Definition: wma.cpp:975
bool decodeNoise(Common::BitStream &bits, int bSize, bool *hasChannel, int *coefCount)
Definition: wma.cpp:1107
virtual size_t seek(ptrdiff_t offset, Origin whence=kOriginBegin)=0
Sets the stream position indicator for the stream.
bool decodeSpectralCoef(Common::BitStream &bits, bool msStereo, bool *hasChannel, int *coefCount, int coefBitCount)
Definition: wma.cpp:1181
int _lastSuperframeLen
Size of the overhang data.
Definition: wma.cpp:224
static void vectorFMulReverse(float *dst, const float *src0, const float *src1, int len)
Definition: wma.cpp:93
void reset(PointerType o=0)
Resets the pointer with the new value.
Definition: scopedptr.h:87
Common::ScopedArray< float > _coefHuffmanLevelTable[2]
Level table for the coef Huffman.
Definition: wma.cpp:187
int getBlockSizeCount(uint16 flags)
Definition: wma.cpp:416
Utility functions for debug output.
PointerType release()
Returns the plain pointer value and releases ScopedPtr.
Definition: scopedptr.h:103
Common::ScopedPtr< Common::Huffman > _hgainHuffman
Perceptual noise Huffman code.
Definition: wma.cpp:195
const uint8 * huffBits
Bit sizes.
Definition: wmadata.h:1378
uint8_t uint8
Definition: types.h:200
void initCoefHuffman(float bps)
Definition: wma.cpp:648
virtual size_t pos() const =0
Return the stream position in bits.
Mathematical helpers.
void calculateMDCTCoefficients(int bSize, bool *hasChannel, int *coefCount, int totalGain, float mdctNorm)
Definition: wma.cpp:1217
int _blockLen
Current block length.
Definition: wma.cpp:166
#define M_PI
Definition: maths.h:39
Implementing the reading stream interfaces for plain memory blocks.
int _blockLenBits
log2 of current block length.
Definition: wma.cpp:167
#define ARRAYSIZE(x)
Macro which determines the number of entries in a fixed size array.
Definition: util.h:131
const float * getSineWindow(int bits)
RewindableAudioStream * makePCMStream(Common::SeekableReadStream *stream, int rate, byte flags, int channels, bool disposeAfterUse)
Creates an audio stream, which plays from the given stream.
Definition: pcm.cpp:140
uint32 getBits(size_t n)
Read a multi-bit value from the bit stream.
Definition: bitstream.h:178
Decoding PCM (Pulse Code Modulation).
int _coefsStart
First coded coef.
Definition: wma.cpp:174
void init(Common::SeekableReadStream *extraData)
Definition: wma.cpp:331
uint8 _channels
Output channel count.
Definition: wma.cpp:147
Static data used for decoding Microsoft&#39;s Windows Media Audio.
WMACodec(int version, uint32 sampleRate, uint8 channels, uint32 bitRate, uint32 blockAlign, Common::SeekableReadStream *extraData=0)
Definition: wma.cpp:296
size_t pos() const
Return the stream position in bits.
Definition: bitstream.h:227
int _blockSizeCount
Number of block sizes.
Definition: wma.cpp:162
int16_t int16
Definition: types.h:201
void initNoise()
Definition: wma.cpp:629
static const int kBlockSizeMax
Max number of bytes in a block.
Definition: wma.cpp:128
void evalFlags(uint16 flags, Common::SeekableReadStream *extraData)
Definition: wma.cpp:385
int _highBandValues[kChannelsMax][kHighBandSizeMax]
Definition: wma.cpp:206
byte _lastSuperframe[kSuperframeSizeMax+4]
Overhang from the last superframe.
Definition: wma.cpp:223
(Inverse) Modified Discrete Cosine Transforms.
Definition: mdct.h:64
A simple scoped smart pointer template.
static const WMACoefHuffmanParam coefHuffmanParam[6]
Definition: wmadata.h:1382
uint32 getSymbol(BitStream &bits) const
Return the next symbol in the bitstream.
Definition: huffman.cpp:85
Definition: game.h:37
static const uint8 exponentBand44100[3][25]
Definition: wmadata.h:78
Basic exceptions to throw.
void initMDCT()
Definition: wma.cpp:668
void calculateCoefCount(int *coefCount, int bSize) const
Definition: wma.cpp:1100
int _exponentHighBands[kBlockNBSizes][kHighBandSizeMax]
Definition: wma.cpp:180
int _prevBlockLenBits
log2 of previous block length.
Definition: wma.cpp:169
bool calculateIMDCT(int bSize, bool msStereo, bool *hasChannel)
Definition: wma.cpp:1012
static const uint8 exponentBand32000[3][25]
Definition: wmadata.h:72
Common::PtrVector< Common::MDCT > _mdct
MDCT contexts.
Definition: wma.cpp:219
bool decodeRunLevel(Common::BitStream &bits, const Common::Huffman &huffman, const float *levelTable, const uint16 *runTable, int version, float *ptr, int offset, int numCoefs, int blockLen, int frameLenBits, int coefNbBits)
Definition: wma.cpp:1541
const uint32 * huffCodes
Bit values.
Definition: wmadata.h:1377
int n
Number of codes.
Definition: wmadata.h:1373
uint16_t uint16
Definition: types.h:202
int _lastBitoffset
Bit position within the overhang.
Definition: wma.cpp:225
Utility templates and functions.
uint32 _sampleRate
Output sample rate.
Definition: wma.cpp:146
int getChannels() const
Return the number channels in this stream.
Definition: wma.cpp:110
int _curFrame
The number of the frame we&#39;re currently in.
Definition: wma.cpp:159
float _maxExponent[kChannelsMax]
Definition: wma.cpp:200
An AudioStream designed to work in terms of packets.
Definition: audiostream.h:271
Decode a Huffman&#39;d bitstream.
Definition: huffman.h:47
virtual uint32 getBit()=0
Read a bit from the bit stream.
T MIN(T a, T b)
Definition: util.h:70
static int readTotalGain(Common::BitStream &bits)
Definition: wma.cpp:1680
bool endOfData() const
End of data reached? If this returns true, it means that at this time there is no data available in t...
Definition: wma.cpp:112
bool _highBandCoded[kChannelsMax][kHighBandSizeMax]
Definition: wma.cpp:205
float _lspPowETable[256]
Definition: wma.cpp:214
static const int kNoiseTabSize
Size of the noise table.
Definition: wma.cpp:139
virtual size_t read(void *dataPtr, size_t dataSize)=0
Read data from the stream.
Simple memory based &#39;stream&#39;, which implements the ReadStream interface for a plain memory block...
Definition: memreadstream.h:66
static int totalGainToBits(int totalGain)
Definition: wma.cpp:1693
void window(float *out) const
Apply MDCT window and add into output.
Definition: wma.cpp:1613
Low-level type definitions to handle fixed width types portably.
Common::ScopedPtr< Common::Huffman > _coefHuffman[2]
Coefficients Huffman codes.
Definition: wma.cpp:182
float _lspPowMTable1[(1<< kLSPPowBits)]
Definition: wma.cpp:215
int _exponentsBSize[kChannelsMax]
Definition: wma.cpp:198
StackException Exception
Definition: error.h:59
Common::ScopedPtr< QueuingAudioStream > _audStream
Definition: wma.cpp:232
A vector storing pointer to objects, with automatic deletion.
int _exponentSizes[kBlockNBSizes]
Definition: wma.cpp:176
const uint16 wmaCriticalFreqs[25]
Definition: wmadata.h:58
bool useNoiseCoding(float &highFreq, float &bps)
Definition: wma.cpp:453
void warning(const char *s,...)
Definition: util.cpp:33
virtual size_t size() const =0
Obtains the total size of the stream, measured in bytes.
uint32 getNormalizedSampleRate()
Definition: wma.cpp:430
void calcIMDCT(float *output, const float *input)
Compute inverse MDCT of size N = 2^nbits.
Definition: mdct.cpp:129
const uint8 scaleHuffBits[121]
Definition: wmadata.h:1426
static const int kHighBandSizeMax
Max size of a high band.
Definition: wma.cpp:136
bool decodeExpLSP(Common::BitStream &bits, int ch)
Definition: wma.cpp:1523
bool _useBitReservoir
Is each frame packet a "superframe"?
Definition: wma.cpp:153
Decoding Microsoft&#39;s Windows Media Audio.
static const int kLSPCoefCount
Definition: wmadata.h:1437
const uint32 scaleHuffCodes[121]
Definition: wmadata.h:1407
void initLSPToCurve()
Definition: wma.cpp:723
A bit stream.
bool _useNoiseCoding
Should perceptual noise be added?
Definition: wma.cpp:155
int getFrameBitLength()
Definition: wma.cpp:400
void skip(size_t n)
Skip the specified amount of bits.
Definition: bitstream.h:221
int _exponentHighSizes[kBlockNBSizes]
Definition: wma.cpp:179
sound is 16 bits wide (default: 8bit)
Definition: pcm.h:72
Generic audio input stream.
Definition: audiostream.h:70
#define XOREOS_FALLTHROUGH
Definition: fallthrough.h:60
PointerType get() const
Returns the plain pointer value.
Definition: scopedptr.h:96
static void butterflyFloats(float *v1, float *v2, int len)
Definition: wma.cpp:78
uint16 _exponentBands[kBlockNBSizes][25]
Definition: wma.cpp:177
float _exponents[kChannelsMax][kBlockSizeMax]
Definition: wma.cpp:199
size_t size() const
Return the stream size in bits.
Definition: bitstream.h:236
bool endOfStream() const
End of stream reached? If this returns true, it means that all data in this stream is used up and no ...
Definition: wma.cpp:113
bool _resetBlockLengths
Do we need new block lengths?
Definition: wma.cpp:157
void queuePacket(Common::SeekableReadStream *data)
Queue the next packet to be decoded.
Definition: wma.cpp:1719
Common::ScopedArray< uint16 > _coefHuffmanIntTable[2]
Int table for the coef Huffman.
Definition: wma.cpp:188
Parameters for Huffman&#39;d WMA coefficient codes.
Definition: wmadata.h:1372
int _version
WMA version.
Definition: wma.cpp:144
bool _useVariableBlockLen
Are the block lengths variable?
Definition: wma.cpp:154
bool _useExpHuffman
Exponents in Huffman code? Otherwise, in LSP.
Definition: wma.cpp:152
int _frameLenBits
log2 of the frame length.
Definition: wma.cpp:161
Decompressing Huffman codes.
virtual void skip(size_t n)=0
Skip the specified amount of bits.
static const int kChannelsMax
Max number of channels we support.
Definition: wma.cpp:122
uint32_t uint32
Definition: types.h:204
float _output[kBlockSizeMax *2]
Definition: wma.cpp:228
int _coefsEnd[kBlockNBSizes]
Max number of coded coefficients.
Definition: wma.cpp:175
float _coefs[kChannelsMax][kBlockSizeMax]
Definition: wma.cpp:210
std::vector< const float * > _mdctWindow
MDCT window functions.
Definition: wma.cpp:220
static const int kSuperframeSizeMax
Max size of a superframe.
Definition: wma.cpp:133
float _lspPowMTable2[(1<< kLSPPowBits)]
Definition: wma.cpp:216
static void vectorFMulAdd(float *dst, const float *src0, const float *src1, const float *src2, int len)
Definition: wma.cpp:87
void initExponents()
Definition: wma.cpp:679
bool decodeFrame(Common::BitStream &bits, int16 *outputData)
Definition: wma.cpp:892
Common::ScopedPtr< Common::Huffman > _expHuffman
Exponents Huffman code.
Definition: wma.cpp:202
static void floatToInt16Interleave(int16 *dst, const float **src, uint32 length, uint8 channels)
Definition: util.h:39
virtual uint32 getBits(size_t n)=0
Read a multi-bit value from the bit stream.
const uint8 hgainHuffBits[37]
Definition: wmadata.h:1399
samples are little endian (default: big endian)
Definition: pcm.h:75
uint16 getFlags(Common::SeekableReadStream *extraData)
Definition: wma.cpp:371
int _nextBlockLenBits
log2 of next block length.
Definition: wma.cpp:168
A template implementing a bit stream for different data memory layouts.
Definition: bitstream.h:85
static const int kLSPPowBits
Number of bits for the LSP power value.
Definition: wma.cpp:142
bool decodeExpHuffman(Common::BitStream &bits, int ch)
Definition: wma.cpp:1423
float _coefs1[kChannelsMax][kBlockSizeMax]
Definition: wma.cpp:209
Common::SeekableReadStream * decodeSuperFrame(Common::SeekableReadStream &data)
Definition: wma.cpp:759
static const int kBlockBitsMax
Max number of bits in a block.
Definition: wma.cpp:125
Common::ScopedArray< uint16 > _coefHuffmanRunTable[2]
Run table for the coef Huffman.
Definition: wma.cpp:186
bool decodeExponents(Common::BitStream &bits, int bSize, bool *hasChannel)
Definition: wma.cpp:1158
int _framePos
The position within the frame we&#39;re currently in.
Definition: wma.cpp:163
PacketizedAudioStream * makeWMAStream(int version, uint32 sampleRate, uint8 channels, uint32 bitRate, uint32 blockAlign, Common::SeekableReadStream &extraData)
Create a PacketizedAudioStream that decodes WMA sound.
Definition: wma.cpp:1726
static uint32 getLargeVal(Common::BitStream &bits)
Definition: wma.cpp:1701
uint32 _blockAlign
Input block align.
Definition: wma.cpp:149
static const float powTab[]
Definition: wma.cpp:1342
float getNormalizedMDCTLength() const
Definition: wma.cpp:1207
int _highBandStart[kBlockNBSizes]
Index of first coef in high band.
Definition: wma.cpp:178
const WMACoefHuffmanParam * _coefHuffmanParam[2]
Params for coef Huffman codes.
Definition: wma.cpp:184
byte _audioFlags
Output flags.
Definition: wma.cpp:150
int _noiseIndex
Definition: wma.cpp:193
const float lspCodebook[kLSPCoefCount][16]
Definition: wmadata.h:1439
static const int kBlockNBSizes
Definition: wma.cpp:130
Interface for a seekable & readable data stream.
Definition: readstream.h:265
Streaming audio.
int _byteOffsetBits
Definition: wma.cpp:171
int getRate() const
Sample rate of the stream.
Definition: wma.cpp:111
void lspToCurve(float *out, float *val_max_ptr, int n, float *lsp)
Definition: wma.cpp:1494
static const int kBlockBitsMin
Min number of bits in a block.
Definition: wma.cpp:124
A bit stream.
Definition: bitstream.h:40
float _lspCosTable[kBlockSizeMax]
Definition: wma.cpp:213
size_t readBuffer(int16 *buffer, const size_t numSamples)
Fill the given buffer with up to numSamples samples.
Definition: wma.cpp:114
uint8 byte
Definition: types.h:209
uint32 _bitRate
Input bit rate.
Definition: wma.cpp:148
unsigned int uint
Definition: types.h:211
static const uint8 exponentBand22050[3][25]
Definition: wmadata.h:66
void evalMDCTScales(float highFreq)
Definition: wma.cpp:519
Sound decoding utility functions.