bitStream.cpp 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "core/stream/bitStream.h"
  24. #include "core/strings/stringFunctions.h"
  25. #include "math/mathIO.h"
  26. #include "console/consoleObject.h"
  27. #include "platform/platformNet.h"
  28. #include "core/bitVector.h"
  29. static BitStream gPacketStream(NULL, 0);
  30. static U8 gPacketBuffer[Net::MaxPacketDataSize];
  31. // bitstream utility functions
  32. void BitStream::clearStringBuffer()
  33. {
  34. static char stringBuf[256];
  35. stringBuf[0] = 0;
  36. // setStringBuffer( stringBuf );
  37. }
  38. void BitStream::setStringBuffer(char buffer[256])
  39. {
  40. // stringBuffer = buffer;
  41. }
  42. BitStream *BitStream::getPacketStream(U32 writeSize)
  43. {
  44. if(!writeSize)
  45. writeSize = Net::MaxPacketDataSize;
  46. gPacketStream.setBuffer(gPacketBuffer, writeSize, Net::MaxPacketDataSize);
  47. gPacketStream.setPosition(0);
  48. return &gPacketStream;
  49. }
  50. void BitStream::sendPacketStream(const NetAddress *addr)
  51. {
  52. Net::sendto(addr, gPacketStream.getBuffer(), gPacketStream.getPosition());
  53. }
  54. // CodeReview WTF is this additional IsEqual? - BJG, 3/29/07
  55. inline bool IsEqual(F32 a, F32 b) { return a == b; }
  56. ResizeBitStream::ResizeBitStream(U32 minSpace, U32 initialSize) : BitStream(NULL, 0, 0)
  57. {
  58. mMinSpace = minSpace;
  59. if(!initialSize)
  60. initialSize = minSpace * 2;
  61. U8 *buf = (U8 *) dMalloc(initialSize);
  62. setBuffer(buf, initialSize, initialSize);
  63. }
  64. ResizeBitStream::~ResizeBitStream()
  65. {
  66. dFree(dataPtr);
  67. }
  68. void ResizeBitStream::validate()
  69. {
  70. if(getPosition() + mMinSpace > bufSize)
  71. {
  72. bufSize = getPosition() + mMinSpace * 2;
  73. dataPtr = (U8 *) dRealloc(dataPtr, bufSize);
  74. maxReadBitNum = bufSize << 3;
  75. maxWriteBitNum = bufSize << 3;
  76. }
  77. }
  78. class HuffmanProcessor
  79. {
  80. static const U32 csm_charFreqs[256];
  81. bool m_tablesBuilt;
  82. void buildTables();
  83. struct HuffNode {
  84. U32 pop;
  85. S16 index0;
  86. S16 index1;
  87. };
  88. struct HuffLeaf {
  89. U32 pop;
  90. U8 numBits;
  91. U8 symbol;
  92. U32 code; // no code should be longer than 32 bits.
  93. };
  94. // We have to be a bit careful with these, mSince they are pointers...
  95. struct HuffWrap {
  96. HuffNode* pNode;
  97. HuffLeaf* pLeaf;
  98. public:
  99. HuffWrap() : pNode(NULL), pLeaf(NULL) { }
  100. void set(HuffLeaf* in_leaf) { pNode = NULL; pLeaf = in_leaf; }
  101. void set(HuffNode* in_node) { pLeaf = NULL; pNode = in_node; }
  102. U32 getPop() { if (pNode) return pNode->pop; else return pLeaf->pop; }
  103. };
  104. Vector<HuffNode> m_huffNodes;
  105. Vector<HuffLeaf> m_huffLeaves;
  106. S16 determineIndex(HuffWrap&);
  107. void generateCodes(BitStream&, S32, S32);
  108. public:
  109. HuffmanProcessor() : m_tablesBuilt(false) { }
  110. static HuffmanProcessor g_huffProcessor;
  111. bool readHuffBuffer(BitStream* pStream, char* out_pBuffer);
  112. bool writeHuffBuffer(BitStream* pStream, const char* out_pBuffer, S32 maxLen);
  113. };
  114. HuffmanProcessor HuffmanProcessor::g_huffProcessor;
  115. void BitStream::setBuffer(void *bufPtr, S32 size, S32 maxSize)
  116. {
  117. dataPtr = (U8 *) bufPtr;
  118. bitNum = 0;
  119. bufSize = size;
  120. maxReadBitNum = size << 3;
  121. if(maxSize < 0)
  122. maxSize = size;
  123. maxWriteBitNum = maxSize << 3;
  124. error = false;
  125. clearCompressionPoint();
  126. }
  127. U32 BitStream::getPosition() const
  128. {
  129. return (bitNum + 7) >> 3;
  130. }
  131. bool BitStream::setPosition(const U32 pos)
  132. {
  133. bitNum = pos << 3;
  134. return (true);
  135. }
  136. U32 BitStream::getStreamSize()
  137. {
  138. return bufSize;
  139. }
  140. U8 *BitStream::getBytePtr()
  141. {
  142. return dataPtr + getPosition();
  143. }
  144. U32 BitStream::getReadByteSize()
  145. {
  146. return (maxReadBitNum >> 3) - getPosition();
  147. }
  148. U32 BitStream::getWriteByteSize()
  149. {
  150. return (maxWriteBitNum >> 3) - getPosition();
  151. }
  152. void BitStream::clear()
  153. {
  154. dMemset(dataPtr, 0, bufSize);
  155. }
  156. void BitStream::writeClassId(U32 classId, U32 classType, U32 classGroup)
  157. {
  158. AssertFatal(classType < NetClassTypesCount, "Out of range class type.");
  159. AssertFatal(classGroup < NetClassGroupsCount, "Out of range class group.");
  160. AssertFatal(classId < AbstractClassRep::NetClassCount[classGroup][classType], "Out of range class id.");
  161. AssertFatal(AbstractClassRep::NetClassCount[classGroup][classType] < (1 << AbstractClassRep::NetClassBitSize[classGroup][classType]),
  162. "NetClassBitSize too small!");
  163. writeInt(classId, AbstractClassRep::NetClassBitSize[classGroup][classType]);
  164. }
  165. S32 BitStream::readClassId(U32 classType, U32 classGroup)
  166. {
  167. AssertFatal(classType < NetClassTypesCount, "Out of range class type.");
  168. AssertFatal(classGroup < NetClassGroupsCount, "Out of range class group.");
  169. AssertFatal(AbstractClassRep::NetClassCount[classGroup][classType] < (1 << AbstractClassRep::NetClassBitSize[classGroup][classType]),
  170. "NetClassBitSize too small!");
  171. S32 ret = readInt(AbstractClassRep::NetClassBitSize[classGroup][classType]);
  172. AssertFatal(ret < AbstractClassRep::NetClassCount[classGroup][classType], "BitStream::readClassId - unexpected class ID!");
  173. if(ret >= AbstractClassRep::NetClassCount[classGroup][classType])
  174. return -1;
  175. return ret;
  176. }
  177. void BitStream::writeBits(S32 bitCount, const void *bitPtr)
  178. {
  179. if(!bitCount)
  180. return;
  181. if(bitCount + bitNum > maxWriteBitNum)
  182. {
  183. error = true;
  184. AssertFatal(false, "Out of range write");
  185. return;
  186. }
  187. // [tom, 8/17/2006] This is probably a lot lamer then it needs to be. However,
  188. // at least it doesnt clobber data or overrun the buffer like the old code did.
  189. const U8 *ptr = (U8 *)bitPtr;
  190. for(S32 srcBitNum = 0;srcBitNum < bitCount;srcBitNum++)
  191. {
  192. if((*(ptr + (srcBitNum >> 3)) & (1 << (srcBitNum & 0x7))) != 0)
  193. *(dataPtr + (bitNum >> 3)) |= (1 << (bitNum & 0x7));
  194. else
  195. *(dataPtr + (bitNum >> 3)) &= ~(1 << (bitNum & 0x7));
  196. bitNum++;
  197. }
  198. }
  199. void BitStream::setBit(S32 bitCount, bool set)
  200. {
  201. if(set)
  202. *(dataPtr + (bitCount >> 3)) |= (1 << (bitCount & 0x7));
  203. else
  204. *(dataPtr + (bitCount >> 3)) &= ~(1 << (bitCount & 0x7));
  205. }
  206. bool BitStream::testBit(S32 bitCount)
  207. {
  208. return (*(dataPtr + (bitCount >> 3)) & (1 << (bitCount & 0x7))) != 0;
  209. }
  210. bool BitStream::writeFlag(bool val)
  211. {
  212. if(bitNum + 1 > maxWriteBitNum)
  213. {
  214. error = true;
  215. AssertFatal(false, "Out of range write");
  216. return false;
  217. }
  218. if(val)
  219. *(dataPtr + (bitNum >> 3)) |= (1 << (bitNum & 0x7));
  220. else
  221. *(dataPtr + (bitNum >> 3)) &= ~(1 << (bitNum & 0x7));
  222. bitNum++;
  223. return (val);
  224. }
  225. void BitStream::readBits(S32 bitCount, void *bitPtr)
  226. {
  227. if(!bitCount)
  228. return;
  229. if(bitCount + bitNum > maxReadBitNum)
  230. {
  231. error = true;
  232. //AssertFatal(false, "Out of range read");
  233. AssertWarn(false, "Out of range read");
  234. return;
  235. }
  236. U8 *stPtr = dataPtr + (bitNum >> 3);
  237. S32 byteCount = (bitCount + 7) >> 3;
  238. U8 *ptr = (U8 *) bitPtr;
  239. S32 downShift = bitNum & 0x7;
  240. S32 upShift = 8 - downShift;
  241. U8 curB = *stPtr;
  242. const U8 *stEnd = dataPtr + bufSize;
  243. while(byteCount--)
  244. {
  245. stPtr++;
  246. U8 nextB = stPtr < stEnd ? *stPtr : 0;
  247. *ptr++ = (curB >> downShift) | (nextB << upShift);
  248. curB = nextB;
  249. }
  250. bitNum += bitCount;
  251. }
  252. bool BitStream::_read(U32 size, void *dataPtr)
  253. {
  254. readBits(size << 3, dataPtr);
  255. return true;
  256. }
  257. bool BitStream::_write(U32 size, const void *dataPtr)
  258. {
  259. writeBits(size << 3, dataPtr);
  260. return true;
  261. }
  262. S32 BitStream::readInt(S32 bitCount)
  263. {
  264. S32 ret = 0;
  265. readBits(bitCount, &ret);
  266. ret = convertLEndianToHost(ret);
  267. if(bitCount == 32)
  268. return ret;
  269. else
  270. ret &= (1 << bitCount) - 1;
  271. return ret;
  272. }
  273. void BitStream::writeInt(S32 val, S32 bitCount)
  274. {
  275. val = convertHostToLEndian(val);
  276. writeBits(bitCount, &val);
  277. }
  278. void BitStream::writeFloat(F32 f, S32 bitCount)
  279. {
  280. writeInt((S32)(f * ((1 << bitCount) - 1)), bitCount);
  281. }
  282. F32 BitStream::readFloat(S32 bitCount)
  283. {
  284. return readInt(bitCount) / F32((1 << bitCount) - 1);
  285. }
  286. void BitStream::writeSignedFloat(F32 f, S32 bitCount)
  287. {
  288. writeInt((S32)(((f + 1) * .5) * ((1 << bitCount) - 1)), bitCount);
  289. }
  290. F32 BitStream::readSignedFloat(S32 bitCount)
  291. {
  292. return readInt(bitCount) * 2 / F32((1 << bitCount) - 1) - 1.0f;
  293. }
  294. void BitStream::writeSignedInt(S32 value, S32 bitCount)
  295. {
  296. if(writeFlag(value < 0))
  297. writeInt(-value, bitCount - 1);
  298. else
  299. writeInt(value, bitCount - 1);
  300. }
  301. S32 BitStream::readSignedInt(S32 bitCount)
  302. {
  303. if(readFlag())
  304. return -readInt(bitCount - 1);
  305. else
  306. return readInt(bitCount - 1);
  307. }
  308. void BitStream::writeNormalVector(const Point3F& vec, S32 bitCount)
  309. {
  310. F32 phi = mAtan2(vec.x, vec.y) / M_PI;
  311. F32 theta = mAtan2(vec.z, mSqrt(vec.x*vec.x + vec.y*vec.y)) / (M_PI/2.0);
  312. writeSignedFloat(phi, bitCount+1);
  313. writeSignedFloat(theta, bitCount);
  314. }
  315. void BitStream::readNormalVector(Point3F *vec, S32 bitCount)
  316. {
  317. F32 phi = readSignedFloat(bitCount+1) * M_PI;
  318. F32 theta = readSignedFloat(bitCount) * (M_PI/2.0);
  319. vec->x = mSin(phi)*mCos(theta);
  320. vec->y = mCos(phi)*mCos(theta);
  321. vec->z = mSin(theta);
  322. }
  323. Point3F BitStream::dumbDownNormal(const Point3F& vec, S32 bitCount)
  324. {
  325. U8 buffer[128];
  326. BitStream temp(buffer, 128);
  327. temp.writeNormalVector(vec, bitCount);
  328. temp.setCurPos(0);
  329. Point3F ret;
  330. temp.readNormalVector(&ret, bitCount);
  331. return ret;
  332. }
  333. void BitStream::writeVector( Point3F vec, F32 maxMag, S32 magBits, S32 normalBits )
  334. {
  335. F32 mag = vec.len();
  336. // If its zero length then we're done.
  337. if ( !writeFlag( mag > 0.0f ) )
  338. return;
  339. // Write the magnitude compressed unless its greater than the maximum.
  340. if ( writeFlag( mag < maxMag ) )
  341. writeFloat( mag / maxMag, magBits );
  342. else
  343. write( mag );
  344. // Finally write the normal part.
  345. vec *= 1.0f / mag;
  346. writeNormalVector( vec, normalBits );
  347. }
  348. void BitStream::readVector( Point3F *outVec, F32 maxMag, S32 magBits, S32 normalBits )
  349. {
  350. // Nothing more to do if we got a zero length vector.
  351. if ( !readFlag() )
  352. {
  353. outVec->set(0,0,0);
  354. return;
  355. }
  356. // Read the compressed or uncompressed magnitude.
  357. F32 mag;
  358. if ( readFlag() )
  359. mag = readFloat( magBits ) * maxMag;
  360. else
  361. read( &mag );
  362. // Finally read the normal and reconstruct the vector.
  363. readNormalVector( outVec, normalBits );
  364. *outVec *= mag;
  365. }
  366. void BitStream::writeAffineTransform(const MatrixF& matrix)
  367. {
  368. // AssertFatal(matrix.isAffine() == true,
  369. // "BitStream::writeAffineTransform: Error, must write only affine transforms!");
  370. Point3F pos;
  371. matrix.getColumn(3, &pos);
  372. mathWrite(*this, pos);
  373. QuatF q(matrix);
  374. q.normalize();
  375. write(q.x);
  376. write(q.y);
  377. write(q.z);
  378. writeFlag(q.w < 0.0);
  379. }
  380. void BitStream::readAffineTransform(MatrixF* matrix)
  381. {
  382. Point3F pos;
  383. QuatF q;
  384. mathRead(*this, &pos);
  385. read(&q.x);
  386. read(&q.y);
  387. read(&q.z);
  388. q.w = mSqrt(1.0 - getMin(F32(((q.x * q.x) + (q.y * q.y) + (q.z * q.z))), 1.f));
  389. if (readFlag())
  390. q.w = -q.w;
  391. q.setMatrix(matrix);
  392. matrix->setColumn(3, pos);
  393. // AssertFatal(matrix->isAffine() == true,
  394. // "BitStream::readAffineTransform: Error, transform should be affine after this function!");
  395. }
  396. void BitStream::writeQuat( const QuatF& quat, U32 bitCount )
  397. {
  398. writeSignedFloat( quat.x, bitCount );
  399. writeSignedFloat( quat.y, bitCount );
  400. writeSignedFloat( quat.z, bitCount );
  401. writeFlag( quat.w < 0.0f );
  402. }
  403. void BitStream::readQuat( QuatF *outQuat, U32 bitCount )
  404. {
  405. outQuat->x = readSignedFloat( bitCount );
  406. outQuat->y = readSignedFloat( bitCount );
  407. outQuat->z = readSignedFloat( bitCount );
  408. outQuat->w = mSqrt( 1.0 - getMin( mSquared( outQuat->x ) +
  409. mSquared( outQuat->y ) +
  410. mSquared( outQuat->z ),
  411. 1.0f ) );
  412. if ( readFlag() )
  413. outQuat->w = -outQuat->w;
  414. }
  415. void BitStream::writeBits( const BitVector &bitvec )
  416. {
  417. U32 size = bitvec.getSize();
  418. if ( writeFlag( size <= 127 ) )
  419. writeInt( size, 7 );
  420. else
  421. write( size );
  422. writeBits( bitvec.getSize(), bitvec.getBits() );
  423. }
  424. void BitStream::readBits( BitVector *bitvec )
  425. {
  426. U32 size;
  427. if ( readFlag() ) // size <= 127
  428. size = readInt( 7 );
  429. else
  430. read( &size );
  431. bitvec->setSize( size );
  432. readBits( size, bitvec->getBits() );
  433. }
  434. //----------------------------------------------------------------------------
  435. void BitStream::clearCompressionPoint()
  436. {
  437. mCompressPoint.set(0,0,0);
  438. }
  439. void BitStream::setCompressionPoint(const Point3F& p)
  440. {
  441. mCompressPoint = p;
  442. }
  443. static U32 gBitCounts[4] = {
  444. 16, 18, 20, 32
  445. };
  446. void BitStream::writeCompressedPoint(const Point3F& p,F32 scale)
  447. {
  448. // Same # of bits for all axis
  449. Point3F vec;
  450. F32 invScale = 1 / scale;
  451. U32 type;
  452. vec = p - mCompressPoint;
  453. F32 dist = vec.len() * invScale;
  454. if(dist < (1 << 15))
  455. type = 0;
  456. else if(dist < (1 << 17))
  457. type = 1;
  458. else if(dist < (1 << 19))
  459. type = 2;
  460. else
  461. type = 3;
  462. writeInt(type, 2);
  463. if (type != 3)
  464. {
  465. type = gBitCounts[type];
  466. writeSignedInt(S32(vec.x * invScale + 0.5f),type);
  467. writeSignedInt(S32(vec.y * invScale + 0.5f),type);
  468. writeSignedInt(S32(vec.z * invScale + 0.5f),type);
  469. }
  470. else
  471. {
  472. write(p.x);
  473. write(p.y);
  474. write(p.z);
  475. }
  476. }
  477. void BitStream::readCompressedPoint(Point3F* p,F32 scale)
  478. {
  479. // Same # of bits for all axis
  480. U32 type = readInt(2);
  481. if(type == 3)
  482. {
  483. read(&p->x);
  484. read(&p->y);
  485. read(&p->z);
  486. }
  487. else
  488. {
  489. type = gBitCounts[type];
  490. p->x = (F32)readSignedInt(type);
  491. p->y = (F32)readSignedInt(type);
  492. p->z = (F32)readSignedInt(type);
  493. p->x = mCompressPoint.x + p->x * scale;
  494. p->y = mCompressPoint.y + p->y * scale;
  495. p->z = mCompressPoint.z + p->z * scale;
  496. }
  497. }
  498. //------------------------------------------------------------------------------
  499. InfiniteBitStream::InfiniteBitStream()
  500. {
  501. //
  502. }
  503. InfiniteBitStream::~InfiniteBitStream()
  504. {
  505. //
  506. }
  507. void InfiniteBitStream::reset()
  508. {
  509. // Rewing back to beginning
  510. setPosition(0);
  511. }
  512. void InfiniteBitStream::validate(U32 upcomingBytes)
  513. {
  514. if(getPosition() + upcomingBytes + mMinSpace > bufSize)
  515. {
  516. bufSize = getPosition() + upcomingBytes + mMinSpace;
  517. dataPtr = (U8 *) dRealloc(dataPtr, bufSize);
  518. maxReadBitNum = bufSize << 3;
  519. maxWriteBitNum = bufSize << 3;
  520. }
  521. }
  522. void InfiniteBitStream::compact()
  523. {
  524. // Prepare to copy...
  525. U32 oldSize = bufSize;
  526. U8 *tmp = (U8*)dMalloc(bufSize);
  527. // Copy things...
  528. bufSize = getPosition() + mMinSpace * 2;
  529. dMemcpy(tmp, dataPtr, oldSize);
  530. // And clean up.
  531. dFree(dataPtr);
  532. dataPtr = tmp;
  533. maxReadBitNum = bufSize << 3;
  534. maxWriteBitNum = bufSize << 3;
  535. }
  536. void InfiniteBitStream::writeToStream(Stream &s)
  537. {
  538. s.write(getPosition(), dataPtr);
  539. }
  540. //------------------------------------------------------------------------------
  541. void BitStream::readString(char buf[256])
  542. {
  543. if(stringBuffer)
  544. {
  545. if(readFlag())
  546. {
  547. S32 offset = readInt(8);
  548. HuffmanProcessor::g_huffProcessor.readHuffBuffer(this, stringBuffer + offset);
  549. dStrcpy(buf, stringBuffer);
  550. return;
  551. }
  552. }
  553. HuffmanProcessor::g_huffProcessor.readHuffBuffer(this, buf);
  554. if(stringBuffer)
  555. dStrcpy(stringBuffer, buf);
  556. }
  557. void BitStream::writeString(const char *string, S32 maxLen)
  558. {
  559. if(!string)
  560. string = "";
  561. if(stringBuffer)
  562. {
  563. S32 j;
  564. for(j = 0; j < maxLen && stringBuffer[j] == string[j] && string[j];j++)
  565. ;
  566. dStrncpy(stringBuffer, string, maxLen);
  567. stringBuffer[maxLen] = 0;
  568. if(writeFlag(j > 2))
  569. {
  570. writeInt(j, 8);
  571. HuffmanProcessor::g_huffProcessor.writeHuffBuffer(this, string + j, maxLen - j);
  572. return;
  573. }
  574. }
  575. HuffmanProcessor::g_huffProcessor.writeHuffBuffer(this, string, maxLen);
  576. }
  577. void HuffmanProcessor::buildTables()
  578. {
  579. AssertFatal(m_tablesBuilt == false, "Cannot build tables twice!");
  580. m_tablesBuilt = true;
  581. S32 i;
  582. // First, construct the array of wraps...
  583. //
  584. m_huffLeaves.setSize(256);
  585. m_huffNodes.reserve(256);
  586. m_huffNodes.increment();
  587. for (i = 0; i < 256; i++) {
  588. HuffLeaf& rLeaf = m_huffLeaves[i];
  589. rLeaf.pop = csm_charFreqs[i] + 1;
  590. rLeaf.symbol = U8(i);
  591. dMemset(&rLeaf.code, 0, sizeof(rLeaf.code));
  592. rLeaf.numBits = 0;
  593. }
  594. S32 currWraps = 256;
  595. HuffWrap* pWrap = new HuffWrap[256];
  596. for (i = 0; i < 256; i++) {
  597. pWrap[i].set(&m_huffLeaves[i]);
  598. }
  599. while (currWraps != 1) {
  600. U32 min1 = 0xfffffffe, min2 = 0xffffffff;
  601. S32 index1 = -1, index2 = -1;
  602. for (i = 0; i < currWraps; i++) {
  603. if (pWrap[i].getPop() < min1) {
  604. min2 = min1;
  605. index2 = index1;
  606. min1 = pWrap[i].getPop();
  607. index1 = i;
  608. } else if (pWrap[i].getPop() < min2) {
  609. min2 = pWrap[i].getPop();
  610. index2 = i;
  611. }
  612. }
  613. AssertFatal(index1 != -1 && index2 != -1 && index1 != index2, "hrph");
  614. // Create a node for this...
  615. m_huffNodes.increment();
  616. HuffNode& rNode = m_huffNodes.last();
  617. rNode.pop = pWrap[index1].getPop() + pWrap[index2].getPop();
  618. rNode.index0 = determineIndex(pWrap[index1]);
  619. rNode.index1 = determineIndex(pWrap[index2]);
  620. S32 mergeIndex = index1 > index2 ? index2 : index1;
  621. S32 nukeIndex = index1 > index2 ? index1 : index2;
  622. pWrap[mergeIndex].set(&rNode);
  623. if (index2 != (currWraps - 1)) {
  624. pWrap[nukeIndex] = pWrap[currWraps - 1];
  625. }
  626. currWraps--;
  627. }
  628. AssertFatal(currWraps == 1, "wrong wraps?");
  629. AssertFatal(pWrap[0].pNode != NULL && pWrap[0].pLeaf == NULL, "Wrong wrap type!");
  630. // Ok, now we have one wrap, which is a node. we need to make sure that this
  631. // is the first node in the node list.
  632. m_huffNodes[0] = *(pWrap[0].pNode);
  633. delete [] pWrap;
  634. U32 code = 0;
  635. BitStream bs(&code, 4);
  636. generateCodes(bs, 0, 0);
  637. }
  638. void HuffmanProcessor::generateCodes(BitStream& rBS, S32 index, S32 depth)
  639. {
  640. if (index < 0) {
  641. // leaf node, copy the code in, and back out...
  642. HuffLeaf& rLeaf = m_huffLeaves[-(index + 1)];
  643. dMemcpy(&rLeaf.code, rBS.dataPtr, sizeof(rLeaf.code));
  644. rLeaf.numBits = depth;
  645. } else {
  646. HuffNode& rNode = m_huffNodes[index];
  647. S32 pos = rBS.getCurPos();
  648. rBS.writeFlag(false);
  649. generateCodes(rBS, rNode.index0, depth + 1);
  650. rBS.setCurPos(pos);
  651. rBS.writeFlag(true);
  652. generateCodes(rBS, rNode.index1, depth + 1);
  653. rBS.setCurPos(pos);
  654. }
  655. }
  656. S16 HuffmanProcessor::determineIndex(HuffWrap& rWrap)
  657. {
  658. if (rWrap.pLeaf != NULL) {
  659. AssertFatal(rWrap.pNode == NULL, "Got a non-NULL pNode in a HuffWrap with a non-NULL leaf.");
  660. return -((rWrap.pLeaf - m_huffLeaves.address()) + 1);
  661. } else {
  662. AssertFatal(rWrap.pNode != NULL, "Got a NULL pNode in a HuffWrap with a NULL leaf.");
  663. return rWrap.pNode - m_huffNodes.address();
  664. }
  665. }
  666. bool HuffmanProcessor::readHuffBuffer(BitStream* pStream, char* out_pBuffer)
  667. {
  668. if (m_tablesBuilt == false)
  669. buildTables();
  670. if (pStream->readFlag()) {
  671. S32 len = pStream->readInt(8);
  672. for (S32 i = 0; i < len; i++) {
  673. S32 index = 0;
  674. while (true) {
  675. if (index >= 0) {
  676. if (pStream->readFlag() == true) {
  677. index = m_huffNodes[index].index1;
  678. } else {
  679. index = m_huffNodes[index].index0;
  680. }
  681. } else {
  682. out_pBuffer[i] = m_huffLeaves[-(index+1)].symbol;
  683. break;
  684. }
  685. }
  686. }
  687. out_pBuffer[len] = '\0';
  688. return true;
  689. } else {
  690. // Uncompressed string...
  691. U32 len = pStream->readInt(8);
  692. pStream->read(len, out_pBuffer);
  693. out_pBuffer[len] = '\0';
  694. return true;
  695. }
  696. }
  697. bool HuffmanProcessor::writeHuffBuffer(BitStream* pStream, const char* out_pBuffer, S32 maxLen)
  698. {
  699. if (out_pBuffer == NULL) {
  700. pStream->writeFlag(false);
  701. pStream->writeInt(0, 8);
  702. return true;
  703. }
  704. if (m_tablesBuilt == false)
  705. buildTables();
  706. S32 len = out_pBuffer ? dStrlen(out_pBuffer) : 0;
  707. AssertWarn(len <= 255, "String TOO long for writeString");
  708. AssertWarn(len <= 255, out_pBuffer);
  709. if (len > maxLen)
  710. len = maxLen;
  711. S32 numBits = 0;
  712. S32 i;
  713. for (i = 0; i < len; i++)
  714. numBits += m_huffLeaves[(unsigned char)out_pBuffer[i]].numBits;
  715. if (numBits >= (len * 8)) {
  716. pStream->writeFlag(false);
  717. pStream->writeInt(len, 8);
  718. pStream->write(len, out_pBuffer);
  719. } else {
  720. pStream->writeFlag(true);
  721. pStream->writeInt(len, 8);
  722. for (i = 0; i < len; i++) {
  723. HuffLeaf& rLeaf = m_huffLeaves[((unsigned char)out_pBuffer[i])];
  724. pStream->writeBits(rLeaf.numBits, &rLeaf.code);
  725. }
  726. }
  727. return true;
  728. }
  729. const U32 HuffmanProcessor::csm_charFreqs[256] = {
  730. 0 ,
  731. 0 ,
  732. 0 ,
  733. 0 ,
  734. 0 ,
  735. 0 ,
  736. 0 ,
  737. 0 ,
  738. 0 ,
  739. 329 ,
  740. 21 ,
  741. 0 ,
  742. 0 ,
  743. 0 ,
  744. 0 ,
  745. 0 ,
  746. 0 ,
  747. 0 ,
  748. 0 ,
  749. 0 ,
  750. 0 ,
  751. 0 ,
  752. 0 ,
  753. 0 ,
  754. 0 ,
  755. 0 ,
  756. 0 ,
  757. 0 ,
  758. 0 ,
  759. 0 ,
  760. 0 ,
  761. 0 ,
  762. 2809 ,
  763. 68 ,
  764. 0 ,
  765. 27 ,
  766. 0 ,
  767. 58 ,
  768. 3 ,
  769. 62 ,
  770. 4 ,
  771. 7 ,
  772. 0 ,
  773. 0 ,
  774. 15 ,
  775. 65 ,
  776. 554 ,
  777. 3 ,
  778. 394 ,
  779. 404 ,
  780. 189 ,
  781. 117 ,
  782. 30 ,
  783. 51 ,
  784. 27 ,
  785. 15 ,
  786. 34 ,
  787. 32 ,
  788. 80 ,
  789. 1 ,
  790. 142 ,
  791. 3 ,
  792. 142 ,
  793. 39 ,
  794. 0 ,
  795. 144 ,
  796. 125 ,
  797. 44 ,
  798. 122 ,
  799. 275 ,
  800. 70 ,
  801. 135 ,
  802. 61 ,
  803. 127 ,
  804. 8 ,
  805. 12 ,
  806. 113 ,
  807. 246 ,
  808. 122 ,
  809. 36 ,
  810. 185 ,
  811. 1 ,
  812. 149 ,
  813. 309 ,
  814. 335 ,
  815. 12 ,
  816. 11 ,
  817. 14 ,
  818. 54 ,
  819. 151 ,
  820. 0 ,
  821. 0 ,
  822. 2 ,
  823. 0 ,
  824. 0 ,
  825. 211 ,
  826. 0 ,
  827. 2090 ,
  828. 344 ,
  829. 736 ,
  830. 993 ,
  831. 2872 ,
  832. 701 ,
  833. 605 ,
  834. 646 ,
  835. 1552 ,
  836. 328 ,
  837. 305 ,
  838. 1240 ,
  839. 735 ,
  840. 1533 ,
  841. 1713 ,
  842. 562 ,
  843. 3 ,
  844. 1775 ,
  845. 1149 ,
  846. 1469 ,
  847. 979 ,
  848. 407 ,
  849. 553 ,
  850. 59 ,
  851. 279 ,
  852. 31 ,
  853. 0 ,
  854. 0 ,
  855. 0 ,
  856. 68 ,
  857. 0 ,
  858. 0 ,
  859. 0 ,
  860. 0 ,
  861. 0 ,
  862. 0 ,
  863. 0 ,
  864. 0 ,
  865. 0 ,
  866. 0 ,
  867. 0 ,
  868. 0 ,
  869. 0 ,
  870. 0 ,
  871. 0 ,
  872. 0 ,
  873. 0 ,
  874. 0 ,
  875. 0 ,
  876. 0 ,
  877. 0 ,
  878. 0 ,
  879. 0 ,
  880. 0 ,
  881. 0 ,
  882. 0 ,
  883. 0 ,
  884. 0 ,
  885. 0 ,
  886. 0 ,
  887. 0 ,
  888. 0 ,
  889. 0 ,
  890. 0 ,
  891. 0 ,
  892. 0 ,
  893. 0 ,
  894. 0 ,
  895. 0 ,
  896. 0 ,
  897. 0 ,
  898. 0 ,
  899. 0 ,
  900. 0 ,
  901. 0 ,
  902. 0 ,
  903. 0 ,
  904. 0 ,
  905. 0 ,
  906. 0 ,
  907. 0 ,
  908. 0 ,
  909. 0 ,
  910. 0 ,
  911. 0 ,
  912. 0 ,
  913. 0 ,
  914. 0 ,
  915. 0 ,
  916. 0 ,
  917. 0 ,
  918. 0 ,
  919. 0 ,
  920. 0 ,
  921. 0 ,
  922. 0 ,
  923. 0 ,
  924. 0 ,
  925. 0 ,
  926. 0 ,
  927. 0 ,
  928. 0 ,
  929. 0 ,
  930. 0 ,
  931. 0 ,
  932. 0 ,
  933. 0 ,
  934. 0 ,
  935. 0 ,
  936. 0 ,
  937. 0 ,
  938. 0 ,
  939. 0 ,
  940. 0 ,
  941. 0 ,
  942. 0 ,
  943. 0 ,
  944. 0 ,
  945. 0 ,
  946. 0 ,
  947. 0 ,
  948. 0 ,
  949. 0 ,
  950. 0 ,
  951. 0 ,
  952. 0 ,
  953. 0 ,
  954. 0 ,
  955. 0 ,
  956. 0 ,
  957. 0 ,
  958. 0 ,
  959. 0 ,
  960. 0 ,
  961. 0 ,
  962. 0 ,
  963. 0 ,
  964. 0 ,
  965. 0 ,
  966. 0 ,
  967. 0 ,
  968. 0 ,
  969. 0 ,
  970. 0 ,
  971. 0 ,
  972. 0 ,
  973. 0 ,
  974. 0 ,
  975. 0 ,
  976. 0 ,
  977. 0 ,
  978. 0 ,
  979. 0 ,
  980. 0 ,
  981. 0 ,
  982. 0 ,
  983. 0 ,
  984. 0 ,
  985. 0
  986. };