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

bink_decoder.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 on eos' Bink decoder which is in turn
00024 // based quite heavily on the Bink decoder found in FFmpeg.
00025 // Many thanks to Kostya Shishkov for doing the hard work.
00026 
00027 #include "audio/audiostream.h"
00028 #include "audio/decoders/raw.h"
00029 
00030 #include "common/util.h"
00031 #include "common/textconsole.h"
00032 #include "common/math.h"
00033 #include "common/stream.h"
00034 #include "common/substream.h"
00035 #include "common/file.h"
00036 #include "common/str.h"
00037 #include "common/bitstream.h"
00038 #include "common/huffman.h"
00039 #include "common/rdft.h"
00040 #include "common/dct.h"
00041 #include "common/system.h"
00042 
00043 #include "graphics/yuva_to_rgba.h" // ResidualVM specific
00044 #include "graphics/surface.h"
00045 
00046 #include "video/binkdata.h"
00047 #include "video/bink_decoder.h"
00048 
00049 static const uint32 kBIKfID = MKTAG('B', 'I', 'K', 'f');
00050 static const uint32 kBIKgID = MKTAG('B', 'I', 'K', 'g');
00051 static const uint32 kBIKhID = MKTAG('B', 'I', 'K', 'h');
00052 static const uint32 kBIKiID = MKTAG('B', 'I', 'K', 'i');
00053 
00054 static const uint32 kVideoFlagAlpha = 0x00100000;
00055 
00056 static const uint16 kAudioFlagDCT    = 0x1000;
00057 static const uint16 kAudioFlagStereo = 0x2000;
00058 
00059 // Number of bits used to store first DC value in bundle
00060 static const uint32 kDCStartBits = 11;
00061 
00062 namespace Video {
00063 
00064 BinkDecoder::BinkDecoder() {
00065     _bink = 0;
00066 }
00067 
00068 BinkDecoder::~BinkDecoder() {
00069     close();
00070 }
00071 
00072 bool BinkDecoder::loadStream(Common::SeekableReadStream *stream) {
00073     close();
00074 
00075     uint32 id = stream->readUint32BE();
00076     if ((id != kBIKfID) && (id != kBIKgID) && (id != kBIKhID) && (id != kBIKiID))
00077         return false;
00078 
00079     uint32 fileSize         = stream->readUint32LE() + 8;
00080     uint32 frameCount       = stream->readUint32LE();
00081     uint32 largestFrameSize = stream->readUint32LE();
00082 
00083     if (largestFrameSize > fileSize) {
00084         warning("Largest frame size greater than file size");
00085         return false;
00086     }
00087 
00088     stream->skip(4);
00089 
00090     uint32 width  = stream->readUint32LE();
00091     uint32 height = stream->readUint32LE();
00092 
00093     uint32 frameRateNum = stream->readUint32LE();
00094     uint32 frameRateDen = stream->readUint32LE();
00095     if (frameRateNum == 0 || frameRateDen == 0) {
00096         warning("Invalid frame rate (%d/%d)", frameRateNum, frameRateDen);
00097         return false;
00098     }
00099 
00100     _bink = stream;
00101 
00102     uint32 videoFlags = _bink->readUint32LE();
00103 
00104     // BIKh and BIKi swap the chroma planes
00105     addTrack(new BinkVideoTrack(width, height, getDefaultHighColorFormat(), frameCount,
00106             Common::Rational(frameRateNum, frameRateDen), (id == kBIKhID || id == kBIKiID), videoFlags & kVideoFlagAlpha, id));
00107 
00108     uint32 audioTrackCount = _bink->readUint32LE();
00109 
00110     if (audioTrackCount > 0) {
00111         _audioTracks.resize(audioTrackCount);
00112 
00113         _bink->skip(4 * audioTrackCount);
00114 
00115         // Reading audio track properties
00116         for (uint32 i = 0; i < audioTrackCount; i++) {
00117             AudioInfo &track = _audioTracks[i];
00118 
00119             track.sampleRate = _bink->readUint16LE();
00120             track.flags      = _bink->readUint16LE();
00121 
00122             initAudioTrack(track);
00123         }
00124 
00125         _bink->skip(4 * audioTrackCount);
00126     }
00127 
00128     // Reading video frame properties
00129     _frames.resize(frameCount);
00130     for (uint32 i = 0; i < frameCount; i++) {
00131         _frames[i].offset   = _bink->readUint32LE();
00132         _frames[i].keyFrame = _frames[i].offset & 1;
00133 
00134         _frames[i].offset &= ~1;
00135 
00136         if (i != 0)
00137             _frames[i - 1].size = _frames[i].offset - _frames[i - 1].offset;
00138 
00139         _frames[i].bits = 0;
00140     }
00141 
00142     _frames[frameCount - 1].size = _bink->size() - _frames[frameCount - 1].offset;
00143 
00144     return true;
00145 }
00146 
00147 void BinkDecoder::close() {
00148     VideoDecoder::close();
00149 
00150     delete _bink;
00151     _bink = 0;
00152 
00153     _audioTracks.clear();
00154     _frames.clear();
00155 }
00156 
00157 void BinkDecoder::readNextPacket() {
00158     BinkVideoTrack *videoTrack = (BinkVideoTrack *)getTrack(0);
00159 
00160     if (videoTrack->endOfTrack())
00161         return;
00162 
00163     VideoFrame &frame = _frames[videoTrack->getCurFrame() + 1];
00164 
00165     if (!_bink->seek(frame.offset))
00166         error("Bad bink seek");
00167 
00168     uint32 frameSize = frame.size;
00169 
00170     for (uint32 i = 0; i < _audioTracks.size(); i++) {
00171         AudioInfo &audio = _audioTracks[i];
00172 
00173         uint32 audioPacketLength = _bink->readUint32LE();
00174 
00175         frameSize -= 4;
00176 
00177         if (frameSize < audioPacketLength)
00178             error("Audio packet too big for the frame");
00179 
00180         if (audioPacketLength >= 4) {
00181             // Get our track - audio index plus one as the first track is video
00182             BinkAudioTrack *audioTrack = (BinkAudioTrack *)getTrack(i + 1);
00183             uint32 audioPacketStart = _bink->pos();
00184             uint32 audioPacketEnd   = _bink->pos() + audioPacketLength;
00185 
00186             //                  Number of samples in bytes
00187             audio.sampleCount = _bink->readUint32LE() / (2 * audio.channels);
00188 
00189             audio.bits = new Common::BitStream32LELSB(new Common::SeekableSubReadStream(_bink,
00190                     audioPacketStart + 4, audioPacketEnd), DisposeAfterUse::YES);
00191 
00192             audioTrack->decodePacket();
00193 
00194             delete audio.bits;
00195             audio.bits = 0;
00196 
00197             _bink->seek(audioPacketEnd);
00198 
00199             frameSize -= audioPacketLength;
00200         }
00201     }
00202 
00203     uint32 videoPacketStart = _bink->pos();
00204     uint32 videoPacketEnd   = _bink->pos() + frameSize;
00205 
00206     frame.bits = new Common::BitStream32LELSB(new Common::SeekableSubReadStream(_bink,
00207             videoPacketStart, videoPacketEnd), DisposeAfterUse::YES);
00208 
00209     videoTrack->decodePacket(frame);
00210 
00211     delete frame.bits;
00212     frame.bits = 0;
00213 }
00214 
00215 VideoDecoder::AudioTrack *BinkDecoder::getAudioTrack(int index) {
00216     // Bink audio track indexes are relative to the first audio track
00217     Track *track = getTrack(index + 1);
00218 
00219     if (!track || track->getTrackType() != Track::kTrackTypeAudio)
00220         return 0;
00221 
00222     return (AudioTrack *)track;
00223 }
00224 
00225 BinkDecoder::VideoFrame::VideoFrame() : bits(0) {
00226 }
00227 
00228 BinkDecoder::VideoFrame::~VideoFrame() {
00229     delete bits;
00230 }
00231 
00232 
00233 BinkDecoder::AudioInfo::AudioInfo() : bits(0), bands(0), rdft(0), dct(0) {
00234 }
00235 
00236 BinkDecoder::AudioInfo::~AudioInfo() {
00237     delete bits;
00238 
00239     delete[] bands;
00240 
00241     delete rdft;
00242     delete dct;
00243 }
00244 
00245 BinkDecoder::BinkVideoTrack::BinkVideoTrack(uint32 width, uint32 height, const Graphics::PixelFormat &format, uint32 frameCount, const Common::Rational &frameRate, bool swapPlanes, bool hasAlpha, uint32 id) :
00246         _frameCount(frameCount), _frameRate(frameRate), _swapPlanes(swapPlanes), _hasAlpha(hasAlpha), _id(id) {
00247     _curFrame = -1;
00248 
00249     for (int i = 0; i < 16; i++)
00250         _huffman[i] = 0;
00251 
00252     for (int i = 0; i < kSourceMAX; i++) {
00253         _bundles[i].countLength = 0;
00254 
00255         _bundles[i].huffman.index = 0;
00256         for (int j = 0; j < 16; j++)
00257             _bundles[i].huffman.symbols[j] = j;
00258 
00259         _bundles[i].data     = 0;
00260         _bundles[i].dataEnd  = 0;
00261         _bundles[i].curDec   = 0;
00262         _bundles[i].curPtr   = 0;
00263     }
00264 
00265     for (int i = 0; i < 16; i++) {
00266         _colHighHuffman[i].index = 0;
00267         for (int j = 0; j < 16; j++)
00268             _colHighHuffman[i].symbols[j] = j;
00269     }
00270 
00271     // Make the surface even-sized:
00272     _surfaceHeight = height;
00273     _surfaceWidth = width;
00274 
00275     if (height & 1) {
00276         _surfaceHeight++;
00277     }
00278     if (width & 1) {
00279         _surfaceWidth++;
00280     }
00281 
00282     _surface.create(_surfaceWidth, _surfaceHeight, format);
00283     // Since we over-allocate to make surfaces even-sized
00284     // we need to set the actual VIDEO size back into the
00285     // surface.
00286     _surface.h = height;
00287     _surface.w = width;
00288 
00289     // Compute the video dimensions in blocks
00290     _yBlockWidth   = (width  +  7) >> 3;
00291     _yBlockHeight  = (height +  7) >> 3;
00292     _uvBlockWidth  = (width  + 15) >> 4;
00293     _uvBlockHeight = (height + 15) >> 4;
00294 
00295     // The planes are sized according to the number of blocks
00296     _curPlanes[0] = new byte[_yBlockWidth  * 8 * _yBlockHeight  * 8]; // Y
00297     _curPlanes[1] = new byte[_uvBlockWidth * 8 * _uvBlockHeight * 8]; // U, 1/4 resolution
00298     _curPlanes[2] = new byte[_uvBlockWidth * 8 * _uvBlockHeight * 8]; // V, 1/4 resolution
00299     _curPlanes[3] = new byte[_yBlockWidth  * 8 * _yBlockHeight  * 8]; // A
00300     _oldPlanes[0] = new byte[_yBlockWidth  * 8 * _yBlockHeight  * 8]; // Y
00301     _oldPlanes[1] = new byte[_uvBlockWidth * 8 * _uvBlockHeight * 8]; // U, 1/4 resolution
00302     _oldPlanes[2] = new byte[_uvBlockWidth * 8 * _uvBlockHeight * 8]; // V, 1/4 resolution
00303     _oldPlanes[3] = new byte[_yBlockWidth  * 8 * _yBlockHeight  * 8]; // A
00304 
00305     // Initialize the video with solid black
00306     memset(_curPlanes[0],   0, _yBlockWidth  * 8 * _yBlockHeight  * 8);
00307     memset(_curPlanes[1],   0, _uvBlockWidth * 8 * _uvBlockHeight * 8);
00308     memset(_curPlanes[2],   0, _uvBlockWidth * 8 * _uvBlockHeight * 8);
00309     memset(_curPlanes[3], 255, _yBlockWidth  * 8 * _yBlockHeight  * 8);
00310     memset(_oldPlanes[0],   0, _yBlockWidth  * 8 * _yBlockHeight  * 8);
00311     memset(_oldPlanes[1],   0, _uvBlockWidth * 8 * _uvBlockHeight * 8);
00312     memset(_oldPlanes[2],   0, _uvBlockWidth * 8 * _uvBlockHeight * 8);
00313     memset(_oldPlanes[3], 255, _yBlockWidth  * 8 * _yBlockHeight  * 8);
00314 
00315     initBundles();
00316     initHuffman();
00317 }
00318 
00319 BinkDecoder::BinkVideoTrack::~BinkVideoTrack() {
00320     for (int i = 0; i < 4; i++) {
00321         delete[] _curPlanes[i]; _curPlanes[i] = 0;
00322         delete[] _oldPlanes[i]; _oldPlanes[i] = 0;
00323     }
00324 
00325     deinitBundles();
00326 
00327     for (int i = 0; i < 16; i++) {
00328         delete _huffman[i];
00329         _huffman[i] = 0;
00330     }
00331 
00332     _surface.free();
00333 }
00334 
00335 // ResidualVM-specific class -- Duplicated from audio/decoders/quicktime.cpp
00336 // If the Bink seeking code ever makes it to ScummVM, move SilentAudioStream
00337 // out of quicktime.cpp so that it can be shared.
00341 class SilentAudioStream : public Audio::AudioStream {
00342 public:
00343     SilentAudioStream(int rate, bool stereo) : _rate(rate), _isStereo(stereo) {}
00344 
00345     int readBuffer(int16 *buffer, const int numSamples) {
00346         memset(buffer, 0, numSamples * 2);
00347         return numSamples;
00348     }
00349 
00350     bool endOfData() const { return false; } // it never ends!
00351     bool isStereo() const { return _isStereo; }
00352     int getRate() const { return _rate; }
00353 
00354 private:
00355     int _rate;
00356     bool _isStereo;
00357 };
00358 
00359 // ResidualVM-specific function
00360 Common::Rational BinkDecoder::getFrameRate() {
00361     BinkVideoTrack *videoTrack = (BinkVideoTrack *)getTrack(0);
00362 
00363     return videoTrack->getFrameRate();
00364 }
00365 
00366 // ResidualVM-specific function
00367 bool BinkDecoder::seekIntern(const Audio::Timestamp &time) {
00368     BinkVideoTrack *videoTrack = (BinkVideoTrack *)getTrack(0);
00369 
00370     uint32 frame = videoTrack->getFrameAtTime(time);
00371 
00372     // Track down the keyframe
00373     uint32 keyFrame = findKeyFrame(frame);
00374     videoTrack->setCurFrame(keyFrame - 1);
00375 
00376     // Adjust the video track to use for seeking
00377     findNextVideoTrack();
00378 
00379     if (frame == keyFrame) {
00380         // We're already good, no need to go further
00381         return true;
00382     }
00383 
00384     // Seek the audio tracks
00385     for (uint32 i = 0; i < _audioTracks.size(); i++) {
00386         BinkAudioTrack *audioTrack = (BinkAudioTrack *)getTrack(i + 1);
00387         audioTrack->seek(videoTrack->getFrameTime(keyFrame));
00388     }
00389 
00390     while (getCurFrame() < (int32)frame - 1)
00391         decodeNextFrame();
00392 
00393     // Skip decoded audio between the keyframe and the target frame
00394     for (uint32 i = 0; i < _audioTracks.size(); i++) {
00395         BinkAudioTrack *audioTrack = (BinkAudioTrack *)getTrack(i + 1);
00396         int rate = audioTrack->getRate();
00397 
00398         Audio::Timestamp delay = videoTrack->getFrameTime(frame - 1).convertToFramerate(rate)
00399                 - videoTrack->getFrameTime(keyFrame).convertToFramerate(rate);
00400 
00401         audioTrack->skipSamples(delay);
00402     }
00403 
00404     return true;
00405 }
00406 
00407 // ResidualVM-specific function
00408 uint32 BinkDecoder::findKeyFrame(uint32 frame) const {
00409     assert(frame < _frames.size());
00410 
00411     for (int i = frame; i >= 0; i--) {
00412         if (_frames[i].keyFrame)
00413             return i;
00414     }
00415 
00416     // If none found, we'll assume the requested frame is a key frame
00417     return frame;
00418 }
00419 
00420 // ResidualVM-specific function
00421 int BinkDecoder::BinkAudioTrack::getRate() {
00422     return _audioStream->getRate();
00423 }
00424 
00425 // ResidualVM-specific function
00426 void BinkDecoder::BinkAudioTrack::skipSamples(const Audio::Timestamp &length) {
00427     int32 sampleCount = length.totalNumberOfFrames();
00428 
00429     if (sampleCount <= 0)
00430         return;
00431 
00432     if (_audioStream->isStereo())
00433         sampleCount *= 2;
00434 
00435     int16 *tempBuffer = new int16[sampleCount];
00436     _audioStream->readBuffer(tempBuffer, sampleCount);
00437     delete[] tempBuffer;
00438 }
00439 
00440 // ResidualVM-specific function
00441 bool BinkDecoder::BinkAudioTrack::seek(const Audio::Timestamp &time) {
00442     // Don't window the output with the previous frame -- there is no output from the previous frame
00443     _audioInfo->first = true;
00444 
00445     if (time != Audio::Timestamp(0)) {
00446         // The first frame of the file contains an audio prebuffer of about 750ms.
00447         // When seeking to a later frame, the audio stream needs to be prefilled with some data
00448         // amounting to 750ms, otherwise the audio stream will underrun and / or the audio and video
00449         // streams will be out of sync.
00450         // For now, we do as the official Bink decoder up to version 1.2j. The stream is prefilled
00451         // with silence.
00452         // The official bink decoder behavior is documented here:
00453         // http://www.radgametools.com/bnkhist.htm#Changes from 1.2i to 1.2J (02-18-2002)
00454         SilentAudioStream *silence = new SilentAudioStream(_audioInfo->outSampleRate, _audioInfo->outChannels == 2);
00455         Audio::AudioStream *prebuffer = Audio::makeLimitingAudioStream(silence, Audio::Timestamp(750));
00456         _audioStream->queueAudioStream(prebuffer);
00457     }
00458 
00459     return true;
00460 }
00461 
00462 // ResidualVM-specific function
00463 bool BinkDecoder::BinkVideoTrack::rewind() {
00464     if (!VideoTrack::rewind()) {
00465         return false;
00466     }
00467 
00468     _curFrame = -1;
00469 
00470     // Re-initialize the video with solid black
00471     memset(_curPlanes[0],   0, _yBlockWidth  * 8 * _yBlockHeight  * 8);
00472     memset(_curPlanes[1],   0, _uvBlockWidth * 8 * _uvBlockHeight * 8);
00473     memset(_curPlanes[2],   0, _uvBlockWidth * 8 * _uvBlockHeight * 8);
00474     memset(_curPlanes[3], 255, _yBlockWidth  * 8 * _yBlockHeight  * 8);
00475     memset(_oldPlanes[0],   0, _yBlockWidth  * 8 * _yBlockHeight  * 8);
00476     memset(_oldPlanes[1],   0, _uvBlockWidth * 8 * _uvBlockHeight * 8);
00477     memset(_oldPlanes[2],   0, _uvBlockWidth * 8 * _uvBlockHeight * 8);
00478     memset(_oldPlanes[3], 255, _yBlockWidth  * 8 * _yBlockHeight  * 8);
00479 
00480     return true;
00481 }
00482 
00483 void BinkDecoder::BinkVideoTrack::decodePacket(VideoFrame &frame) {
00484     assert(frame.bits);
00485 
00486     if (_hasAlpha) {
00487         if (_id == kBIKiID)
00488             frame.bits->skip(32);
00489 
00490         decodePlane(frame, 3, false);
00491     }
00492 
00493     if (_id == kBIKiID)
00494         frame.bits->skip(32);
00495 
00496     for (int i = 0; i < 3; i++) {
00497         int planeIdx = ((i == 0) || !_swapPlanes) ? i : (i ^ 3);
00498 
00499         decodePlane(frame, planeIdx, i != 0);
00500 
00501         if (frame.bits->pos() >= frame.bits->size())
00502             break;
00503     }
00504 
00505     // Convert the YUV data we have to our format
00506     // The width used here is the surface-width, and not the video-width
00507     // to allow for odd-sized videos.
00508     // ResidualVM: added support for Alpha version: YUVAToRGBAMan, _curPlanes[3]
00509     assert(_curPlanes[0] && _curPlanes[1] && _curPlanes[2] && _curPlanes[3]);
00510     YUVAToRGBAMan.convert420(&_surface, Graphics::YUVAToRGBAManager::kScaleITU, _curPlanes[0], _curPlanes[1], _curPlanes[2], _curPlanes[3],
00511             _surfaceWidth, _surfaceHeight, _yBlockWidth * 8, _uvBlockWidth * 8);
00512 
00513     // And swap the planes with the reference planes
00514     for (int i = 0; i < 4; i++)
00515         SWAP(_curPlanes[i], _oldPlanes[i]);
00516 
00517     _curFrame++;
00518 }
00519 
00520 void BinkDecoder::BinkVideoTrack::decodePlane(VideoFrame &video, int planeIdx, bool isChroma) {
00521     uint32 blockWidth  = isChroma ? _uvBlockWidth  : _yBlockWidth;
00522     uint32 blockHeight = isChroma ? _uvBlockHeight : _yBlockHeight;
00523     uint32 width       = blockWidth  * 8;
00524     uint32 height      = blockHeight * 8;
00525 
00526     DecodeContext ctx;
00527 
00528     ctx.video     = &video;
00529     ctx.planeIdx  = planeIdx;
00530     ctx.destStart = _curPlanes[planeIdx];
00531     ctx.destEnd   = _curPlanes[planeIdx] + width * height;
00532     ctx.prevStart = _oldPlanes[planeIdx];
00533     ctx.prevEnd   = _oldPlanes[planeIdx] + width * height;
00534     ctx.pitch     = width;
00535 
00536     for (int i = 0; i < 64; i++) {
00537         ctx.coordMap[i] = (i & 7) + (i >> 3) * ctx.pitch;
00538 
00539         ctx.coordScaledMap1[i] = ((i & 7) * 2 + 0) + (((i >> 3) * 2 + 0) * ctx.pitch);
00540         ctx.coordScaledMap2[i] = ((i & 7) * 2 + 1) + (((i >> 3) * 2 + 0) * ctx.pitch);
00541         ctx.coordScaledMap3[i] = ((i & 7) * 2 + 0) + (((i >> 3) * 2 + 1) * ctx.pitch);
00542         ctx.coordScaledMap4[i] = ((i & 7) * 2 + 1) + (((i >> 3) * 2 + 1) * ctx.pitch);
00543     }
00544 
00545     for (int i = 0; i < kSourceMAX; i++) {
00546         _bundles[i].countLength = _bundles[i].countLengths[isChroma ? 1 : 0];
00547 
00548         readBundle(video, (Source) i);
00549     }
00550 
00551     for (ctx.blockY = 0; ctx.blockY < blockHeight; ctx.blockY++) {
00552         readBlockTypes  (video, _bundles[kSourceBlockTypes]);
00553         readBlockTypes  (video, _bundles[kSourceSubBlockTypes]);
00554         readColors      (video, _bundles[kSourceColors]);
00555         readPatterns    (video, _bundles[kSourcePattern]);
00556         readMotionValues(video, _bundles[kSourceXOff]);
00557         readMotionValues(video, _bundles[kSourceYOff]);
00558         readDCS         (video, _bundles[kSourceIntraDC], kDCStartBits, false);
00559         readDCS         (video, _bundles[kSourceInterDC], kDCStartBits, true);
00560         readRuns        (video, _bundles[kSourceRun]);
00561 
00562         ctx.dest = ctx.destStart + 8 * ctx.blockY * ctx.pitch;
00563         ctx.prev = ctx.prevStart + 8 * ctx.blockY * ctx.pitch;
00564 
00565         for (ctx.blockX = 0; ctx.blockX < blockWidth; ctx.blockX++, ctx.dest += 8, ctx.prev += 8) {
00566             BlockType blockType = (BlockType) getBundleValue(kSourceBlockTypes);
00567 
00568             // 16x16 block type on odd line means part of the already decoded block, so skip it
00569             if ((ctx.blockY & 1) && (blockType == kBlockScaled)) {
00570                 ctx.blockX += 1;
00571                 ctx.dest   += 8;
00572                 ctx.prev   += 8;
00573                 continue;
00574             }
00575 
00576             switch (blockType) {
00577             case kBlockSkip:
00578                 blockSkip(ctx);
00579                 break;
00580             case kBlockScaled:
00581                 blockScaled(ctx);
00582                 break;
00583             case kBlockMotion:
00584                 blockMotion(ctx);
00585                 break;
00586             case kBlockRun:
00587                 blockRun(ctx);
00588                 break;
00589             case kBlockResidue:
00590                 blockResidue(ctx);
00591                 break;
00592             case kBlockIntra:
00593                 blockIntra(ctx);
00594                 break;
00595             case kBlockFill:
00596                 blockFill(ctx);
00597                 break;
00598             case kBlockInter:
00599                 blockInter(ctx);
00600                 break;
00601             case kBlockPattern:
00602                 blockPattern(ctx);
00603                 break;
00604             case kBlockRaw:
00605                 blockRaw(ctx);
00606                 break;
00607             default:
00608                 error("Unknown block type: %d", blockType);
00609             }
00610 
00611         }
00612 
00613     }
00614 
00615     if (video.bits->pos() & 0x1F) // next plane data starts at 32-bit boundary
00616         video.bits->skip(32 - (video.bits->pos() & 0x1F));
00617 
00618 }
00619 
00620 void BinkDecoder::BinkVideoTrack::readBundle(VideoFrame &video, Source source) {
00621     if (source == kSourceColors) {
00622         for (int i = 0; i < 16; i++)
00623             readHuffman(video, _colHighHuffman[i]);
00624 
00625         _colLastVal = 0;
00626     }
00627 
00628     if ((source != kSourceIntraDC) && (source != kSourceInterDC))
00629         readHuffman(video, _bundles[source].huffman);
00630 
00631     _bundles[source].curDec = _bundles[source].data;
00632     _bundles[source].curPtr = _bundles[source].data;
00633 }
00634 
00635 void BinkDecoder::BinkVideoTrack::readHuffman(VideoFrame &video, Huffman &huffman) {
00636     huffman.index = video.bits->getBits(4);
00637 
00638     if (huffman.index == 0) {
00639         // The first tree always gives raw nibbles
00640         for (int i = 0; i < 16; i++)
00641             huffman.symbols[i] = i;
00642 
00643         return;
00644     }
00645 
00646     byte hasSymbol[16];
00647 
00648     if (video.bits->getBit()) {
00649         // Symbol selection
00650         memset(hasSymbol, 0, 16);
00651 
00652         uint8 length = video.bits->getBits(3);
00653         for (int i = 0; i <= length; i++) {
00654             huffman.symbols[i] = video.bits->getBits(4);
00655             hasSymbol[huffman.symbols[i]] = 1;
00656         }
00657 
00658         for (int i = 0; i < 16; i++)
00659             if (hasSymbol[i] == 0)
00660                 huffman.symbols[++length] = i;
00661 
00662         return;
00663     }
00664 
00665     // Symbol shuffling
00666 
00667     byte tmp1[16], tmp2[16];
00668     byte *in = tmp1, *out = tmp2;
00669 
00670     uint8 depth = video.bits->getBits(2);
00671 
00672     for (int i = 0; i < 16; i++)
00673         in[i] = i;
00674 
00675     for (int i = 0; i <= depth; i++) {
00676         int size = 1 << i;
00677 
00678         for (int j = 0; j < 16; j += (size << 1))
00679             mergeHuffmanSymbols(video, out + j, in + j, size);
00680 
00681         SWAP(in, out);
00682     }
00683 
00684     memcpy(huffman.symbols, in, 16);
00685 }
00686 
00687 void BinkDecoder::BinkVideoTrack::mergeHuffmanSymbols(VideoFrame &video, byte *dst, const byte *src, int size) {
00688     const byte *src2  = src + size;
00689     int size2 = size;
00690 
00691     do {
00692         if (!video.bits->getBit()) {
00693             *dst++ = *src++;
00694             size--;
00695         } else {
00696             *dst++ = *src2++;
00697             size2--;
00698         }
00699 
00700     } while (size && size2);
00701 
00702     while (size--)
00703         *dst++ = *src++;
00704 
00705     while (size2--)
00706         *dst++ = *src2++;
00707 }
00708 
00709 void BinkDecoder::BinkVideoTrack::initBundles() {
00710     uint32 bw     = (_surface.w + 7) >> 3;
00711     uint32 bh     = (_surface.h + 7) >> 3;
00712     uint32 blocks = bw * bh;
00713 
00714     for (int i = 0; i < kSourceMAX; i++) {
00715         _bundles[i].data    = new byte[blocks * 64];
00716         _bundles[i].dataEnd = _bundles[i].data + blocks * 64;
00717     }
00718 
00719     uint32 cbw[2] = { (uint32)((_surface.w + 7) >> 3), (uint32)((_surface.w  + 15) >> 4) };
00720     uint32 cw [2] = { (uint32)( _surface.w          ), (uint32)( _surface.w        >> 1) };
00721 
00722     // Calculate the lengths of an element count in bits
00723     for (int i = 0; i < 2; i++) {
00724         int width = MAX<uint32>(cw[i], 8);
00725 
00726         _bundles[kSourceBlockTypes   ].countLengths[i] = Common::intLog2((width       >> 3) + 511) + 1;
00727         _bundles[kSourceSubBlockTypes].countLengths[i] = Common::intLog2(((width + 7) >> 4) + 511) + 1;
00728         _bundles[kSourceColors       ].countLengths[i] = Common::intLog2((cbw[i])     * 64  + 511) + 1;
00729         _bundles[kSourceIntraDC      ].countLengths[i] = Common::intLog2((width       >> 3) + 511) + 1;
00730         _bundles[kSourceInterDC      ].countLengths[i] = Common::intLog2((width       >> 3) + 511) + 1;
00731         _bundles[kSourceXOff         ].countLengths[i] = Common::intLog2((width       >> 3) + 511) + 1;
00732         _bundles[kSourceYOff         ].countLengths[i] = Common::intLog2((width       >> 3) + 511) + 1;
00733         _bundles[kSourcePattern      ].countLengths[i] = Common::intLog2((cbw[i]      << 3) + 511) + 1;
00734         _bundles[kSourceRun          ].countLengths[i] = Common::intLog2((cbw[i])     * 48  + 511) + 1;
00735     }
00736 }
00737 
00738 void BinkDecoder::BinkVideoTrack::deinitBundles() {
00739     for (int i = 0; i < kSourceMAX; i++)
00740         delete[] _bundles[i].data;
00741 }
00742 
00743 void BinkDecoder::BinkVideoTrack::initHuffman() {
00744     for (int i = 0; i < 16; i++)
00745         _huffman[i] = new Common::Huffman(binkHuffmanLengths[i][15], 16, binkHuffmanCodes[i], binkHuffmanLengths[i]);
00746 }
00747 
00748 byte BinkDecoder::BinkVideoTrack::getHuffmanSymbol(VideoFrame &video, Huffman &huffman) {
00749     return huffman.symbols[_huffman[huffman.index]->getSymbol(*video.bits)];
00750 }
00751 
00752 int32 BinkDecoder::BinkVideoTrack::getBundleValue(Source source) {
00753     if ((source < kSourceXOff) || (source == kSourceRun))
00754         return *_bundles[source].curPtr++;
00755 
00756     if ((source == kSourceXOff) || (source == kSourceYOff))
00757         return (int8) *_bundles[source].curPtr++;
00758 
00759     int16 ret = *((int16 *) _bundles[source].curPtr);
00760 
00761     _bundles[source].curPtr += 2;
00762 
00763     return ret;
00764 }
00765 
00766 uint32 BinkDecoder::BinkVideoTrack::readBundleCount(VideoFrame &video, Bundle &bundle) {
00767     if (!bundle.curDec || (bundle.curDec > bundle.curPtr))
00768         return 0;
00769 
00770     uint32 n = video.bits->getBits(bundle.countLength);
00771     if (n == 0)
00772         bundle.curDec = 0;
00773 
00774     return n;
00775 }
00776 
00777 void BinkDecoder::BinkVideoTrack::blockSkip(DecodeContext &ctx) {
00778     byte *dest = ctx.dest;
00779     byte *prev = ctx.prev;
00780 
00781     for (int j = 0; j < 8; j++, dest += ctx.pitch, prev += ctx.pitch)
00782         memcpy(dest, prev, 8);
00783 }
00784 
00785 void BinkDecoder::BinkVideoTrack::blockScaledSkip(DecodeContext &ctx) {
00786     byte *dest = ctx.dest;
00787     byte *prev = ctx.prev;
00788 
00789     for (int j = 0; j < 16; j++, dest += ctx.pitch, prev += ctx.pitch)
00790         memcpy(dest, prev, 16);
00791 }
00792 
00793 void BinkDecoder::BinkVideoTrack::blockScaledRun(DecodeContext &ctx) {
00794     const uint8 *scan = binkPatterns[ctx.video->bits->getBits(4)];
00795 
00796     int i = 0;
00797     do {
00798         int run = getBundleValue(kSourceRun) + 1;
00799 
00800         i += run;
00801         if (i > 64)
00802             error("Run went out of bounds");
00803 
00804         if (ctx.video->bits->getBit()) {
00805 
00806             byte v = getBundleValue(kSourceColors);
00807             for (int j = 0; j < run; j++, scan++)
00808                 ctx.dest[ctx.coordScaledMap1[*scan]] =
00809                 ctx.dest[ctx.coordScaledMap2[*scan]] =
00810                 ctx.dest[ctx.coordScaledMap3[*scan]] =
00811                 ctx.dest[ctx.coordScaledMap4[*scan]] = v;
00812 
00813         } else
00814             for (int j = 0; j < run; j++, scan++)
00815                 ctx.dest[ctx.coordScaledMap1[*scan]] =
00816                 ctx.dest[ctx.coordScaledMap2[*scan]] =
00817                 ctx.dest[ctx.coordScaledMap3[*scan]] =
00818                 ctx.dest[ctx.coordScaledMap4[*scan]] = getBundleValue(kSourceColors);
00819 
00820     } while (i < 63);
00821 
00822     if (i == 63)
00823         ctx.dest[ctx.coordScaledMap1[*scan]] =
00824         ctx.dest[ctx.coordScaledMap2[*scan]] =
00825         ctx.dest[ctx.coordScaledMap3[*scan]] =
00826         ctx.dest[ctx.coordScaledMap4[*scan]] = getBundleValue(kSourceColors);
00827 }
00828 
00829 void BinkDecoder::BinkVideoTrack::blockScaledIntra(DecodeContext &ctx) {
00830     int16 block[64];
00831     memset(block, 0, 64 * sizeof(int16));
00832 
00833     block[0] = getBundleValue(kSourceIntraDC);
00834 
00835     readDCTCoeffs(*ctx.video, block, true);
00836 
00837     IDCT(block);
00838 
00839     int16 *src   = block;
00840     byte  *dest1 = ctx.dest;
00841     byte  *dest2 = ctx.dest + ctx.pitch;
00842     for (int j = 0; j < 8; j++, dest1 += (ctx.pitch << 1) - 16, dest2 += (ctx.pitch << 1) - 16, src += 8) {
00843 
00844         for (int i = 0; i < 8; i++, dest1 += 2, dest2 += 2)
00845             dest1[0] = dest1[1] = dest2[0] = dest2[1] = src[i];
00846 
00847     }
00848 }
00849 
00850 void BinkDecoder::BinkVideoTrack::blockScaledFill(DecodeContext &ctx) {
00851     byte v = getBundleValue(kSourceColors);
00852 
00853     byte *dest = ctx.dest;
00854     for (int i = 0; i < 16; i++, dest += ctx.pitch)
00855         memset(dest, v, 16);
00856 }
00857 
00858 void BinkDecoder::BinkVideoTrack::blockScaledPattern(DecodeContext &ctx) {
00859     byte col[2];
00860 
00861     for (int i = 0; i < 2; i++)
00862         col[i] = getBundleValue(kSourceColors);
00863 
00864     byte *dest1 = ctx.dest;
00865     byte *dest2 = ctx.dest + ctx.pitch;
00866     for (int j = 0; j < 8; j++, dest1 += (ctx.pitch << 1) - 16, dest2 += (ctx.pitch << 1) - 16) {
00867         byte v = getBundleValue(kSourcePattern);
00868 
00869         for (int i = 0; i < 8; i++, dest1 += 2, dest2 += 2, v >>= 1)
00870             dest1[0] = dest1[1] = dest2[0] = dest2[1] = col[v & 1];
00871     }
00872 }
00873 
00874 void BinkDecoder::BinkVideoTrack::blockScaledRaw(DecodeContext &ctx) {
00875     byte row[8];
00876 
00877     byte *dest1 = ctx.dest;
00878     byte *dest2 = ctx.dest + ctx.pitch;
00879     for (int j = 0; j < 8; j++, dest1 += (ctx.pitch << 1) - 16, dest2 += (ctx.pitch << 1) - 16) {
00880         memcpy(row, _bundles[kSourceColors].curPtr, 8);
00881 
00882         for (int i = 0; i < 8; i++, dest1 += 2, dest2 += 2)
00883             dest1[0] = dest1[1] = dest2[0] = dest2[1] = row[i];
00884 
00885         _bundles[kSourceColors].curPtr += 8;
00886     }
00887 }
00888 
00889 void BinkDecoder::BinkVideoTrack::blockScaled(DecodeContext &ctx) {
00890     BlockType blockType = (BlockType) getBundleValue(kSourceSubBlockTypes);
00891 
00892     switch (blockType) {
00893     case kBlockRun:
00894         blockScaledRun(ctx);
00895         break;
00896     case kBlockIntra:
00897         blockScaledIntra(ctx);
00898         break;
00899     case kBlockFill:
00900         blockScaledFill(ctx);
00901         break;
00902     case kBlockPattern:
00903         blockScaledPattern(ctx);
00904         break;
00905     case kBlockRaw:
00906         blockScaledRaw(ctx);
00907         break;
00908     default:
00909         error("Invalid 16x16 block type: %d", blockType);
00910     }
00911 
00912     ctx.blockX += 1;
00913     ctx.dest   += 8;
00914     ctx.prev   += 8;
00915 }
00916 
00917 void BinkDecoder::BinkVideoTrack::blockMotion(DecodeContext &ctx) {
00918     int8 xOff = getBundleValue(kSourceXOff);
00919     int8 yOff = getBundleValue(kSourceYOff);
00920 
00921     byte *dest = ctx.dest;
00922     byte *prev = ctx.prev + yOff * ((int32) ctx.pitch) + xOff;
00923     if ((prev < ctx.prevStart) || (prev > ctx.prevEnd))
00924         error("Copy out of bounds (%d | %d)", ctx.blockX * 8 + xOff, ctx.blockY * 8 + yOff);
00925 
00926     for (int j = 0; j < 8; j++, dest += ctx.pitch, prev += ctx.pitch)
00927         memcpy(dest, prev, 8);
00928 }
00929 
00930 void BinkDecoder::BinkVideoTrack::blockRun(DecodeContext &ctx) {
00931     const uint8 *scan = binkPatterns[ctx.video->bits->getBits(4)];
00932 
00933     int i = 0;
00934     do {
00935         int run = getBundleValue(kSourceRun) + 1;
00936 
00937         i += run;
00938         if (i > 64)
00939             error("Run went out of bounds");
00940 
00941         if (ctx.video->bits->getBit()) {
00942 
00943             byte v = getBundleValue(kSourceColors);
00944             for (int j = 0; j < run; j++)
00945                 ctx.dest[ctx.coordMap[*scan++]] = v;
00946 
00947         } else
00948             for (int j = 0; j < run; j++)
00949                 ctx.dest[ctx.coordMap[*scan++]] = getBundleValue(kSourceColors);
00950 
00951     } while (i < 63);
00952 
00953     if (i == 63)
00954         ctx.dest[ctx.coordMap[*scan++]] = getBundleValue(kSourceColors);
00955 }
00956 
00957 void BinkDecoder::BinkVideoTrack::blockResidue(DecodeContext &ctx) {
00958     blockMotion(ctx);
00959 
00960     byte v = ctx.video->bits->getBits(7);
00961 
00962     int16 block[64];
00963     memset(block, 0, 64 * sizeof(int16));
00964 
00965     readResidue(*ctx.video, block, v);
00966 
00967     byte  *dst = ctx.dest;
00968     int16 *src = block;
00969     for (int i = 0; i < 8; i++, dst += ctx.pitch, src += 8)
00970         for (int j = 0; j < 8; j++)
00971             dst[j] += src[j];
00972 }
00973 
00974 void BinkDecoder::BinkVideoTrack::blockIntra(DecodeContext &ctx) {
00975     int16 block[64];
00976     memset(block, 0, 64 * sizeof(int16));
00977 
00978     block[0] = getBundleValue(kSourceIntraDC);
00979 
00980     readDCTCoeffs(*ctx.video, block, true);
00981 
00982     IDCTPut(ctx, block);
00983 }
00984 
00985 void BinkDecoder::BinkVideoTrack::blockFill(DecodeContext &ctx) {
00986     byte v = getBundleValue(kSourceColors);
00987 
00988     byte *dest = ctx.dest;
00989     for (int i = 0; i < 8; i++, dest += ctx.pitch)
00990         memset(dest, v, 8);
00991 }
00992 
00993 void BinkDecoder::BinkVideoTrack::blockInter(DecodeContext &ctx) {
00994     blockMotion(ctx);
00995 
00996     int16 block[64];
00997     memset(block, 0, 64 * sizeof(int16));
00998 
00999     block[0] = getBundleValue(kSourceInterDC);
01000 
01001     readDCTCoeffs(*ctx.video, block, false);
01002 
01003     IDCTAdd(ctx, block);
01004 }
01005 
01006 void BinkDecoder::BinkVideoTrack::blockPattern(DecodeContext &ctx) {
01007     byte col[2];
01008 
01009     for (int i = 0; i < 2; i++)
01010         col[i] = getBundleValue(kSourceColors);
01011 
01012     byte *dest = ctx.dest;
01013     for (int i = 0; i < 8; i++, dest += ctx.pitch - 8) {
01014         byte v = getBundleValue(kSourcePattern);
01015 
01016         for (int j = 0; j < 8; j++, v >>= 1)
01017             *dest++ = col[v & 1];
01018     }
01019 }
01020 
01021 void BinkDecoder::BinkVideoTrack::blockRaw(DecodeContext &ctx) {
01022     byte *dest = ctx.dest;
01023     byte *data = _bundles[kSourceColors].curPtr;
01024     for (int i = 0; i < 8; i++, dest += ctx.pitch, data += 8)
01025         memcpy(dest, data, 8);
01026 
01027     _bundles[kSourceColors].curPtr += 64;
01028 }
01029 
01030 void BinkDecoder::BinkVideoTrack::readRuns(VideoFrame &video, Bundle &bundle) {
01031     uint32 n = readBundleCount(video, bundle);
01032     if (n == 0)
01033         return;
01034 
01035     byte *decEnd = bundle.curDec + n;
01036     if (decEnd > bundle.dataEnd)
01037         error("Run value went out of bounds");
01038 
01039     if (video.bits->getBit()) {
01040         byte v = video.bits->getBits(4);
01041 
01042         memset(bundle.curDec, v, n);
01043         bundle.curDec += n;
01044 
01045     } else
01046         while (bundle.curDec < decEnd)
01047             *bundle.curDec++ = getHuffmanSymbol(video, bundle.huffman);
01048 }
01049 
01050 void BinkDecoder::BinkVideoTrack::readMotionValues(VideoFrame &video, Bundle &bundle) {
01051     uint32 n = readBundleCount(video, bundle);
01052     if (n == 0)
01053         return;
01054 
01055     byte *decEnd = bundle.curDec + n;
01056     if (decEnd > bundle.dataEnd)
01057         error("Too many motion values");
01058 
01059     if (video.bits->getBit()) {
01060         byte v = video.bits->getBits(4);
01061 
01062         if (v) {
01063             int sign = -(int)video.bits->getBit();
01064             v = (v ^ sign) - sign;
01065         }
01066 
01067         memset(bundle.curDec, v, n);
01068 
01069         bundle.curDec += n;
01070         return;
01071     }
01072 
01073     do {
01074         byte v = getHuffmanSymbol(video, bundle.huffman);
01075 
01076         if (v) {
01077             int sign = -(int)video.bits->getBit();
01078             v = (v ^ sign) - sign;
01079         }
01080 
01081         *bundle.curDec++ = v;
01082 
01083     } while (bundle.curDec < decEnd);
01084 }
01085 
01086 const uint8 rleLens[4] = { 4, 8, 12, 32 };
01087 void BinkDecoder::BinkVideoTrack::readBlockTypes(VideoFrame &video, Bundle &bundle) {
01088     uint32 n = readBundleCount(video, bundle);
01089     if (n == 0)
01090         return;
01091 
01092     byte *decEnd = bundle.curDec + n;
01093     if (decEnd > bundle.dataEnd)
01094         error("Too many block type values");
01095 
01096     if (video.bits->getBit()) {
01097         byte v = video.bits->getBits(4);
01098 
01099         memset(bundle.curDec, v, n);
01100 
01101         bundle.curDec += n;
01102         return;
01103     }
01104 
01105     byte last = 0;
01106     do {
01107 
01108         byte v = getHuffmanSymbol(video, bundle.huffman);
01109 
01110         if (v < 12) {
01111             last = v;
01112             *bundle.curDec++ = v;
01113         } else {
01114             int run = rleLens[v - 12];
01115 
01116             memset(bundle.curDec, last, run);
01117 
01118             bundle.curDec += run;
01119         }
01120 
01121     } while (bundle.curDec < decEnd);
01122 }
01123 
01124 void BinkDecoder::BinkVideoTrack::readPatterns(VideoFrame &video, Bundle &bundle) {
01125     uint32 n = readBundleCount(video, bundle);
01126     if (n == 0)
01127         return;
01128 
01129     byte *decEnd = bundle.curDec + n;
01130     if (decEnd > bundle.dataEnd)
01131         error("Too many pattern values");
01132 
01133     byte v;
01134     while (bundle.curDec < decEnd) {
01135         v  = getHuffmanSymbol(video, bundle.huffman);
01136         v |= getHuffmanSymbol(video, bundle.huffman) << 4;
01137         *bundle.curDec++ = v;
01138     }
01139 }
01140 
01141 
01142 void BinkDecoder::BinkVideoTrack::readColors(VideoFrame &video, Bundle &bundle) {
01143     uint32 n = readBundleCount(video, bundle);
01144     if (n == 0)
01145         return;
01146 
01147     byte *decEnd = bundle.curDec + n;
01148     if (decEnd > bundle.dataEnd)
01149         error("Too many color values");
01150 
01151     if (video.bits->getBit()) {
01152         _colLastVal = getHuffmanSymbol(video, _colHighHuffman[_colLastVal]);
01153 
01154         byte v;
01155         v = getHuffmanSymbol(video, bundle.huffman);
01156         v = (_colLastVal << 4) | v;
01157 
01158         if (_id != kBIKiID) {
01159             int sign = ((int8) v) >> 7;
01160             v = ((v & 0x7F) ^ sign) - sign;
01161             v += 0x80;
01162         }
01163 
01164         memset(bundle.curDec, v, n);
01165         bundle.curDec += n;
01166 
01167         return;
01168     }
01169 
01170     while (bundle.curDec < decEnd) {
01171         _colLastVal = getHuffmanSymbol(video, _colHighHuffman[_colLastVal]);
01172 
01173         byte v;
01174         v = getHuffmanSymbol(video, bundle.huffman);
01175         v = (_colLastVal << 4) | v;
01176 
01177         if (_id != kBIKiID) {
01178             int sign = ((int8) v) >> 7;
01179             v = ((v & 0x7F) ^ sign) - sign;
01180             v += 0x80;
01181         }
01182         *bundle.curDec++ = v;
01183     }
01184 }
01185 
01186 void BinkDecoder::BinkVideoTrack::readDCS(VideoFrame &video, Bundle &bundle, int startBits, bool hasSign) {
01187     uint32 length = readBundleCount(video, bundle);
01188     if (length == 0)
01189         return;
01190 
01191     int16 *dest = (int16 *) bundle.curDec;
01192 
01193     int32 v = video.bits->getBits(startBits - (hasSign ? 1 : 0));
01194     if (v && hasSign) {
01195         int sign = -(int)video.bits->getBit();
01196         v = (v ^ sign) - sign;
01197     }
01198 
01199     *dest++ = v;
01200     length--;
01201 
01202     for (uint32 i = 0; i < length; i += 8) {
01203         uint32 length2 = MIN<uint32>(length - i, 8);
01204 
01205         byte bSize = video.bits->getBits(4);
01206 
01207         if (bSize) {
01208 
01209             for (uint32 j = 0; j < length2; j++) {
01210                 int16 v2 = video.bits->getBits(bSize);
01211                 if (v2) {
01212                     int sign = -(int)video.bits->getBit();
01213                     v2 = (v2 ^ sign) - sign;
01214                 }
01215 
01216                 v += v2;
01217                 *dest++ = v;
01218 
01219                 if ((v < -32768) || (v > 32767))
01220                     error("DC value went out of bounds: %d", v);
01221             }
01222 
01223         } else
01224             for (uint32 j = 0; j < length2; j++)
01225                 *dest++ = v;
01226     }
01227 
01228     bundle.curDec = (byte *) dest;
01229 }
01230 
01232 void BinkDecoder::BinkVideoTrack::readDCTCoeffs(VideoFrame &video, int16 *block, bool isIntra) {
01233     int coefCount = 0;
01234     int coefIdx[64];
01235 
01236     int listStart = 64;
01237     int listEnd   = 64;
01238 
01239     int coefList[128];      int modeList[128];
01240     coefList[listEnd] = 4;  modeList[listEnd++] = 0;
01241     coefList[listEnd] = 24; modeList[listEnd++] = 0;
01242     coefList[listEnd] = 44; modeList[listEnd++] = 0;
01243     coefList[listEnd] = 1;  modeList[listEnd++] = 3;
01244     coefList[listEnd] = 2;  modeList[listEnd++] = 3;
01245     coefList[listEnd] = 3;  modeList[listEnd++] = 3;
01246 
01247     int bits = video.bits->getBits(4) - 1;
01248     for (int mask = 1 << bits; bits >= 0; mask >>= 1, bits--) {
01249         int listPos = listStart;
01250 
01251         while (listPos < listEnd) {
01252 
01253             if (!(modeList[listPos] | coefList[listPos]) || !video.bits->getBit()) {
01254                 listPos++;
01255                 continue;
01256             }
01257 
01258             int ccoef = coefList[listPos];
01259             int mode  = modeList[listPos];
01260 
01261             switch (mode) {
01262             case 0:
01263                 coefList[listPos] = ccoef + 4;
01264                 modeList[listPos] = 1;
01265                 // fall through
01266             case 2:
01267                 if (mode == 2) {
01268                     coefList[listPos]   = 0;
01269                     modeList[listPos++] = 0;
01270                 }
01271                 for (int i = 0; i < 4; i++, ccoef++) {
01272                     if (video.bits->getBit()) {
01273                         coefList[--listStart] = ccoef;
01274                         modeList[  listStart] = 3;
01275                     } else {
01276                         int t;
01277                         if (!bits) {
01278                             t = 1 - (video.bits->getBit() << 1);
01279                         } else {
01280                             t = video.bits->getBits(bits) | mask;
01281 
01282                             int sign = -(int)video.bits->getBit();
01283                             t = (t ^ sign) - sign;
01284                         }
01285                         block[binkScan[ccoef]] = t;
01286                         coefIdx[coefCount++]   = ccoef;
01287                     }
01288                 }
01289                 break;
01290 
01291             case 1:
01292                 modeList[listPos] = 2;
01293                 for (int i = 0; i < 3; i++) {
01294                     ccoef += 4;
01295                     coefList[listEnd]   = ccoef;
01296                     modeList[listEnd++] = 2;
01297                 }
01298                 break;
01299 
01300             case 3:
01301                 int t;
01302                 if (!bits) {
01303                     t = 1 - (video.bits->getBit() << 1);
01304                 } else {
01305                     t = video.bits->getBits(bits) | mask;
01306 
01307                     int sign = -(int)video.bits->getBit();
01308                     t = (t ^ sign) - sign;
01309                 }
01310                 block[binkScan[ccoef]] = t;
01311                 coefIdx[coefCount++]   = ccoef;
01312                 coefList[listPos]      = 0;
01313                 modeList[listPos++]    = 0;
01314                 break;
01315             }
01316         }
01317     }
01318 
01319     uint8 quantIdx = video.bits->getBits(4);
01320     const uint32 *quant = isIntra ? binkIntraQuant[quantIdx] : binkInterQuant[quantIdx];
01321     block[0] = (block[0] * quant[0]) >> 11;
01322 
01323     for (int i = 0; i < coefCount; i++) {
01324         int idx = coefIdx[i];
01325         block[binkScan[idx]] = (block[binkScan[idx]] * quant[idx]) >> 11;
01326     }
01327 
01328 }
01329 
01331 void BinkDecoder::BinkVideoTrack::readResidue(VideoFrame &video, int16 *block, int masksCount) {
01332     int nzCoeff[64];
01333     int nzCoeffCount = 0;
01334 
01335     int listStart = 64;
01336     int listEnd   = 64;
01337 
01338     int coefList[128];      int modeList[128];
01339     coefList[listEnd] =  4; modeList[listEnd++] = 0;
01340     coefList[listEnd] = 24; modeList[listEnd++] = 0;
01341     coefList[listEnd] = 44; modeList[listEnd++] = 0;
01342     coefList[listEnd] =  0; modeList[listEnd++] = 2;
01343 
01344     for (int mask = 1 << video.bits->getBits(3); mask; mask >>= 1) {
01345 
01346         for (int i = 0; i < nzCoeffCount; i++) {
01347             if (!video.bits->getBit())
01348                 continue;
01349             if (block[nzCoeff[i]] < 0)
01350                 block[nzCoeff[i]] -= mask;
01351             else
01352                 block[nzCoeff[i]] += mask;
01353             masksCount--;
01354             if (masksCount < 0)
01355                 return;
01356         }
01357 
01358         int listPos = listStart;
01359         while (listPos < listEnd) {
01360 
01361             if (!(coefList[listPos] | modeList[listPos]) || !video.bits->getBit()) {
01362                 listPos++;
01363                 continue;
01364             }
01365 
01366             int ccoef = coefList[listPos];
01367             int mode  = modeList[listPos];
01368 
01369             switch (mode) {
01370             case 0:
01371                 coefList[listPos] = ccoef + 4;
01372                 modeList[listPos] = 1;
01373                 // fall through
01374             case 2:
01375                 if (mode == 2) {
01376                     coefList[listPos]   = 0;
01377                     modeList[listPos++] = 0;
01378                 }
01379 
01380                 for (int i = 0; i < 4; i++, ccoef++) {
01381                     if (video.bits->getBit()) {
01382                         coefList[--listStart] = ccoef;
01383                         modeList[  listStart] = 3;
01384                     } else {
01385                         nzCoeff[nzCoeffCount++] = binkScan[ccoef];
01386 
01387                         int sign = -(int)video.bits->getBit();
01388                         block[binkScan[ccoef]] = (mask ^ sign) - sign;
01389 
01390                         masksCount--;
01391                         if (masksCount < 0)
01392                             return;
01393                     }
01394                 }
01395                 break;
01396 
01397             case 1:
01398                 modeList[listPos] = 2;
01399                 for (int i = 0; i < 3; i++) {
01400                     ccoef += 4;
01401                     coefList[listEnd]   = ccoef;
01402                     modeList[listEnd++] = 2;
01403                 }
01404                 break;
01405 
01406             case 3:
01407                 nzCoeff[nzCoeffCount++] = binkScan[ccoef];
01408 
01409                 int sign = -(int)video.bits->getBit();
01410                 block[binkScan[ccoef]] = (mask ^ sign) - sign;
01411 
01412                 coefList[listPos]   = 0;
01413                 modeList[listPos++] = 0;
01414                 masksCount--;
01415                 if (masksCount < 0)
01416                     return;
01417                 break;
01418             }
01419         }
01420     }
01421 }
01422 
01423 #define A1  2896 /* (1/sqrt(2))<<12 */
01424 #define A2  2217
01425 #define A3  3784
01426 #define A4 -5352
01427 
01428 #define IDCT_TRANSFORM(dest,s0,s1,s2,s3,s4,s5,s6,s7,d0,d1,d2,d3,d4,d5,d6,d7,munge,src) {\
01429     const int a0 = (src)[s0] + (src)[s4]; \
01430     const int a1 = (src)[s0] - (src)[s4]; \
01431     const int a2 = (src)[s2] + (src)[s6]; \
01432     const int a3 = (A1*((src)[s2] - (src)[s6])) >> 11; \
01433     const int a4 = (src)[s5] + (src)[s3]; \
01434     const int a5 = (src)[s5] - (src)[s3]; \
01435     const int a6 = (src)[s1] + (src)[s7]; \
01436     const int a7 = (src)[s1] - (src)[s7]; \
01437     const int b0 = a4 + a6; \
01438     const int b1 = (A3*(a5 + a7)) >> 11; \
01439     const int b2 = ((A4*a5) >> 11) - b0 + b1; \
01440     const int b3 = (A1*(a6 - a4) >> 11) - b2; \
01441     const int b4 = ((A2*a7) >> 11) + b3 - b1; \
01442     (dest)[d0] = munge(a0+a2   +b0); \
01443     (dest)[d1] = munge(a1+a3-a2+b2); \
01444     (dest)[d2] = munge(a1-a3+a2+b3); \
01445     (dest)[d3] = munge(a0-a2   -b4); \
01446     (dest)[d4] = munge(a0-a2   +b4); \
01447     (dest)[d5] = munge(a1-a3+a2-b3); \
01448     (dest)[d6] = munge(a1+a3-a2-b2); \
01449     (dest)[d7] = munge(a0+a2   -b0); \
01450 }
01451 /* end IDCT_TRANSFORM macro */
01452 
01453 #define MUNGE_NONE(x) (x)
01454 #define IDCT_COL(dest,src) IDCT_TRANSFORM(dest,0,8,16,24,32,40,48,56,0,8,16,24,32,40,48,56,MUNGE_NONE,src)
01455 
01456 #define MUNGE_ROW(x) (((x) + 0x7F)>>8)
01457 #define IDCT_ROW(dest,src) IDCT_TRANSFORM(dest,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,MUNGE_ROW,src)
01458 
01459 static inline void IDCTCol(int16 *dest, const int16 *src) {
01460     if ((src[8] | src[16] | src[24] | src[32] | src[40] | src[48] | src[56]) == 0) {
01461         dest[ 0] =
01462         dest[ 8] =
01463         dest[16] =
01464         dest[24] =
01465         dest[32] =
01466         dest[40] =
01467         dest[48] =
01468         dest[56] = src[0];
01469     } else {
01470         IDCT_COL(dest, src);
01471     }
01472 }
01473 
01474 void BinkDecoder::BinkVideoTrack::IDCT(int16 *block) {
01475     int i;
01476     int16 temp[64];
01477 
01478     for (i = 0; i < 8; i++)
01479         IDCTCol(&temp[i], &block[i]);
01480     for (i = 0; i < 8; i++) {
01481         IDCT_ROW( (&block[8*i]), (&temp[8*i]) );
01482     }
01483 }
01484 
01485 void BinkDecoder::BinkVideoTrack::IDCTAdd(DecodeContext &ctx, int16 *block) {
01486     int i, j;
01487 
01488     IDCT(block);
01489     byte *dest = ctx.dest;
01490     for (i = 0; i < 8; i++, dest += ctx.pitch, block += 8)
01491         for (j = 0; j < 8; j++)
01492              dest[j] += block[j];
01493 }
01494 
01495 void BinkDecoder::BinkVideoTrack::IDCTPut(DecodeContext &ctx, int16 *block) {
01496     int i;
01497     int16 temp[64];
01498     for (i = 0; i < 8; i++)
01499         IDCTCol(&temp[i], &block[i]);
01500     for (i = 0; i < 8; i++) {
01501         IDCT_ROW( (&ctx.dest[i*ctx.pitch]), (&temp[8*i]) );
01502     }
01503 }
01504 
01505 BinkDecoder::BinkAudioTrack::BinkAudioTrack(BinkDecoder::AudioInfo &audio, Audio::Mixer::SoundType soundType) :
01506         AudioTrack(soundType),
01507         _audioInfo(&audio) {
01508     _audioStream = Audio::makeQueuingAudioStream(_audioInfo->outSampleRate, _audioInfo->outChannels == 2);
01509 }
01510 
01511 BinkDecoder::BinkAudioTrack::~BinkAudioTrack() {
01512     delete _audioStream;
01513 }
01514 
01515 Audio::AudioStream *BinkDecoder::BinkAudioTrack::getAudioStream() const {
01516     return _audioStream;
01517 }
01518 
01519 void BinkDecoder::BinkAudioTrack::decodePacket() {
01520     int outSize = _audioInfo->frameLen * _audioInfo->channels;
01521 
01522     while (_audioInfo->bits->pos() < _audioInfo->bits->size()) {
01523         int16 *out = (int16 *)malloc(outSize * 2);
01524         memset(out, 0, outSize * 2);
01525 
01526         audioBlock(out);
01527 
01528         byte flags = Audio::FLAG_16BITS;
01529         if (_audioInfo->outChannels == 2)
01530             flags |= Audio::FLAG_STEREO;
01531 
01532 #ifdef SCUMM_LITTLE_ENDIAN
01533         flags |= Audio::FLAG_LITTLE_ENDIAN;
01534 #endif
01535 
01536         _audioStream->queueBuffer((byte *)out, _audioInfo->blockSize * 2, DisposeAfterUse::YES, flags);
01537 
01538         if (_audioInfo->bits->pos() & 0x1F) // next data block starts at a 32-byte boundary
01539             _audioInfo->bits->skip(32 - (_audioInfo->bits->pos() & 0x1F));
01540     }
01541 }
01542 
01543 void BinkDecoder::BinkAudioTrack::audioBlock(int16 *out) {
01544     if      (_audioInfo->codec == kAudioCodecDCT)
01545         audioBlockDCT ();
01546     else if (_audioInfo->codec == kAudioCodecRDFT)
01547         audioBlockRDFT();
01548 
01549     floatToInt16Interleave(out, const_cast<const float **>(_audioInfo->coeffsPtr), _audioInfo->frameLen, _audioInfo->channels);
01550 
01551     if (!_audioInfo->first) {
01552         int count = _audioInfo->overlapLen * _audioInfo->channels;
01553         int shift = Common::intLog2(count);
01554         for (int i = 0; i < count; i++) {
01555             out[i] = (_audioInfo->prevCoeffs[i] * (count - i) + out[i] * i) >> shift;
01556         }
01557     }
01558 
01559     memcpy(_audioInfo->prevCoeffs, out + _audioInfo->blockSize, _audioInfo->overlapLen * _audioInfo->channels * sizeof(*out));
01560 
01561     _audioInfo->first = false;
01562 }
01563 
01564 void BinkDecoder::BinkAudioTrack::audioBlockDCT() {
01565     _audioInfo->bits->skip(2);
01566 
01567     for (uint8 i = 0; i < _audioInfo->channels; i++) {
01568         float *coeffs = _audioInfo->coeffsPtr[i];
01569 
01570         readAudioCoeffs(coeffs);
01571 
01572         coeffs[0] /= 0.5;
01573 
01574         _audioInfo->dct->calc(coeffs);
01575 
01576         for (uint32 j = 0; j < _audioInfo->frameLen; j++)
01577             coeffs[j] *= (_audioInfo->frameLen / 2.0);
01578     }
01579 
01580 }
01581 
01582 void BinkDecoder::BinkAudioTrack::audioBlockRDFT() {
01583     for (uint8 i = 0; i < _audioInfo->channels; i++) {
01584         float *coeffs = _audioInfo->coeffsPtr[i];
01585 
01586         readAudioCoeffs(coeffs);
01587 
01588         _audioInfo->rdft->calc(coeffs);
01589     }
01590 }
01591 
01592 static const uint8 rleLengthTab[16] = {
01593     2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 32, 64
01594 };
01595 
01596 void BinkDecoder::BinkAudioTrack::readAudioCoeffs(float *coeffs) {
01597     coeffs[0] = getFloat() * _audioInfo->root;
01598     coeffs[1] = getFloat() * _audioInfo->root;
01599 
01600     float quant[25];
01601 
01602     for (uint32 i = 0; i < _audioInfo->bandCount; i++) {
01603         int value = _audioInfo->bits->getBits(8);
01604 
01605         //                              0.066399999 / log10(M_E)
01606         quant[i] = exp(MIN(value, 95) * 0.15289164787221953823f) * _audioInfo->root;
01607     }
01608 
01609     float q = 0.0;
01610 
01611     // Find band (k)
01612     int k;
01613     for (k = 0; _audioInfo->bands[k] < 1; k++)
01614         q = quant[k];
01615 
01616     // Parse coefficients
01617     uint32 i = 2;
01618     while (i < _audioInfo->frameLen) {
01619 
01620         uint32 j = 0;
01621         if (_audioInfo->bits->getBit())
01622             j = i + rleLengthTab[_audioInfo->bits->getBits(4)] * 8;
01623         else
01624             j = i + 8;
01625 
01626         j = MIN(j, _audioInfo->frameLen);
01627 
01628         int width = _audioInfo->bits->getBits(4);
01629         if (width == 0) {
01630 
01631             memset(coeffs + i, 0, (j - i) * sizeof(*coeffs));
01632             i = j;
01633             while (_audioInfo->bands[k] * 2 < i)
01634                 q = quant[k++];
01635 
01636         } else {
01637 
01638             while (i < j) {
01639                 if (_audioInfo->bands[k] * 2 == i)
01640                     q = quant[k++];
01641 
01642                 int coeff = _audioInfo->bits->getBits(width);
01643                 if (coeff) {
01644 
01645                     if (_audioInfo->bits->getBit())
01646                         coeffs[i] = -q * coeff;
01647                     else
01648                         coeffs[i] =  q * coeff;
01649 
01650                 } else {
01651                     coeffs[i] = 0.0;
01652                 }
01653                 i++;
01654             }
01655 
01656         }
01657 
01658     }
01659 
01660 }
01661 
01662 static inline int floatToInt16One(float src) {
01663     return (int16)CLIP<int>((int)floor(src + 0.5), -32768, 32767);
01664 }
01665 
01666 void BinkDecoder::BinkAudioTrack::floatToInt16Interleave(int16 *dst, const float **src, uint32 length, uint8 channels) {
01667     if (channels == 2) {
01668         for (uint32 i = 0; i < length; i++) {
01669             dst[2 * i    ] = floatToInt16One(src[0][i]);
01670             dst[2 * i + 1] = floatToInt16One(src[1][i]);
01671         }
01672     } else {
01673         for(uint8 c = 0; c < channels; c++)
01674             for(uint32 i = 0, j = c; i < length; i++, j += channels)
01675                 dst[j] = floatToInt16One(src[c][i]);
01676     }
01677 }
01678 
01679 float BinkDecoder::BinkAudioTrack::getFloat() {
01680     int power = _audioInfo->bits->getBits(5);
01681 
01682     float f = ldexp((float)_audioInfo->bits->getBits(23), power - 23);
01683 
01684     if (_audioInfo->bits->getBit())
01685         f = -f;
01686 
01687     return f;
01688 }
01689 
01690 void BinkDecoder::initAudioTrack(AudioInfo &audio) {
01691     audio.sampleCount = 0;
01692     audio.bits        = 0;
01693 
01694     audio.channels = ((audio.flags & kAudioFlagStereo) != 0) ? 2 : 1;
01695     audio.codec    = ((audio.flags & kAudioFlagDCT   ) != 0) ? kAudioCodecDCT : kAudioCodecRDFT;
01696 
01697     if (audio.channels > kAudioChannelsMax)
01698         error("Too many audio channels: %d", audio.channels);
01699 
01700     uint32 frameLenBits;
01701     // Calculate frame length
01702     if     (audio.sampleRate < 22050)
01703         frameLenBits =  9;
01704     else if(audio.sampleRate < 44100)
01705         frameLenBits = 10;
01706     else
01707         frameLenBits = 11;
01708 
01709     audio.frameLen = 1 << frameLenBits;
01710 
01711     audio.outSampleRate = audio.sampleRate;
01712     audio.outChannels   = audio.channels;
01713 
01714     if (audio.codec  == kAudioCodecRDFT) {
01715         // RDFT audio already interleaves the samples correctly
01716 
01717         if (audio.channels == 2)
01718             frameLenBits++;
01719 
01720         audio.sampleRate *= audio.channels;
01721         audio.frameLen   *= audio.channels;
01722         audio.channels    = 1;
01723     }
01724 
01725     audio.overlapLen = audio.frameLen / 16;
01726     audio.blockSize  = (audio.frameLen - audio.overlapLen) * audio.channels;
01727     audio.root       = 2.0 / sqrt((double)audio.frameLen);
01728 
01729     uint32 sampleRateHalf = (audio.sampleRate + 1) / 2;
01730 
01731     // Calculate number of bands
01732     for (audio.bandCount = 1; audio.bandCount < 25; audio.bandCount++)
01733         if (sampleRateHalf <= binkCriticalFreqs[audio.bandCount - 1])
01734             break;
01735 
01736     audio.bands = new uint32[audio.bandCount + 1];
01737 
01738     // Populate bands
01739     audio.bands[0] = 1;
01740     for (uint32 i = 1; i < audio.bandCount; i++)
01741         audio.bands[i] = binkCriticalFreqs[i - 1] * (audio.frameLen / 2) / sampleRateHalf;
01742     audio.bands[audio.bandCount] = audio.frameLen / 2;
01743 
01744     audio.first = true;
01745 
01746     for (uint8 i = 0; i < audio.channels; i++)
01747         audio.coeffsPtr[i] = audio.coeffs + i * audio.frameLen;
01748 
01749     audio.codec = ((audio.flags & kAudioFlagDCT) != 0) ? kAudioCodecDCT : kAudioCodecRDFT;
01750 
01751     if      (audio.codec == kAudioCodecRDFT)
01752         audio.rdft = new Common::RDFT(frameLenBits, Common::RDFT::DFT_C2R);
01753     else if (audio.codec == kAudioCodecDCT)
01754         audio.dct  = new Common::DCT(frameLenBits, Common::DCT::DCT_III);
01755 
01756     addTrack(new BinkAudioTrack(audio, getSoundType()));
01757 }
01758 
01759 } // End of namespace Video


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