DOOM-3-BFG

DOOM 3 BFG Edition
Log | Files | Refs

Compressor.cpp (56518B)


      1 /*
      2 ===========================================================================
      3 
      4 Doom 3 BFG Edition GPL Source Code
      5 Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company. 
      6 
      7 This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").  
      8 
      9 Doom 3 BFG Edition Source Code is free software: you can redistribute it and/or modify
     10 it under the terms of the GNU General Public License as published by
     11 the Free Software Foundation, either version 3 of the License, or
     12 (at your option) any later version.
     13 
     14 Doom 3 BFG Edition Source Code is distributed in the hope that it will be useful,
     15 but WITHOUT ANY WARRANTY; without even the implied warranty of
     16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     17 GNU General Public License for more details.
     18 
     19 You should have received a copy of the GNU General Public License
     20 along with Doom 3 BFG Edition Source Code.  If not, see <http://www.gnu.org/licenses/>.
     21 
     22 In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code.  If not, please request a copy in writing from id Software at the address below.
     23 
     24 If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
     25 
     26 ===========================================================================
     27 */
     28 #include "../idlib/precompiled.h"
     29 #pragma hdrstop
     30 
     31 
     32 /*
     33 =================================================================================
     34 
     35 	idCompressor_None
     36 
     37 =================================================================================
     38 */
     39 
     40 class idCompressor_None : public idCompressor {
     41 public:
     42 					idCompressor_None();
     43 
     44 	void			Init( idFile *f, bool compress, int wordLength );
     45 	void			FinishCompress();
     46 	float			GetCompressionRatio() const;
     47 
     48 	const char *	GetName();
     49 	const char *	GetFullPath();
     50 	int				Read( void *outData, int outLength );
     51 	int				Write( const void *inData, int inLength );
     52 	int				Length();
     53 	ID_TIME_T			Timestamp();
     54 	int				Tell();
     55 	void			ForceFlush();
     56 	void			Flush();
     57 	int				Seek( long offset, fsOrigin_t origin );
     58 
     59 protected:
     60 	idFile *		file;
     61 	bool			compress;
     62 };
     63 
     64 /*
     65 ================
     66 idCompressor_None::idCompressor_None
     67 ================
     68 */
     69 idCompressor_None::idCompressor_None() {
     70 	file = NULL;
     71 	compress = true;
     72 }
     73 
     74 /*
     75 ================
     76 idCompressor_None::Init
     77 ================
     78 */
     79 void idCompressor_None::Init( idFile *f, bool compress, int wordLength ) {
     80 	this->file = f;
     81 	this->compress = compress;
     82 }
     83 
     84 /*
     85 ================
     86 idCompressor_None::FinishCompress
     87 ================
     88 */
     89 void idCompressor_None::FinishCompress() {
     90 }
     91 
     92 /*
     93 ================
     94 idCompressor_None::GetCompressionRatio
     95 ================
     96 */
     97 float idCompressor_None::GetCompressionRatio() const {
     98 	return 0.0f;
     99 }
    100 
    101 /*
    102 ================
    103 idCompressor_None::GetName
    104 ================
    105 */
    106 const char *idCompressor_None::GetName() {
    107 	if ( file ) {
    108 		return file->GetName();
    109 	} else {
    110 		return "";
    111 	}
    112 }
    113 
    114 /*
    115 ================
    116 idCompressor_None::GetFullPath
    117 ================
    118 */
    119 const char *idCompressor_None::GetFullPath() {
    120 	if ( file ) {
    121 		return file->GetFullPath();
    122 	} else {
    123 		return "";
    124 	}
    125 }
    126 
    127 /*
    128 ================
    129 idCompressor_None::Write
    130 ================
    131 */
    132 int idCompressor_None::Write( const void *inData, int inLength ) {
    133 	if ( compress == false || inLength <= 0 ) {
    134 		return 0;
    135 	}
    136 	return file->Write( inData, inLength );
    137 }
    138 
    139 /*
    140 ================
    141 idCompressor_None::Read
    142 ================
    143 */
    144 int idCompressor_None::Read( void *outData, int outLength ) {
    145 	if ( compress == true || outLength <= 0 ) {
    146 		return 0;
    147 	}
    148 	return file->Read( outData, outLength );
    149 }
    150 
    151 /*
    152 ================
    153 idCompressor_None::Length
    154 ================
    155 */
    156 int idCompressor_None::Length() {
    157 	if ( file ) {
    158 		return file->Length();
    159 	} else {
    160 		return 0;
    161 	}
    162 }
    163 
    164 /*
    165 ================
    166 idCompressor_None::Timestamp
    167 ================
    168 */
    169 ID_TIME_T idCompressor_None::Timestamp() {
    170 	if ( file ) {
    171 		return file->Timestamp();
    172 	} else {
    173 		return 0;
    174 	}
    175 }
    176 
    177 /*
    178 ================
    179 idCompressor_None::Tell
    180 ================
    181 */
    182 int idCompressor_None::Tell() {
    183 	if ( file ) {
    184 		return file->Tell();
    185 	} else {
    186 		return 0;
    187 	}
    188 }
    189 
    190 /*
    191 ================
    192 idCompressor_None::ForceFlush
    193 ================
    194 */
    195 void idCompressor_None::ForceFlush() {
    196 	if ( file ) {
    197 		file->ForceFlush();
    198 	}
    199 }
    200 
    201 /*
    202 ================
    203 idCompressor_None::Flush
    204 ================
    205 */
    206 void idCompressor_None::Flush() {
    207 	if ( file ) {
    208 		file->ForceFlush();
    209 	}
    210 }
    211 
    212 /*
    213 ================
    214 idCompressor_None::Seek
    215 ================
    216 */
    217 int idCompressor_None::Seek( long offset, fsOrigin_t origin ) {
    218 	common->Error( "cannot seek on idCompressor" );
    219 	return -1;
    220 }
    221 
    222 
    223 /*
    224 =================================================================================
    225 
    226 	idCompressor_BitStream
    227 
    228 	Base class for bit stream compression.
    229 
    230 =================================================================================
    231 */
    232 
    233 class idCompressor_BitStream : public idCompressor_None {
    234 public:
    235 					idCompressor_BitStream() {}
    236 
    237 	void			Init( idFile *f, bool compress, int wordLength );
    238 	void			FinishCompress();
    239 	float			GetCompressionRatio() const;
    240 
    241 	int				Write( const void *inData, int inLength );
    242 	int				Read( void *outData, int outLength );
    243 
    244 protected:
    245 	byte			buffer[65536];
    246 	int				wordLength;
    247 
    248 	int				readTotalBytes;
    249 	int				readLength;
    250 	int				readByte;
    251 	int				readBit;
    252 	const byte *	readData;
    253 
    254 	int				writeTotalBytes;
    255 	int				writeLength;
    256 	int				writeByte;
    257 	int				writeBit;
    258 	byte *			writeData;
    259 
    260 protected:
    261 	void			InitCompress( const void *inData, const int inLength );
    262 	void			InitDecompress( void *outData, int outLength );
    263 	void			WriteBits( int value, int numBits );
    264 	int				ReadBits( int numBits );
    265 	void			UnreadBits( int numBits );
    266 	int				Compare( const byte *src1, int bitPtr1, const byte *src2, int bitPtr2, int maxBits ) const;
    267 };
    268 
    269 /*
    270 ================
    271 idCompressor_BitStream::Init
    272 ================
    273 */
    274 void idCompressor_BitStream::Init( idFile *f, bool compress, int wordLength ) {
    275 
    276 	assert( wordLength >= 1 && wordLength <= 32 );
    277 
    278 	this->file = f;
    279 	this->compress = compress;
    280 	this->wordLength = wordLength;
    281 
    282 	readTotalBytes = 0;
    283 	readLength = 0;
    284 	readByte = 0;
    285 	readBit = 0;
    286 	readData = NULL;
    287 
    288 	writeTotalBytes = 0;
    289 	writeLength = 0;
    290 	writeByte = 0;
    291 	writeBit = 0;
    292 	writeData = NULL;
    293 }
    294 
    295 /*
    296 ================
    297 idCompressor_BitStream::InitCompress
    298 ================
    299 */
    300 ID_INLINE void idCompressor_BitStream::InitCompress( const void *inData, const int inLength ) {
    301 
    302 	readLength = inLength;
    303 	readByte = 0;
    304 	readBit = 0;
    305 	readData = (const byte *) inData;
    306 
    307 	if ( !writeLength ) {
    308 		writeLength = sizeof( buffer );
    309 		writeByte = 0;
    310 		writeBit = 0;
    311 		writeData = buffer;
    312 	}
    313 }
    314 
    315 /*
    316 ================
    317 idCompressor_BitStream::InitDecompress
    318 ================
    319 */
    320 ID_INLINE void idCompressor_BitStream::InitDecompress( void *outData, int outLength ) {
    321 
    322 	if ( !readLength ) {
    323 		readLength = file->Read( buffer, sizeof( buffer ) );
    324 		readByte = 0;
    325 		readBit = 0;
    326 		readData = buffer;
    327 	}
    328 
    329 	writeLength = outLength;
    330 	writeByte = 0;
    331 	writeBit = 0;
    332 	writeData = (byte *) outData;
    333 }
    334 
    335 /*
    336 ================
    337 idCompressor_BitStream::WriteBits
    338 ================
    339 */
    340 void idCompressor_BitStream::WriteBits( int value, int numBits ) {
    341 	int put, fraction;
    342 
    343 	// Short circuit for writing single bytes at a time
    344 	if ( writeBit == 0 && numBits == 8 && writeByte < writeLength ) {
    345 		writeByte++;
    346 		writeTotalBytes++;
    347 		writeData[writeByte - 1] = value;
    348 		return;
    349 	}
    350 
    351 
    352 	while( numBits ) {
    353 		if ( writeBit == 0 ) {
    354 			if ( writeByte >= writeLength ) {
    355 				if ( writeData == buffer ) {
    356 					file->Write( buffer, writeByte );
    357 					writeByte = 0;
    358 				} else {
    359 					put = numBits;
    360 					writeBit = put & 7;
    361 					writeByte += ( put >> 3 ) + ( writeBit != 0 );
    362 					writeTotalBytes += ( put >> 3 ) + ( writeBit != 0 );
    363 					return;
    364 				}
    365 			}
    366 			writeData[writeByte] = 0;
    367 			writeByte++;
    368 			writeTotalBytes++;
    369 		}
    370 		put = 8 - writeBit;
    371 		if ( put > numBits ) {
    372 			put = numBits;
    373 		}
    374 		fraction = value & ( ( 1 << put ) - 1 );
    375 		writeData[writeByte - 1] |= fraction << writeBit;
    376 		numBits -= put;
    377 		value >>= put;
    378 		writeBit = ( writeBit + put ) & 7;
    379 	}
    380 }
    381 
    382 /*
    383 ================
    384 idCompressor_BitStream::ReadBits
    385 ================
    386 */
    387 int idCompressor_BitStream::ReadBits( int numBits ) {
    388 	int value, valueBits, get, fraction;
    389 
    390 	value = 0;
    391 	valueBits = 0;
    392 
    393 	// Short circuit for reading single bytes at a time
    394 	if ( readBit == 0 && numBits == 8 && readByte < readLength ) {
    395 		readByte++;
    396 		readTotalBytes++;
    397 		return readData[readByte - 1];
    398 	}
    399 
    400 	while ( valueBits < numBits ) {
    401 		if ( readBit == 0 ) {
    402 			if ( readByte >= readLength ) {
    403 				if ( readData == buffer ) {
    404 					readLength = file->Read( buffer, sizeof( buffer ) );
    405 					readByte = 0;
    406 				} else {
    407 					get = numBits - valueBits;
    408 					readBit = get & 7;
    409 					readByte += ( get >> 3 ) + ( readBit != 0 );
    410 					readTotalBytes += ( get >> 3 ) + ( readBit != 0 );
    411 					return value;
    412 				}
    413 			}
    414 			readByte++;
    415 			readTotalBytes++;
    416 		}
    417 		get = 8 - readBit;
    418 		if ( get > (numBits - valueBits) ) {
    419 			get = (numBits - valueBits);
    420 		}
    421 		fraction = readData[readByte - 1];
    422 		fraction >>= readBit;
    423 		fraction &= ( 1 << get ) - 1;
    424 		value |= fraction << valueBits;
    425 		valueBits += get;
    426 		readBit = ( readBit + get ) & 7;
    427 	}
    428 
    429 	return value;
    430 }
    431 
    432 /*
    433 ================
    434 idCompressor_BitStream::UnreadBits
    435 ================
    436 */
    437 void idCompressor_BitStream::UnreadBits( int numBits ) {
    438 	readByte -= ( numBits >> 3 );
    439 	readTotalBytes -= ( numBits >> 3 );
    440 	if ( readBit == 0 ) {
    441 		readBit = 8 - ( numBits & 7 );
    442 	} else {
    443 		readBit -= numBits & 7;
    444 		if ( readBit <= 0 ) {
    445 			readByte--;
    446 			readTotalBytes--;
    447 			readBit = ( readBit + 8 ) & 7;
    448 		}
    449 	}
    450 	if ( readByte < 0 ) {
    451 		readByte = 0;
    452 		readBit = 0;
    453 	}
    454 }
    455 
    456 /*
    457 ================
    458 idCompressor_BitStream::Compare
    459 ================
    460 */
    461 int idCompressor_BitStream::Compare( const byte *src1, int bitPtr1, const byte *src2, int bitPtr2, int maxBits ) const {
    462 	int i;
    463 
    464 	// If the two bit pointers are aligned then we can use a faster comparison
    465 	if ( ( bitPtr1 & 7 ) == (bitPtr2 & 7 ) && maxBits > 16 ) {
    466 		const byte *p1 = &src1[bitPtr1 >> 3];
    467 		const byte *p2 = &src2[bitPtr2 >> 3];
    468 
    469 		int bits = 0;
    470 
    471 		int bitsRemain = maxBits;
    472 
    473 		// Compare the first couple bits (if any)
    474 		if ( bitPtr1 & 7 ) {
    475 			for ( i = (bitPtr1 & 7); i < 8; i++, bits++ ) {
    476 				if ( ( ( *p1 >> i ) ^ ( *p2 >> i ) ) & 1 ) {
    477 					return bits;
    478 				}
    479 				bitsRemain--;
    480 			}
    481 			p1++;
    482 			p2++;
    483 		}
    484 
    485 		int remain = bitsRemain >> 3;
    486 
    487 		// Compare the middle bytes as ints
    488 		while ( remain >= 4 && (*(const int *)p1 == *(const int *)p2) ) {
    489 			p1 += 4;
    490 			p2 += 4;
    491 			remain -= 4;
    492 			bits += 32;
    493 		}
    494 
    495 		// Compare the remaining bytes
    496 		while ( remain > 0 && (*p1 == *p2) ) {
    497 			p1++;
    498 			p2++;
    499 			remain--;
    500 			bits += 8;
    501 		}
    502 
    503 		// Compare the last couple of bits (if any)
    504 		int finalBits = 8;
    505 		if ( remain == 0 ) {
    506 			finalBits = ( bitsRemain & 7 );
    507 		}
    508 		for ( i = 0; i < finalBits; i++, bits++ ) {
    509 			if ( ( ( *p1 >> i ) ^ ( *p2 >> i ) ) & 1 ) {
    510 				return bits;
    511 			}
    512 		}
    513 
    514 		assert(bits == maxBits);
    515 		return bits;
    516 	} else {
    517 	for ( i = 0; i < maxBits; i++ ) {
    518 			if ( ( ( src1[bitPtr1 >> 3] >> ( bitPtr1 & 7 ) ) ^ ( src2[bitPtr2 >> 3] >> ( bitPtr2 & 7 ) ) ) & 1 ) {
    519 			break;
    520 		}
    521 		bitPtr1++;
    522 		bitPtr2++;
    523 	}
    524 	return i;
    525 }
    526 }
    527 
    528 /*
    529 ================
    530 idCompressor_BitStream::Write
    531 ================
    532 */
    533 int idCompressor_BitStream::Write( const void *inData, int inLength ) {
    534 	int i;
    535 
    536 	if ( compress == false || inLength <= 0 ) {
    537 		return 0;
    538 	}
    539 
    540 	InitCompress( inData, inLength );
    541 
    542 	for ( i = 0; i < inLength; i++ ) {
    543 		WriteBits( ReadBits( 8 ), 8 );
    544 	}
    545 	return i;
    546 }
    547 
    548 /*
    549 ================
    550 idCompressor_BitStream::FinishCompress
    551 ================
    552 */
    553 void idCompressor_BitStream::FinishCompress() {
    554 	if ( compress == false ) {
    555 		return;
    556 	}
    557 
    558 	if ( writeByte ) {
    559 		file->Write( buffer, writeByte );
    560 	}
    561 	writeLength = 0;
    562 	writeByte = 0;
    563 	writeBit = 0;
    564 }
    565 
    566 /*
    567 ================
    568 idCompressor_BitStream::Read
    569 ================
    570 */
    571 int idCompressor_BitStream::Read( void *outData, int outLength ) {
    572 	int i;
    573 
    574 	if ( compress == true || outLength <= 0 ) {
    575 		return 0;
    576 	}
    577 
    578 	InitDecompress( outData, outLength );
    579 
    580 	for ( i = 0; i < outLength && readLength >= 0; i++ ) {
    581 		WriteBits( ReadBits( 8 ), 8 );
    582 	}
    583 	return i;
    584 }
    585 
    586 /*
    587 ================
    588 idCompressor_BitStream::GetCompressionRatio
    589 ================
    590 */
    591 float idCompressor_BitStream::GetCompressionRatio() const {
    592 	if ( compress ) {
    593 		return ( readTotalBytes - writeTotalBytes ) * 100.0f / readTotalBytes;
    594 	} else {
    595 		return ( writeTotalBytes - readTotalBytes ) * 100.0f / writeTotalBytes;
    596 	}
    597 }
    598 
    599 
    600 /*
    601 =================================================================================
    602 
    603 	idCompressor_RunLength
    604 
    605 	The following algorithm implements run length compression with an arbitrary
    606 	word size.
    607 
    608 =================================================================================
    609 */
    610 
    611 class idCompressor_RunLength : public idCompressor_BitStream {
    612 public:
    613 					idCompressor_RunLength() {}
    614 
    615 	void			Init( idFile *f, bool compress, int wordLength );
    616 
    617 	int				Write( const void *inData, int inLength );
    618 	int				Read( void *outData, int outLength );
    619 
    620 private:
    621 	int				runLengthCode;
    622 };
    623 
    624 /*
    625 ================
    626 idCompressor_RunLength::Init
    627 ================
    628 */
    629 void idCompressor_RunLength::Init( idFile *f, bool compress, int wordLength ) {
    630 	idCompressor_BitStream::Init( f, compress, wordLength );
    631 	runLengthCode = ( 1 << wordLength ) - 1;
    632 }
    633 
    634 /*
    635 ================
    636 idCompressor_RunLength::Write
    637 ================
    638 */
    639 int idCompressor_RunLength::Write( const void *inData, int inLength ) {
    640 	int bits, nextBits, count;
    641 
    642 	if ( compress == false || inLength <= 0 ) {
    643 		return 0;
    644 	}
    645 
    646 	InitCompress( inData, inLength );
    647 
    648 	while( readByte <= readLength ) {
    649 		count = 1;
    650 		bits = ReadBits( wordLength );
    651 		for ( nextBits = ReadBits( wordLength ); nextBits == bits; nextBits = ReadBits( wordLength ) ) {
    652 			count++;
    653 			if ( count >= ( 1 << wordLength ) ) {
    654 				if ( count >= ( 1 << wordLength ) + 3 || bits == runLengthCode ) {
    655 					break;
    656 				}
    657 			}
    658 		}
    659 		if ( nextBits != bits ) {
    660 			UnreadBits( wordLength );
    661 		}
    662 		if ( count > 3 || bits == runLengthCode ) {
    663 			WriteBits( runLengthCode, wordLength );
    664 			WriteBits( bits, wordLength );
    665 			if ( bits != runLengthCode ) {
    666 				count -= 3;
    667 			}
    668 			WriteBits( count - 1, wordLength );
    669 		} else {
    670 			while( count-- ) {
    671 				WriteBits( bits, wordLength );
    672 			}
    673 		}
    674 	}
    675 
    676 	return inLength;
    677 }
    678 
    679 /*
    680 ================
    681 idCompressor_RunLength::Read
    682 ================
    683 */
    684 int idCompressor_RunLength::Read( void *outData, int outLength ) {
    685 	int bits, count;
    686 
    687 	if ( compress == true || outLength <= 0 ) {
    688 		return 0;
    689 	}
    690 
    691 	InitDecompress( outData, outLength );
    692 
    693 	while( writeByte <= writeLength && readLength >= 0 ) {
    694 		bits = ReadBits( wordLength );
    695 		if ( bits == runLengthCode ) {
    696 			bits = ReadBits( wordLength );
    697 			count = ReadBits( wordLength ) + 1;
    698 			if ( bits != runLengthCode ) {
    699 				count += 3;
    700 			}
    701 			while( count-- ) {
    702 				WriteBits( bits, wordLength );
    703 			}
    704 		} else {
    705 			WriteBits( bits, wordLength );
    706 		}
    707 	}
    708 
    709 	return writeByte;
    710 }
    711 
    712 
    713 /*
    714 =================================================================================
    715 
    716 	idCompressor_RunLength_ZeroBased
    717 
    718 	The following algorithm implements run length compression with an arbitrary
    719 	word size for data with a lot of zero bits.
    720 
    721 =================================================================================
    722 */
    723 
    724 class idCompressor_RunLength_ZeroBased : public idCompressor_BitStream {
    725 public:
    726 					idCompressor_RunLength_ZeroBased() {}
    727 
    728 	int				Write( const void *inData, int inLength );
    729 	int				Read( void *outData, int outLength );
    730 
    731 private:
    732 };
    733 
    734 /*
    735 ================
    736 idCompressor_RunLength_ZeroBased::Write
    737 ================
    738 */
    739 int idCompressor_RunLength_ZeroBased::Write( const void *inData, int inLength ) {
    740 	int bits, count;
    741 
    742 	if ( compress == false || inLength <= 0 ) {
    743 		return 0;
    744 	}
    745 
    746 	InitCompress( inData, inLength );
    747 
    748 	while( readByte <= readLength ) {
    749 		count = 0;
    750 		for ( bits = ReadBits( wordLength ); bits == 0 && count < ( 1 << wordLength ); bits = ReadBits( wordLength ) ) {
    751 			count++;
    752 		}
    753 		if ( count ) {
    754 			WriteBits( 0, wordLength );
    755 			WriteBits( count - 1, wordLength );
    756 			UnreadBits( wordLength );
    757 		} else {
    758 			WriteBits( bits, wordLength );
    759 		}
    760 	}
    761 
    762 	return inLength;
    763 }
    764 
    765 /*
    766 ================
    767 idCompressor_RunLength_ZeroBased::Read
    768 ================
    769 */
    770 int idCompressor_RunLength_ZeroBased::Read( void *outData, int outLength ) {
    771 	int bits, count;
    772 
    773 	if ( compress == true || outLength <= 0 ) {
    774 		return 0;
    775 	}
    776 
    777 	InitDecompress( outData, outLength );
    778 
    779 	while( writeByte <= writeLength && readLength >= 0 ) {
    780 		bits = ReadBits( wordLength );
    781 		if ( bits == 0 ) {
    782 			count = ReadBits( wordLength ) + 1;
    783 			while( count-- > 0 ) {
    784 				WriteBits( 0, wordLength );
    785 			}
    786 		} else {
    787 			WriteBits( bits, wordLength );
    788 		}
    789 	}
    790 
    791 	return writeByte;
    792 }
    793 
    794 
    795 /*
    796 =================================================================================
    797 
    798 	idCompressor_Huffman
    799 
    800 	The following algorithm is based on the adaptive Huffman algorithm described
    801 	in Sayood's Data Compression book. The ranks are not actually stored, but
    802 	implicitly defined by the location of a node within a doubly-linked list
    803 
    804 =================================================================================
    805 */
    806 
    807 const int HMAX			= 256;				// Maximum symbol
    808 const int NYT			= HMAX;				// NYT = Not Yet Transmitted
    809 const int INTERNAL_NODE	= HMAX + 1;			// internal node
    810 
    811 typedef struct nodetype {
    812 	struct nodetype *left, *right, *parent; // tree structure
    813 	struct nodetype *next, *prev;			// doubly-linked list
    814 	struct nodetype **head;					// highest ranked node in block
    815 	int				weight;
    816 	int				symbol; 
    817 } huffmanNode_t;
    818 
    819 class idCompressor_Huffman : public idCompressor_None {
    820 public:
    821 					idCompressor_Huffman() {}
    822 
    823 	void			Init( idFile *f, bool compress, int wordLength );
    824 	void			FinishCompress();
    825 	float			GetCompressionRatio() const;
    826 
    827 	int				Write( const void *inData, int inLength );
    828 	int				Read( void *outData, int outLength );
    829 
    830 private:
    831 	byte			seq[65536];
    832 	int				bloc;
    833 	int				blocMax;
    834 	int				blocIn;
    835 	int				blocNode;
    836 	int				blocPtrs;
    837 
    838 	int				compressedSize;
    839 	int				unCompressedSize;
    840 
    841 	huffmanNode_t *	tree;
    842 	huffmanNode_t *	lhead;
    843 	huffmanNode_t *	ltail;
    844 	huffmanNode_t *	loc[HMAX+1];
    845 	huffmanNode_t **freelist;
    846 
    847 	huffmanNode_t	nodeList[768];
    848 	huffmanNode_t *	nodePtrs[768];
    849 
    850 private:
    851 	void			AddRef( byte ch );
    852 	int				Receive( huffmanNode_t *node, int *ch );
    853 	void			Transmit( int ch, byte *fout );
    854 	void			PutBit( int bit, byte *fout, int *offset );
    855 	int				GetBit( byte *fout, int *offset );
    856 
    857 	void			Add_bit( char bit, byte *fout );
    858 	int				Get_bit();
    859 	huffmanNode_t **Get_ppnode();
    860 	void			Free_ppnode( huffmanNode_t **ppnode );
    861 	void			Swap( huffmanNode_t *node1, huffmanNode_t *node2 );
    862 	void			Swaplist( huffmanNode_t *node1, huffmanNode_t *node2 );
    863 	void			Increment( huffmanNode_t *node );
    864 	void			Send( huffmanNode_t *node, huffmanNode_t *child, byte *fout );
    865 };
    866 
    867 /*
    868 ================
    869 idCompressor_Huffman::Init
    870 ================
    871 */
    872 void idCompressor_Huffman::Init( idFile *f, bool compress, int wordLength ) {
    873 	int i;
    874 
    875 	this->file = f;
    876 	this->compress = compress;
    877 	bloc = 0;
    878 	blocMax = 0;
    879 	blocIn = 0;
    880 	blocNode = 0;
    881 	blocPtrs = 0;
    882 	compressedSize = 0;
    883 	unCompressedSize = 0;
    884 
    885 	tree = NULL;
    886 	lhead = NULL;
    887 	ltail = NULL;
    888 	for( i = 0; i < (HMAX+1); i++ ) {
    889 		loc[i] = NULL;
    890 	}
    891 	freelist = NULL;
    892 
    893 	for( i = 0; i < 768; i++ ) {
    894 		memset( &nodeList[i], 0, sizeof(huffmanNode_t) );
    895 		nodePtrs[i] = NULL;
    896 	}
    897 
    898 	if ( compress ) {
    899 		// Add the NYT (not yet transmitted) node into the tree/list
    900 		tree = lhead = loc[NYT] = &nodeList[blocNode++];
    901 		tree->symbol = NYT;
    902 		tree->weight = 0;
    903 		lhead->next = lhead->prev = NULL;
    904 		tree->parent = tree->left = tree->right = NULL;
    905 	} else {
    906 		// Initialize the tree & list with the NYT node 
    907 		tree = lhead = ltail = loc[NYT] = &nodeList[blocNode++];
    908 		tree->symbol = NYT;
    909 		tree->weight = 0;
    910 		lhead->next = lhead->prev = NULL;
    911 		tree->parent = tree->left = tree->right = NULL;
    912 	}
    913 }
    914 
    915 /*
    916 ================
    917 idCompressor_Huffman::PutBit
    918 ================
    919 */
    920 void idCompressor_Huffman::PutBit( int bit, byte *fout, int *offset) {
    921 	bloc = *offset;
    922 	if ( (bloc&7) == 0 ) {
    923 		fout[(bloc>>3)] = 0;
    924 	}
    925 	fout[(bloc>>3)] |= bit << (bloc&7);
    926 	bloc++;
    927 	*offset = bloc;
    928 }
    929 
    930 /*
    931 ================
    932 idCompressor_Huffman::GetBit
    933 ================
    934 */
    935 int idCompressor_Huffman::GetBit( byte *fin, int *offset) {
    936 	int t;
    937 	bloc = *offset;
    938 	t = (fin[(bloc>>3)] >> (bloc&7)) & 0x1;
    939 	bloc++;
    940 	*offset = bloc;
    941 	return t;
    942 }
    943 
    944 /*
    945 ================
    946 idCompressor_Huffman::Add_bit
    947 
    948   Add a bit to the output file (buffered)
    949 ================
    950 */
    951 void idCompressor_Huffman::Add_bit( char bit, byte *fout ) {
    952 	if ( (bloc&7) == 0 ) {
    953 		fout[(bloc>>3)] = 0;
    954 	}
    955 	fout[(bloc>>3)] |= bit << (bloc&7);
    956 	bloc++;
    957 }
    958 
    959 /*
    960 ================
    961 idCompressor_Huffman::Get_bit
    962 
    963   Get one bit from the input file (buffered)
    964 ================
    965 */
    966 int idCompressor_Huffman::Get_bit() {
    967 	int t;
    968 	int wh = bloc >> 3;
    969 	int whb = wh>> 16;
    970 	if ( whb != blocIn ) {
    971 		blocMax += file->Read( seq, sizeof( seq ) );
    972 		blocIn++;
    973 	}
    974 	wh &= 0xffff;
    975 	t = ( seq[wh] >> ( bloc & 7 ) ) & 0x1;
    976 	bloc++;
    977 	return t;
    978 }
    979 
    980 /*
    981 ================
    982 idCompressor_Huffman::Get_ppnode
    983 ================
    984 */
    985 huffmanNode_t **idCompressor_Huffman::Get_ppnode() {
    986 	huffmanNode_t **tppnode;
    987 	if ( !freelist ) {
    988 		return &nodePtrs[blocPtrs++];
    989 	} else {
    990 		tppnode = freelist;
    991 		freelist = (huffmanNode_t **)*tppnode;
    992 		return tppnode;
    993 	}
    994 }
    995 
    996 /*
    997 ================
    998 idCompressor_Huffman::Free_ppnode
    999 ================
   1000 */
   1001 void idCompressor_Huffman::Free_ppnode( huffmanNode_t **ppnode ) {
   1002 	*ppnode = (huffmanNode_t *)freelist;
   1003 	freelist = ppnode;
   1004 }
   1005 
   1006 /*
   1007 ================
   1008 idCompressor_Huffman::Swap
   1009 
   1010   Swap the location of the given two nodes in the tree.
   1011 ================
   1012 */
   1013 void idCompressor_Huffman::Swap( huffmanNode_t *node1, huffmanNode_t *node2 ) { 
   1014 	huffmanNode_t *par1, *par2;
   1015 
   1016 	par1 = node1->parent;
   1017 	par2 = node2->parent;
   1018 
   1019 	if ( par1 ) {
   1020 		if ( par1->left == node1 ) {
   1021 			par1->left = node2;
   1022 		} else {
   1023 	      par1->right = node2;
   1024 		}
   1025 	} else {
   1026 		tree = node2;
   1027 	}
   1028 
   1029 	if ( par2 ) {
   1030 		if ( par2->left == node2 ) {
   1031 			par2->left = node1;
   1032 		} else {
   1033 			par2->right = node1;
   1034 		}
   1035 	} else {
   1036 		tree = node1;
   1037 	}
   1038   
   1039 	node1->parent = par2;
   1040 	node2->parent = par1;
   1041 }
   1042 
   1043 /*
   1044 ================
   1045 idCompressor_Huffman::Swaplist
   1046 
   1047   Swap the given two nodes in the linked list (update ranks)
   1048 ================
   1049 */
   1050 void idCompressor_Huffman::Swaplist( huffmanNode_t *node1, huffmanNode_t *node2 ) {
   1051 	huffmanNode_t *par1;
   1052 
   1053 	par1 = node1->next;
   1054 	node1->next = node2->next;
   1055 	node2->next = par1;
   1056 
   1057 	par1 = node1->prev;
   1058 	node1->prev = node2->prev;
   1059 	node2->prev = par1;
   1060 
   1061 	if ( node1->next == node1 ) {
   1062 		node1->next = node2;
   1063 	}
   1064 	if ( node2->next == node2 ) {
   1065 		node2->next = node1;
   1066 	}
   1067 	if ( node1->next ) {
   1068 		node1->next->prev = node1;
   1069 	}
   1070 	if ( node2->next ) {
   1071 		node2->next->prev = node2;
   1072 	}
   1073 	if ( node1->prev ) {
   1074 		node1->prev->next = node1;
   1075 	}
   1076 	if ( node2->prev ) {
   1077 		node2->prev->next = node2;
   1078 	}
   1079 }
   1080 
   1081 /*
   1082 ================
   1083 idCompressor_Huffman::Increment
   1084 ================
   1085 */
   1086 void idCompressor_Huffman::Increment( huffmanNode_t *node ) {
   1087 	huffmanNode_t *lnode;
   1088 
   1089 	if ( !node ) {
   1090 		return;
   1091 	}
   1092 
   1093 	if ( node->next != NULL && node->next->weight == node->weight ) {
   1094 	    lnode = *node->head;
   1095 		if ( lnode != node->parent ) {
   1096 			Swap( lnode, node );
   1097 		}
   1098 		Swaplist( lnode, node );
   1099 	}
   1100 	if ( node->prev && node->prev->weight == node->weight ) {
   1101 		*node->head = node->prev;
   1102 	} else {
   1103 	    *node->head = NULL;
   1104 		Free_ppnode( node->head );
   1105 	}
   1106 	node->weight++;
   1107 	if ( node->next && node->next->weight == node->weight ) {
   1108 		node->head = node->next->head;
   1109 	} else { 
   1110 		node->head = Get_ppnode();
   1111 		*node->head = node;
   1112 	}
   1113 	if ( node->parent ) {
   1114 		Increment( node->parent );
   1115 		if ( node->prev == node->parent ) {
   1116 			Swaplist( node, node->parent );
   1117 			if ( *node->head == node ) {
   1118 				*node->head = node->parent;
   1119 			}
   1120 		}
   1121 	}
   1122 }
   1123 
   1124 /*
   1125 ================
   1126 idCompressor_Huffman::AddRef
   1127 ================
   1128 */
   1129 void idCompressor_Huffman::AddRef( byte ch ) {
   1130 	huffmanNode_t *tnode, *tnode2;
   1131 	if ( loc[ch] == NULL ) { /* if this is the first transmission of this node */
   1132 		tnode = &nodeList[blocNode++];
   1133 		tnode2 = &nodeList[blocNode++];
   1134 
   1135 		tnode2->symbol = INTERNAL_NODE;
   1136 		tnode2->weight = 1;
   1137 		tnode2->next = lhead->next;
   1138 		if ( lhead->next ) {
   1139 			lhead->next->prev = tnode2;
   1140 			if ( lhead->next->weight == 1 ) {
   1141 				tnode2->head = lhead->next->head;
   1142 			} else {
   1143 				tnode2->head = Get_ppnode();
   1144 				*tnode2->head = tnode2;
   1145 			}
   1146 		} else {
   1147 			tnode2->head = Get_ppnode();
   1148 			*tnode2->head = tnode2;
   1149 		}
   1150 		lhead->next = tnode2;
   1151 		tnode2->prev = lhead;
   1152  
   1153 		tnode->symbol = ch;
   1154 		tnode->weight = 1;
   1155 		tnode->next = lhead->next;
   1156 		if ( lhead->next ) {
   1157 			lhead->next->prev = tnode;
   1158 			if ( lhead->next->weight == 1 ) {
   1159 				tnode->head = lhead->next->head;
   1160 			} else {
   1161 				/* this should never happen */
   1162 				tnode->head = Get_ppnode();
   1163 				*tnode->head = tnode2;
   1164 		    }
   1165 		} else {
   1166 			/* this should never happen */
   1167 			tnode->head = Get_ppnode();
   1168 			*tnode->head = tnode;
   1169 		}
   1170 		lhead->next = tnode;
   1171 		tnode->prev = lhead;
   1172 		tnode->left = tnode->right = NULL;
   1173  
   1174 		if ( lhead->parent ) {
   1175 			if ( lhead->parent->left == lhead ) { /* lhead is guaranteed to by the NYT */
   1176 				lhead->parent->left = tnode2;
   1177 			} else {
   1178 				lhead->parent->right = tnode2;
   1179 			}
   1180 		} else {
   1181 			tree = tnode2; 
   1182 		}
   1183  
   1184 		tnode2->right = tnode;
   1185 		tnode2->left = lhead;
   1186  
   1187 		tnode2->parent = lhead->parent;
   1188 		lhead->parent = tnode->parent = tnode2;
   1189      
   1190 		loc[ch] = tnode;
   1191  
   1192 		Increment( tnode2->parent );
   1193 	} else {
   1194 		Increment( loc[ch] );
   1195 	}
   1196 }
   1197 
   1198 /*
   1199 ================
   1200 idCompressor_Huffman::Receive
   1201 
   1202   Get a symbol.
   1203 ================
   1204 */
   1205 int idCompressor_Huffman::Receive( huffmanNode_t *node, int *ch ) {
   1206 	while ( node && node->symbol == INTERNAL_NODE ) {
   1207 		if ( Get_bit() ) {
   1208 			node = node->right;
   1209 		} else {
   1210 			node = node->left;
   1211 		}
   1212 	}
   1213 	if ( !node ) {
   1214 		return 0;
   1215 	}
   1216 	return (*ch = node->symbol);
   1217 }
   1218 
   1219 /*
   1220 ================
   1221 idCompressor_Huffman::Send
   1222 
   1223   Send the prefix code for this node.
   1224 ================
   1225 */
   1226 void idCompressor_Huffman::Send( huffmanNode_t *node, huffmanNode_t *child, byte *fout ) {
   1227 	if ( node->parent ) {
   1228 		Send( node->parent, node, fout );
   1229 	}
   1230 	if ( child ) {
   1231 		if ( node->right == child ) {
   1232 			Add_bit( 1, fout );
   1233 		} else {
   1234 			Add_bit( 0, fout );
   1235 		}
   1236 	}
   1237 }
   1238 
   1239 /*
   1240 ================
   1241 idCompressor_Huffman::Transmit
   1242 
   1243   Send a symbol.
   1244 ================
   1245 */
   1246 void idCompressor_Huffman::Transmit( int ch, byte *fout ) {
   1247 	int i;
   1248 	if ( loc[ch] == NULL ) { 
   1249 		/* huffmanNode_t hasn't been transmitted, send a NYT, then the symbol */
   1250 		Transmit( NYT, fout );
   1251 		for ( i = 7; i >= 0; i-- ) {
   1252 			Add_bit( (char)((ch >> i) & 0x1), fout );
   1253 		}
   1254 	} else {
   1255 		Send( loc[ch], NULL, fout );
   1256 	}
   1257 }
   1258 
   1259 /*
   1260 ================
   1261 idCompressor_Huffman::Write
   1262 ================
   1263 */
   1264 int idCompressor_Huffman::Write( const void *inData, int inLength ) {
   1265 	int i, ch;
   1266 
   1267 	if ( compress == false || inLength <= 0 ) {
   1268 		return 0;
   1269 	}
   1270 
   1271 	for ( i = 0; i < inLength; i++ ) {
   1272 		ch = ((const byte *)inData)[i];
   1273 		Transmit( ch, seq );				/* Transmit symbol */
   1274 		AddRef( (byte)ch );					/* Do update */
   1275 		int b = (bloc>>3);
   1276 		if ( b > 32768 ) {
   1277 			file->Write( seq, b );
   1278 			seq[0] = seq[b];
   1279 			bloc &= 7;
   1280 			compressedSize += b;
   1281 		}
   1282 	}
   1283 
   1284 	unCompressedSize += i;
   1285 	return i;
   1286 }
   1287 
   1288 /*
   1289 ================
   1290 idCompressor_Huffman::FinishCompress
   1291 ================
   1292 */
   1293 void idCompressor_Huffman::FinishCompress() {
   1294 
   1295 	if ( compress == false ) {
   1296 		return;
   1297 	}
   1298 	
   1299 	bloc += 7;
   1300 	int str = (bloc>>3);
   1301 	if ( str ) {
   1302 		file->Write( seq, str );
   1303 		compressedSize += str;
   1304 	}
   1305 }
   1306 
   1307 /*
   1308 ================
   1309 idCompressor_Huffman::Read
   1310 ================
   1311 */
   1312 int idCompressor_Huffman::Read( void *outData, int outLength ) {
   1313 	int i, j, ch;
   1314 
   1315 	if ( compress == true || outLength <= 0 ) {
   1316 		return 0;
   1317 	}
   1318 
   1319 	if ( bloc == 0 ) {
   1320 		blocMax = file->Read( seq, sizeof( seq ) );
   1321 		blocIn = 0;
   1322 	}
   1323 
   1324 	for ( i = 0; i < outLength; i++ ) {
   1325 		ch = 0;
   1326 		// don't overflow reading from the file
   1327 		if ( ( bloc >> 3 ) > blocMax ) {
   1328 			break;
   1329 		}
   1330 		Receive( tree, &ch );				/* Get a character */
   1331 		if ( ch == NYT ) {					/* We got a NYT, get the symbol associated with it */
   1332 			ch = 0;
   1333 			for ( j = 0; j < 8; j++ ) {
   1334 				ch = ( ch << 1 ) + Get_bit();
   1335 			}
   1336 		}
   1337     
   1338 		((byte *)outData)[i] = ch;			/* Write symbol */
   1339 		AddRef( (byte) ch );				/* Increment node */
   1340 	}
   1341 
   1342 	compressedSize = bloc >> 3;
   1343 	unCompressedSize += i;
   1344 	return i;
   1345 }
   1346 
   1347 /*
   1348 ================
   1349 idCompressor_Huffman::GetCompressionRatio
   1350 ================
   1351 */
   1352 float idCompressor_Huffman::GetCompressionRatio() const {
   1353 	return ( unCompressedSize - compressedSize ) * 100.0f / unCompressedSize;
   1354 }
   1355 
   1356 
   1357 /*
   1358 =================================================================================
   1359 
   1360 	idCompressor_Arithmetic
   1361 
   1362 	The following algorithm is based on the Arithmetic Coding methods described
   1363 	by Mark Nelson. The probability table is implicitly stored.
   1364 
   1365 =================================================================================
   1366 */
   1367 
   1368 const int AC_WORD_LENGTH	= 8;
   1369 const int AC_NUM_BITS		= 16;
   1370 const int AC_MSB_SHIFT		= 15;
   1371 const int AC_MSB2_SHIFT		= 14;
   1372 const int AC_MSB_MASK		= 0x8000;
   1373 const int AC_MSB2_MASK		= 0x4000;
   1374 const int AC_HIGH_INIT		= 0xffff;
   1375 const int AC_LOW_INIT		= 0x0000;
   1376 
   1377 class idCompressor_Arithmetic : public idCompressor_BitStream {
   1378 public:
   1379 					idCompressor_Arithmetic() {}
   1380 
   1381 	void			Init( idFile *f, bool compress, int wordLength );
   1382 	void			FinishCompress();
   1383 
   1384 	int				Write( const void *inData, int inLength );
   1385 	int				Read( void *outData, int outLength );
   1386 	
   1387 private:
   1388 					typedef struct acProbs_s {
   1389 						unsigned int	low;
   1390 						unsigned int	high;
   1391 					} acProbs_t;
   1392 				
   1393 					typedef struct acSymbol_s {
   1394 						unsigned int	low;
   1395 						unsigned int	high;
   1396 						int				position;
   1397 					} acSymbol_t;
   1398 
   1399 	acProbs_t		probabilities[1<<AC_WORD_LENGTH];
   1400 
   1401 	int				symbolBuffer;
   1402 	int				symbolBit;
   1403 
   1404 	unsigned short	low;
   1405 	unsigned short	high;
   1406 	unsigned short	code;
   1407 	unsigned int	underflowBits;
   1408 	unsigned int	scale;
   1409 
   1410 private:
   1411 	void			InitProbabilities();
   1412 	void			UpdateProbabilities( acSymbol_t* symbol );
   1413 	int				ProbabilityForCount( unsigned int count );
   1414 
   1415 	void			CharToSymbol( byte c, acSymbol_t* symbol );
   1416 	void			EncodeSymbol( acSymbol_t* symbol );
   1417 
   1418 	int				SymbolFromCount( unsigned int count, acSymbol_t* symbol );
   1419 	int				GetCurrentCount();
   1420 	void			RemoveSymbolFromStream( acSymbol_t* symbol );
   1421 
   1422 	void			PutBit( int bit );
   1423 	int				GetBit();
   1424 
   1425 	void			WriteOverflowBits();
   1426 };
   1427 
   1428 /*
   1429 ================
   1430 idCompressor_Arithmetic::Init
   1431 ================
   1432 */
   1433 void idCompressor_Arithmetic::Init( idFile *f, bool compress, int wordLength ) {
   1434 	idCompressor_BitStream::Init( f, compress, wordLength );
   1435 
   1436 	symbolBuffer	= 0;
   1437 	symbolBit		= 0;
   1438 }
   1439 
   1440 /*
   1441 ================
   1442 idCompressor_Arithmetic::InitProbabilities
   1443 ================
   1444 */
   1445 void idCompressor_Arithmetic::InitProbabilities() {
   1446 	high			= AC_HIGH_INIT;
   1447 	low				= AC_LOW_INIT;
   1448 	underflowBits	= 0;
   1449 	code			= 0;
   1450 
   1451 	for( int i = 0; i < (1<<AC_WORD_LENGTH); i++ ) {
   1452 		probabilities[ i ].low = i;
   1453 		probabilities[ i ].high = i + 1;
   1454 	}
   1455 
   1456 	scale = (1<<AC_WORD_LENGTH);
   1457 }
   1458 
   1459 /*
   1460 ================
   1461 idCompressor_Arithmetic::UpdateProbabilities
   1462 ================
   1463 */
   1464 void idCompressor_Arithmetic::UpdateProbabilities( acSymbol_t* symbol ) {
   1465 	int i, x;
   1466 
   1467 	x = symbol->position;
   1468 	
   1469 	probabilities[ x ].high++;
   1470 
   1471 	for( i = x + 1; i < (1<<AC_WORD_LENGTH); i++ ) {
   1472 		probabilities[ i ].low++;
   1473 		probabilities[ i ].high++;
   1474 	}
   1475 
   1476 	scale++;
   1477 }
   1478 
   1479 /*
   1480 ================
   1481 idCompressor_Arithmetic::GetCurrentCount
   1482 ================
   1483 */
   1484 int idCompressor_Arithmetic::GetCurrentCount() {
   1485     return (unsigned int) ( ( ( ( (long) code - low ) + 1 ) * scale - 1 ) / ( ( (long) high - low ) + 1 ) );
   1486 }
   1487 
   1488 /*
   1489 ================
   1490 idCompressor_Arithmetic::ProbabilityForCount
   1491 ================
   1492 */
   1493 int idCompressor_Arithmetic::ProbabilityForCount( unsigned int count ) {
   1494 #if 1
   1495 
   1496 	int len, mid, offset, res;
   1497 
   1498 	len = (1<<AC_WORD_LENGTH);
   1499 	mid = len;
   1500 	offset = 0;
   1501 	res = 0;
   1502 	while( mid > 0 ) {
   1503 		mid = len >> 1;
   1504 		if ( count >= probabilities[offset+mid].high ) {
   1505 			offset += mid;
   1506 			len -= mid;
   1507 			res = 1;
   1508 		}
   1509 		else if ( count < probabilities[offset+mid].low ) {
   1510 			len -= mid;
   1511 			res = 0;
   1512 		} else {
   1513 			return offset+mid;
   1514 		}
   1515 	}
   1516 	return offset+res;
   1517 
   1518 #else
   1519 
   1520 	int j;
   1521 
   1522 	for( j = 0; j < (1<<AC_WORD_LENGTH); j++ ) {
   1523         if ( count >= probabilities[ j ].low && count < probabilities[ j ].high ) {
   1524 			return j;
   1525         }
   1526     }
   1527 
   1528 	assert( false );
   1529 
   1530 	return 0;
   1531 
   1532 #endif
   1533 }
   1534 
   1535 /*
   1536 ================
   1537 idCompressor_Arithmetic::SymbolFromCount
   1538 ================
   1539 */
   1540 int idCompressor_Arithmetic::SymbolFromCount( unsigned int count, acSymbol_t* symbol ) {
   1541 	int p = ProbabilityForCount( count );
   1542     symbol->low = probabilities[ p ].low;
   1543     symbol->high = probabilities[ p ].high;
   1544 	symbol->position = p;
   1545     return p;
   1546 }
   1547 
   1548 /*
   1549 ================
   1550 idCompressor_Arithmetic::RemoveSymbolFromStream
   1551 ================
   1552 */
   1553 void idCompressor_Arithmetic::RemoveSymbolFromStream( acSymbol_t* symbol ) {
   1554     long range;
   1555 
   1556 	range	= ( long )( high - low ) + 1;
   1557 	high	= low + ( unsigned short )( ( range * symbol->high ) / scale - 1 );
   1558 	low		= low + ( unsigned short )( ( range * symbol->low ) / scale );
   1559 
   1560     while( true ) {
   1561 
   1562         if ( ( high & AC_MSB_MASK ) == ( low & AC_MSB_MASK ) ) {
   1563 
   1564 		} else if( ( low & AC_MSB2_MASK ) == AC_MSB2_MASK && ( high & AC_MSB2_MASK ) == 0 ) {
   1565             code	^= AC_MSB2_MASK;
   1566             low		&= AC_MSB2_MASK - 1;
   1567             high	|= AC_MSB2_MASK;
   1568 		} else {
   1569 			UpdateProbabilities( symbol );
   1570             return;
   1571 		}
   1572 
   1573         low <<= 1;
   1574         high <<= 1;
   1575         high |= 1;
   1576         code <<= 1;
   1577         code |= ReadBits( 1 );
   1578     }
   1579 }
   1580 
   1581 /*
   1582 ================
   1583 idCompressor_Arithmetic::GetBit
   1584 ================
   1585 */
   1586 int idCompressor_Arithmetic::GetBit() {
   1587 	int getbit;
   1588 
   1589 	if( symbolBit <= 0 ) {
   1590 		// read a new symbol out
   1591 		acSymbol_t symbol;
   1592 		symbolBuffer = SymbolFromCount( GetCurrentCount(), &symbol );
   1593 		RemoveSymbolFromStream( &symbol );
   1594 		symbolBit = AC_WORD_LENGTH;
   1595 	}
   1596 
   1597 	getbit = ( symbolBuffer >> ( AC_WORD_LENGTH - symbolBit ) ) & 1;
   1598 	symbolBit--;
   1599 
   1600 	return getbit;
   1601 }
   1602 
   1603 /*
   1604 ================
   1605 idCompressor_Arithmetic::EncodeSymbol
   1606 ================
   1607 */
   1608 void idCompressor_Arithmetic::EncodeSymbol( acSymbol_t* symbol ) {
   1609 	unsigned int range;
   1610 	
   1611 	// rescale high and low for the new symbol.
   1612 	range	= ( high - low ) + 1;
   1613 	high	= low + ( unsigned short )(( range * symbol->high ) / scale - 1 );
   1614 	low		= low + ( unsigned short )(( range * symbol->low ) / scale );
   1615 
   1616 	while( true ) {
   1617 		if ( ( high & AC_MSB_MASK ) == ( low & AC_MSB_MASK ) ) {
   1618 			// the high digits of low and high have converged, and can be written to the stream
   1619 			WriteBits( high >> AC_MSB_SHIFT, 1 );
   1620 
   1621             while( underflowBits > 0 ) {
   1622 
   1623 				WriteBits( ~high >> AC_MSB_SHIFT, 1 );
   1624 
   1625 				underflowBits--;
   1626             }
   1627         } else if ( ( low & AC_MSB2_MASK ) && !( high & AC_MSB2_MASK ) ) {
   1628 			// underflow is in danger of happening, 2nd digits are converging but 1st digits don't match
   1629 			underflowBits	+= 1;
   1630 			low				&= AC_MSB2_MASK - 1;
   1631 			high			|= AC_MSB2_MASK;
   1632 		} else {
   1633 			UpdateProbabilities( symbol );
   1634             return;
   1635 		}
   1636 
   1637         low <<= 1;
   1638         high <<= 1;
   1639         high |=	1;
   1640     }
   1641 }
   1642 
   1643 /*
   1644 ================
   1645 idCompressor_Arithmetic::CharToSymbol
   1646 ================
   1647 */
   1648 void idCompressor_Arithmetic::CharToSymbol( byte c, acSymbol_t* symbol ) {
   1649 	symbol->low			= probabilities[ c ].low;
   1650 	symbol->high		= probabilities[ c ].high;
   1651 	symbol->position	= c;
   1652 }
   1653 
   1654 /*
   1655 ================
   1656 idCompressor_Arithmetic::PutBit
   1657 ================
   1658 */
   1659 void idCompressor_Arithmetic::PutBit( int putbit ) {
   1660 	symbolBuffer |= ( putbit & 1 ) << symbolBit;
   1661 	symbolBit++;
   1662 
   1663 	if( symbolBit >= AC_WORD_LENGTH ) {
   1664 		acSymbol_t symbol;
   1665 
   1666 		CharToSymbol( symbolBuffer, &symbol );
   1667 		EncodeSymbol( &symbol );
   1668 
   1669 		symbolBit = 0;
   1670 		symbolBuffer = 0;
   1671 	}
   1672 }
   1673 
   1674 /*
   1675 ================
   1676 idCompressor_Arithmetic::WriteOverflowBits
   1677 ================
   1678 */
   1679 void idCompressor_Arithmetic::WriteOverflowBits() {
   1680 
   1681 	WriteBits( low >> AC_MSB2_SHIFT, 1 );
   1682 
   1683 	underflowBits++;
   1684 	while( underflowBits-- > 0 ) {
   1685 		WriteBits( ~low >> AC_MSB2_SHIFT, 1 );
   1686 	}
   1687 }
   1688 
   1689 /*
   1690 ================
   1691 idCompressor_Arithmetic::Write
   1692 ================
   1693 */
   1694 int idCompressor_Arithmetic::Write( const void *inData, int inLength ) {
   1695 	int i, j;
   1696 
   1697 	if ( compress == false || inLength <= 0 ) {
   1698 		return 0;
   1699 	}
   1700 
   1701 	InitCompress( inData, inLength );
   1702 
   1703 	for( i = 0; i < inLength; i++ ) {
   1704 		if ( ( readTotalBytes & ( ( 1 << 14 ) - 1 ) ) == 0 ) {
   1705 			if ( readTotalBytes ) {
   1706 				WriteOverflowBits();
   1707 				WriteBits( 0, 15 );
   1708 				while( writeBit ) {
   1709 					WriteBits( 0, 1 );
   1710 				}
   1711 				WriteBits( 255, 8 );
   1712 			}
   1713 			InitProbabilities();
   1714 		}
   1715 		for ( j = 0; j < 8; j++ ) {
   1716 			PutBit( ReadBits( 1 ) );
   1717 		}
   1718 	}
   1719 
   1720 	return inLength;
   1721 }
   1722 
   1723 /*
   1724 ================
   1725 idCompressor_Arithmetic::FinishCompress
   1726 ================
   1727 */
   1728 void idCompressor_Arithmetic::FinishCompress() {
   1729 	if ( compress == false ) {
   1730 		return;
   1731 	}
   1732 
   1733 	WriteOverflowBits();
   1734 
   1735 	idCompressor_BitStream::FinishCompress();
   1736 }
   1737 
   1738 /*
   1739 ================
   1740 idCompressor_Arithmetic::Read
   1741 ================
   1742 */
   1743 int idCompressor_Arithmetic::Read( void *outData, int outLength ) {
   1744 	int i, j;
   1745 
   1746 	if ( compress == true || outLength <= 0 ) {
   1747 		return 0;
   1748 	}
   1749 
   1750 	InitDecompress( outData, outLength );
   1751 
   1752 	for( i = 0; i < outLength && readLength >= 0; i++ ) {
   1753 		if ( ( writeTotalBytes & ( ( 1 << 14 ) - 1 ) ) == 0 ) {
   1754 			if ( writeTotalBytes ) {
   1755 				while( readBit ) {
   1756 					ReadBits( 1 );
   1757 				}
   1758 				while( ReadBits( 8 ) == 0 && readLength > 0 ) {
   1759 				}
   1760 			}
   1761 			InitProbabilities();
   1762 			for ( j = 0; j < AC_NUM_BITS; j++ ) {
   1763 				code <<= 1;
   1764 				code |= ReadBits( 1 );
   1765 			}
   1766 		}
   1767 		for ( j = 0; j < 8; j++ ) {
   1768 			WriteBits( GetBit(), 1 );
   1769 		}
   1770 	}
   1771 
   1772 	return i;
   1773 }
   1774 
   1775 
   1776 /*
   1777 =================================================================================
   1778 
   1779 	idCompressor_LZSS
   1780 
   1781 	In 1977 Abraham Lempel and Jacob Ziv presented a dictionary based scheme for
   1782 	text compression called LZ77. For any new text LZ77 outputs an offset/length
   1783 	pair to previously seen text and the next new byte after the previously seen
   1784 	text.
   1785 
   1786 	In 1982 James Storer and Thomas Szymanski presented a modification on the work
   1787 	of Lempel and Ziv called LZSS. LZ77 always outputs an offset/length pair, even
   1788 	if a match is only one byte long. An offset/length pair usually takes more than
   1789 	a single byte to store and the compression is not optimal for small match sizes.
   1790 	LZSS uses a bit flag which tells whether the following data is a literal (byte)
   1791 	or an offset/length pair.
   1792 
   1793 	The following algorithm is an implementation of LZSS with arbitrary word size.
   1794 
   1795 =================================================================================
   1796 */
   1797 
   1798 const int LZSS_BLOCK_SIZE		= 65535;
   1799 const int LZSS_HASH_BITS		= 10;
   1800 const int LZSS_HASH_SIZE		= ( 1 << LZSS_HASH_BITS );
   1801 const int LZSS_HASH_MASK		= ( 1 << LZSS_HASH_BITS ) - 1;
   1802 const int LZSS_OFFSET_BITS		= 11;
   1803 const int LZSS_LENGTH_BITS		= 5;
   1804 
   1805 class idCompressor_LZSS : public idCompressor_BitStream {
   1806 public:
   1807 					idCompressor_LZSS() {}
   1808 
   1809 	void			Init( idFile *f, bool compress, int wordLength );
   1810 	void			FinishCompress();
   1811 
   1812 	int				Write( const void *inData, int inLength );
   1813 	int				Read( void *outData, int outLength );
   1814 
   1815 protected:
   1816 	int				offsetBits;
   1817 	int				lengthBits;
   1818 	int				minMatchWords;
   1819 
   1820 	byte			block[LZSS_BLOCK_SIZE];
   1821 	int				blockSize;
   1822 	int				blockIndex;
   1823 
   1824 	int				hashTable[LZSS_HASH_SIZE];
   1825 	int				hashNext[LZSS_BLOCK_SIZE * 8];
   1826 
   1827 protected:
   1828 	bool			FindMatch( int startWord, int startValue, int &wordOffset, int &numWords );
   1829 	void			AddToHash( int index, int hash );
   1830 	int				GetWordFromBlock( int wordOffset ) const;
   1831 	virtual void	CompressBlock();
   1832 	virtual void	DecompressBlock();
   1833 };
   1834 
   1835 /*
   1836 ================
   1837 idCompressor_LZSS::Init
   1838 ================
   1839 */
   1840 void idCompressor_LZSS::Init( idFile *f, bool compress, int wordLength ) {
   1841 	idCompressor_BitStream::Init( f, compress, wordLength );
   1842 
   1843 	offsetBits = LZSS_OFFSET_BITS;
   1844 	lengthBits = LZSS_LENGTH_BITS;
   1845 
   1846 	minMatchWords = ( offsetBits + lengthBits + wordLength ) / wordLength;
   1847 	blockSize = 0;
   1848 	blockIndex = 0;
   1849 }
   1850 
   1851 /*
   1852 ================
   1853 idCompressor_LZSS::FindMatch
   1854 ================
   1855 */
   1856 bool idCompressor_LZSS::FindMatch( int startWord, int startValue, int &wordOffset, int &numWords ) {
   1857 	int i, n, hash, bottom, maxBits;
   1858 
   1859 	wordOffset = startWord;
   1860 	numWords = minMatchWords - 1;
   1861 
   1862 	bottom = Max( 0, startWord - ( ( 1 << offsetBits ) - 1 ) );
   1863 	maxBits = ( blockSize << 3 ) - startWord * wordLength;
   1864 
   1865 	hash = startValue & LZSS_HASH_MASK;
   1866 	for ( i = hashTable[hash]; i >= bottom; i = hashNext[i] ) {
   1867 		n = Compare( block, i * wordLength, block, startWord * wordLength, Min( maxBits, ( startWord - i ) * wordLength ) );
   1868 		if ( n > numWords * wordLength ) {
   1869 			numWords = n / wordLength;
   1870 			wordOffset = i;
   1871 			if ( numWords > ( ( 1 << lengthBits ) - 1 + minMatchWords ) - 1 ) {
   1872 				numWords = ( ( 1 << lengthBits ) - 1 + minMatchWords ) - 1;
   1873 				break;
   1874 			}
   1875 		}
   1876 	}
   1877 
   1878 	return ( numWords >= minMatchWords );
   1879 }
   1880 
   1881 /*
   1882 ================
   1883 idCompressor_LZSS::AddToHash
   1884 ================
   1885 */
   1886 void idCompressor_LZSS::AddToHash( int index, int hash ) {
   1887 	hashNext[index] = hashTable[hash];
   1888 	hashTable[hash] = index;
   1889 }
   1890 
   1891 /*
   1892 ================
   1893 idCompressor_LZSS::GetWordFromBlock
   1894 ================
   1895 */
   1896 int idCompressor_LZSS::GetWordFromBlock( int wordOffset ) const {
   1897 	int blockBit, blockByte, value, valueBits, get, fraction;
   1898 
   1899 	blockBit = ( wordOffset * wordLength ) & 7;
   1900 	blockByte = ( wordOffset * wordLength ) >> 3;
   1901 	if ( blockBit != 0 ) {
   1902 		blockByte++;
   1903 	}
   1904 
   1905 	value = 0;
   1906 	valueBits = 0;
   1907 
   1908 	while ( valueBits < wordLength ) {
   1909 		if ( blockBit == 0 ) {
   1910 			if ( blockByte >= LZSS_BLOCK_SIZE ) {
   1911 				return value;
   1912 			}
   1913 			blockByte++;
   1914 		}
   1915 		get = 8 - blockBit;
   1916 		if ( get > (wordLength - valueBits) ) {
   1917 			get = (wordLength - valueBits);
   1918 		}
   1919 		fraction = block[blockByte - 1];
   1920 		fraction >>= blockBit;
   1921 		fraction &= ( 1 << get ) - 1;
   1922 		value |= fraction << valueBits;
   1923 		valueBits += get;
   1924 		blockBit = ( blockBit + get ) & 7;
   1925 	}
   1926 
   1927 	return value;
   1928 }
   1929 
   1930 /*
   1931 ================
   1932 idCompressor_LZSS::CompressBlock
   1933 ================
   1934 */
   1935 void idCompressor_LZSS::CompressBlock() {
   1936 	int i, startWord, startValue, wordOffset, numWords;
   1937 
   1938 	InitCompress( block, blockSize );
   1939 
   1940 	memset( hashTable, -1, sizeof( hashTable ) );
   1941 	memset( hashNext, -1, sizeof( hashNext ) );
   1942 
   1943 	startWord = 0;
   1944 	while( readByte < readLength ) {
   1945 		startValue = ReadBits( wordLength );
   1946 		if ( FindMatch( startWord, startValue, wordOffset, numWords ) ) {
   1947 			WriteBits( 1, 1 );
   1948 			WriteBits( startWord - wordOffset, offsetBits );
   1949 			WriteBits( numWords - minMatchWords, lengthBits );
   1950 			UnreadBits( wordLength );
   1951 			for ( i = 0; i < numWords; i++ ) {
   1952 				startValue = ReadBits( wordLength );
   1953 				AddToHash( startWord, startValue & LZSS_HASH_MASK );
   1954 				startWord++;
   1955 			}
   1956 		} else {
   1957 			WriteBits( 0, 1 );
   1958 			WriteBits( startValue, wordLength );
   1959 			AddToHash( startWord, startValue & LZSS_HASH_MASK );
   1960 			startWord++;
   1961 		}
   1962 	}
   1963 
   1964 	blockSize = 0;
   1965 }
   1966 
   1967 /*
   1968 ================
   1969 idCompressor_LZSS::DecompressBlock
   1970 ================
   1971 */
   1972 void idCompressor_LZSS::DecompressBlock() {
   1973 	int i, offset, startWord, numWords;
   1974 
   1975 	InitDecompress( block, LZSS_BLOCK_SIZE );
   1976 
   1977 	startWord = 0;
   1978 	while( writeByte < writeLength && readLength >= 0 ) {
   1979 		if ( ReadBits( 1 ) ) {
   1980 			offset = startWord - ReadBits( offsetBits );
   1981 			numWords = ReadBits( lengthBits ) + minMatchWords;
   1982 			for ( i = 0; i < numWords; i++ ) {
   1983 				WriteBits( GetWordFromBlock( offset + i ), wordLength );
   1984 				startWord++;
   1985 			}
   1986 		} else {
   1987 			WriteBits( ReadBits( wordLength ), wordLength );
   1988 			startWord++;
   1989 		}
   1990 	}
   1991 
   1992 	blockSize = Min( writeByte, LZSS_BLOCK_SIZE );
   1993 }
   1994 
   1995 /*
   1996 ================
   1997 idCompressor_LZSS::Write
   1998 ================
   1999 */
   2000 int idCompressor_LZSS::Write( const void *inData, int inLength ) {
   2001 	int i, n;
   2002 
   2003 	if ( compress == false || inLength <= 0 ) {
   2004 		return 0;
   2005 	}
   2006 
   2007 	for ( n = i = 0; i < inLength; i += n ) {
   2008 		n = LZSS_BLOCK_SIZE - blockSize;
   2009 		if ( inLength - i >= n ) {
   2010 			memcpy( block + blockSize, ((const byte *)inData) + i, n );
   2011 			blockSize = LZSS_BLOCK_SIZE;
   2012 			CompressBlock();
   2013 			blockSize = 0;
   2014 		} else {
   2015 			memcpy( block + blockSize, ((const byte *)inData) + i, inLength - i );
   2016 			n = inLength - i;
   2017 			blockSize += n;
   2018 		}
   2019 	}
   2020 
   2021 	return inLength;
   2022 }
   2023 
   2024 /*
   2025 ================
   2026 idCompressor_LZSS::FinishCompress
   2027 ================
   2028 */
   2029 void idCompressor_LZSS::FinishCompress() {
   2030 	if ( compress == false ) {
   2031 		return;
   2032 	}
   2033 	if ( blockSize ) {
   2034 		CompressBlock();
   2035 	}
   2036 	idCompressor_BitStream::FinishCompress();
   2037 }
   2038 
   2039 /*
   2040 ================
   2041 idCompressor_LZSS::Read
   2042 ================
   2043 */
   2044 int idCompressor_LZSS::Read( void *outData, int outLength ) {
   2045 	int i, n;
   2046 
   2047 	if ( compress == true || outLength <= 0 ) {
   2048 		return 0;
   2049 	}
   2050 
   2051 	if ( !blockSize ) {
   2052 		DecompressBlock();
   2053 	}
   2054 
   2055 	for ( n = i = 0; i < outLength; i += n ) {
   2056 		if ( !blockSize ) {
   2057 			return i;
   2058 		}
   2059 		n = blockSize - blockIndex;
   2060 		if ( outLength - i >= n ) {
   2061 			memcpy( ((byte *)outData) + i, block + blockIndex, n );
   2062 			DecompressBlock();
   2063 			blockIndex = 0;
   2064 		} else {
   2065 			memcpy( ((byte *)outData) + i, block + blockIndex, outLength - i );
   2066 			n = outLength - i;
   2067 			blockIndex += n;
   2068 		}
   2069 	}
   2070 
   2071 	return outLength;
   2072 }
   2073 
   2074 /*
   2075 =================================================================================
   2076 
   2077 	idCompressor_LZSS_WordAligned
   2078 
   2079 	Outputs word aligned compressed data.
   2080 
   2081 =================================================================================
   2082 */
   2083 
   2084 class idCompressor_LZSS_WordAligned : public idCompressor_LZSS {
   2085 public:
   2086 					idCompressor_LZSS_WordAligned() {}
   2087 
   2088 	void			Init( idFile *f, bool compress, int wordLength );
   2089 private:
   2090 	virtual void	CompressBlock();
   2091 	virtual void	DecompressBlock();
   2092 };
   2093 
   2094 /*
   2095 ================
   2096 idCompressor_LZSS_WordAligned::Init
   2097 ================
   2098 */
   2099 void idCompressor_LZSS_WordAligned::Init( idFile *f, bool compress, int wordLength ) {
   2100 	idCompressor_LZSS::Init( f, compress, wordLength );
   2101 
   2102 	offsetBits = 2 * wordLength;
   2103 	lengthBits = wordLength;
   2104 
   2105 	minMatchWords = ( offsetBits + lengthBits + wordLength ) / wordLength;
   2106 	blockSize = 0;
   2107 	blockIndex = 0;
   2108 }
   2109 
   2110 /*
   2111 ================
   2112 idCompressor_LZSS_WordAligned::CompressBlock
   2113 ================
   2114 */
   2115 void idCompressor_LZSS_WordAligned::CompressBlock() {
   2116 	int i, startWord, startValue, wordOffset, numWords;
   2117 
   2118 	InitCompress( block, blockSize );
   2119 
   2120 	memset( hashTable, -1, sizeof( hashTable ) );
   2121 	memset( hashNext, -1, sizeof( hashNext ) );
   2122 
   2123 	startWord = 0;
   2124 	while( readByte < readLength ) {
   2125 		startValue = ReadBits( wordLength );
   2126 		if ( FindMatch( startWord, startValue, wordOffset, numWords ) ) {
   2127 			WriteBits( numWords - ( minMatchWords - 1 ), lengthBits );
   2128 			WriteBits( startWord - wordOffset, offsetBits );
   2129 			UnreadBits( wordLength );
   2130 			for ( i = 0; i < numWords; i++ ) {
   2131 				startValue = ReadBits( wordLength );
   2132 				AddToHash( startWord, startValue & LZSS_HASH_MASK );
   2133 				startWord++;
   2134 			}
   2135 		} else {
   2136 			WriteBits( 0, lengthBits );
   2137 			WriteBits( startValue, wordLength );
   2138 			AddToHash( startWord, startValue & LZSS_HASH_MASK );
   2139 			startWord++;
   2140 		}
   2141 	}
   2142 
   2143 	blockSize = 0;
   2144 }
   2145 
   2146 /*
   2147 ================
   2148 idCompressor_LZSS_WordAligned::DecompressBlock
   2149 ================
   2150 */
   2151 void idCompressor_LZSS_WordAligned::DecompressBlock() {
   2152 	int i, offset, startWord, numWords;
   2153 
   2154 	InitDecompress( block, LZSS_BLOCK_SIZE );
   2155 
   2156 	startWord = 0;
   2157 	while( writeByte < writeLength && readLength >= 0 ) {
   2158 		numWords = ReadBits( lengthBits );
   2159 		if ( numWords ) {
   2160 			numWords += ( minMatchWords - 1 );
   2161 			offset = startWord - ReadBits( offsetBits );
   2162 			for ( i = 0; i < numWords; i++ ) {
   2163 				WriteBits( GetWordFromBlock( offset + i ), wordLength );
   2164 				startWord++;
   2165 			}
   2166 		} else {
   2167 			WriteBits( ReadBits( wordLength ), wordLength );
   2168 			startWord++;
   2169 		}
   2170 	}
   2171 
   2172 	blockSize = Min( writeByte, LZSS_BLOCK_SIZE );
   2173 }
   2174 
   2175 /*
   2176 =================================================================================
   2177 
   2178 	idCompressor_LZW
   2179 
   2180 	http://www.unisys.com/about__unisys/lzw
   2181 	http://www.dogma.net/markn/articles/lzw/lzw.htm
   2182 	http://www.cs.cf.ac.uk/Dave/Multimedia/node214.html
   2183 	http://www.cs.duke.edu/csed/curious/compression/lzw.html
   2184 	http://oldwww.rasip.fer.hr/research/compress/algorithms/fund/lz/lzw.html
   2185 
   2186 	This is the same compression scheme used by GIF with the exception that
   2187 	the EOI and clear codes are not explicitly stored.  Instead EOI happens
   2188 	when the input stream runs dry and CC happens when the table gets to big.
   2189 
   2190 	This is a derivation of LZ78, but the dictionary starts with all single
   2191 	character values so only code words are output.  It is similar in theory
   2192 	to LZ77, but instead of using the previous X bytes as a lookup table, a table
   2193 	is built as the stream is read.  The	compressor and decompressor use the
   2194 	same formula, so the tables should be exactly alike.  The only catch is the
   2195 	decompressor is always one step behind the compressor and may get a code not
   2196 	yet in the table.  In this case, it is easy to determine what the next code
   2197 	is going to be (it will be the previous string plus the first byte of the
   2198 	previous string).
   2199 
   2200 	The dictionary can be any size, but 12 bits seems to produce best results for
   2201 	most sample data.  The code size is variable.  It starts with the minimum
   2202 	number of bits required to store the dictionary and automatically increases
   2203 	as the dictionary gets bigger (it starts at 9 bits and grows to 10 bits when
   2204 	item 512 is added, 11 bits when 1024 is added, etc...) once the the dictionary
   2205 	is filled (4096 items for a 12 bit dictionary), the whole thing is cleared and
   2206 	the process starts over again.
   2207 
   2208 	The compressor increases the bit size after it adds the item, while the
   2209 	decompressor does before it adds the item.  The difference is subtle, but
   2210 	it's because decompressor being one step behind.  Otherwise, the decompressor
   2211 	would read 512 with only 9 bits.
   2212 
   2213 	If "Hello" is in the dictionary, then "Hell", "Hel", "He" and "H" will be too.
   2214 	We use this to our advantage by storing the index of the previous code, and
   2215 	the value of the last character.  This means when we traverse through the
   2216 	dictionary, we get the characters in reverse.
   2217 
   2218 	Dictionary entries 0-255 are always going to have the values 0-255
   2219 
   2220 =================================================================================
   2221 */
   2222 
   2223 class idCompressor_LZW : public idCompressor_BitStream {
   2224 public:
   2225 					idCompressor_LZW() {}
   2226 
   2227 	void			Init( idFile *f, bool compress, int wordLength );
   2228 	void			FinishCompress();
   2229 
   2230 	int				Write( const void *inData, int inLength );
   2231 	int				Read( void *outData, int outLength );
   2232 
   2233 protected:
   2234 	int				AddToDict( int w, int k );
   2235 	int				Lookup( int w, int k );
   2236 
   2237 	bool			BumpBits();
   2238 
   2239 	int				WriteChain( int code );
   2240 	void			DecompressBlock();
   2241 
   2242 	static const int LZW_BLOCK_SIZE = 32767;
   2243 	static const int LZW_START_BITS = 9;
   2244 	static const int LZW_FIRST_CODE = (1 << (LZW_START_BITS-1));
   2245 	static const int LZW_DICT_BITS = 12;
   2246 	static const int LZW_DICT_SIZE = 1 << LZW_DICT_BITS;
   2247 
   2248 	// Dictionary data
   2249 	struct {
   2250 		int k;
   2251 		int w;
   2252 	}				dictionary[LZW_DICT_SIZE];
   2253 	idHashIndex		index;
   2254 
   2255 	int				nextCode;
   2256 	int				codeBits;
   2257 
   2258 	// Block data
   2259 	byte			block[LZW_BLOCK_SIZE];
   2260 	int				blockSize;
   2261 	int				blockIndex;
   2262 
   2263 	// Used by the compressor
   2264 	int				w;
   2265 
   2266 	// Used by the decompressor
   2267 	int				oldCode;
   2268 };
   2269 
   2270 /*
   2271 ================
   2272 idCompressor_LZW::Init
   2273 ================
   2274 */
   2275 void idCompressor_LZW::Init( idFile *f, bool compress, int wordLength ) {
   2276 	idCompressor_BitStream::Init( f, compress, wordLength );
   2277 
   2278 	for ( int i=0; i<LZW_FIRST_CODE; i++ ) {
   2279 		dictionary[i].k = i;
   2280 		dictionary[i].w = -1;
   2281 	}
   2282 	index.Clear();
   2283 
   2284 	nextCode = LZW_FIRST_CODE;
   2285 	codeBits = LZW_START_BITS;
   2286 
   2287 	blockSize = 0;
   2288 	blockIndex = 0;
   2289 
   2290 	w = -1;
   2291 	oldCode = -1;
   2292 }
   2293 
   2294 /*
   2295 ================
   2296 idCompressor_LZW::Read
   2297 ================
   2298 */
   2299 int idCompressor_LZW::Read( void *outData, int outLength ) {
   2300 	int i, n;
   2301 
   2302 	if ( compress == true || outLength <= 0 ) {
   2303 		return 0;
   2304 	}
   2305 
   2306 	if ( !blockSize ) {
   2307 		DecompressBlock();
   2308 	}
   2309 
   2310 	for ( n = i = 0; i < outLength; i += n ) {
   2311 		if ( !blockSize ) {
   2312 			return i;
   2313 		}
   2314 		n = blockSize - blockIndex;
   2315 		if ( outLength - i >= n ) {
   2316 			memcpy( ((byte *)outData) + i, block + blockIndex, n );
   2317 			DecompressBlock();
   2318 			blockIndex = 0;
   2319 		} else {
   2320 			memcpy( ((byte *)outData) + i, block + blockIndex, outLength - i );
   2321 			n = outLength - i;
   2322 			blockIndex += n;
   2323 		}
   2324 	}
   2325 
   2326 	return outLength;
   2327 }
   2328 
   2329 /*
   2330 ================
   2331 idCompressor_LZW::Lookup
   2332 ================
   2333 */
   2334 int idCompressor_LZW::Lookup( int w, int k ) {
   2335 	int j;
   2336 
   2337 	if ( w == -1 ) {
   2338 		return k;
   2339 	} else {
   2340 		for ( j = index.First( w ^ k ); j >= 0 ; j = index.Next( j ) ) {
   2341 			if ( dictionary[ j ].k == k && dictionary[ j ].w == w ) { 
   2342 				return j;
   2343 			}
   2344 		}
   2345 	}
   2346 
   2347 	return -1;
   2348 }
   2349 
   2350 /*
   2351 ================
   2352 idCompressor_LZW::AddToDict
   2353 ================
   2354 */
   2355 int idCompressor_LZW::AddToDict( int w, int k ) {
   2356 	dictionary[ nextCode ].k = k;
   2357 	dictionary[ nextCode ].w = w;
   2358 	index.Add( w ^ k, nextCode );
   2359 	return nextCode++;
   2360 }
   2361 
   2362 /*
   2363 ================
   2364 idCompressor_LZW::BumpBits
   2365 
   2366 Possibly increments codeBits
   2367 Returns true if the dictionary was cleared
   2368 ================
   2369 */
   2370 bool idCompressor_LZW::BumpBits() {
   2371 	if ( nextCode == ( 1 << codeBits ) ) {
   2372 		codeBits ++;
   2373 		if ( codeBits > LZW_DICT_BITS ) {
   2374 			nextCode = LZW_FIRST_CODE;
   2375 			codeBits = LZW_START_BITS;
   2376 			index.Clear();
   2377 			return true;
   2378 		}
   2379 	}
   2380 	return false;
   2381 }
   2382 
   2383 /*
   2384 ================
   2385 idCompressor_LZW::FinishCompress
   2386 ================
   2387 */
   2388 void idCompressor_LZW::FinishCompress() {
   2389 	WriteBits( w, codeBits );
   2390 	idCompressor_BitStream::FinishCompress();
   2391 }
   2392 
   2393 /*
   2394 ================
   2395 idCompressor_LZW::Write
   2396 ================
   2397 */
   2398 int idCompressor_LZW::Write( const void *inData, int inLength ) {
   2399 	int i;
   2400 
   2401 	InitCompress( inData, inLength );
   2402 
   2403 	for ( i = 0; i < inLength; i++ ) {
   2404 		int k = ReadBits( 8 );
   2405 
   2406 		int code = Lookup(w, k);
   2407 		if ( code >= 0 ) {
   2408 			w = code;
   2409 		} else {
   2410 			WriteBits( w, codeBits );
   2411 			if ( !BumpBits() ) {
   2412 				AddToDict( w, k );
   2413 			}
   2414 			w = k;
   2415 		}
   2416 	}
   2417 
   2418 	return inLength;
   2419 }
   2420 
   2421 
   2422 /*
   2423 ================
   2424 idCompressor_LZW::WriteChain
   2425 The chain is stored backwards, so we have to write it to a buffer then output the buffer in reverse
   2426 ================
   2427 */
   2428 int idCompressor_LZW::WriteChain( int code ) {
   2429 	byte chain[LZW_DICT_SIZE];
   2430 	int firstChar = 0;
   2431 	int i = 0;
   2432 	do {
   2433 		assert( i < LZW_DICT_SIZE-1 && code >= 0 );
   2434 		chain[i++] = dictionary[code].k;
   2435 		code = dictionary[code].w;
   2436 	} while ( code >= 0 );
   2437 	firstChar = chain[--i];
   2438 	for ( ; i >= 0; i-- ) {
   2439 		WriteBits( chain[i], 8 );
   2440 	}
   2441 	return firstChar;
   2442 }
   2443 
   2444 /*
   2445 ================
   2446 idCompressor_LZW::DecompressBlock
   2447 ================
   2448 */
   2449 void idCompressor_LZW::DecompressBlock() {
   2450 	int code, firstChar;
   2451 
   2452 	InitDecompress( block, LZW_BLOCK_SIZE );
   2453 
   2454 	while( writeByte < writeLength - LZW_DICT_SIZE && readLength > 0 ) {
   2455 		assert( codeBits <= LZW_DICT_BITS );
   2456 
   2457 		code = ReadBits( codeBits );
   2458 		if ( readLength == 0 ) {
   2459 			break;
   2460 		}
   2461 
   2462 		if ( oldCode == -1 ) {
   2463 			assert( code < 256 );
   2464 			WriteBits( code, 8 );
   2465 			oldCode = code;
   2466 			firstChar = code;
   2467 			continue;
   2468 		}
   2469 
   2470 		if ( code >= nextCode ) {
   2471 			assert( code == nextCode );
   2472 			firstChar = WriteChain( oldCode );
   2473 			WriteBits( firstChar, 8 );
   2474 		} else {
   2475 			firstChar = WriteChain( code );
   2476 		}
   2477 		AddToDict( oldCode, firstChar );
   2478 		if ( BumpBits() ) {
   2479 			oldCode = -1;
   2480 		} else {
   2481 			oldCode = code;
   2482 		}
   2483 	}
   2484 
   2485 	blockSize = Min( writeByte, LZW_BLOCK_SIZE );
   2486 }
   2487 
   2488 /*
   2489 =================================================================================
   2490 
   2491 	idCompressor
   2492 
   2493 =================================================================================
   2494 */
   2495 
   2496 /*
   2497 ================
   2498 idCompressor::AllocNoCompression
   2499 ================
   2500 */
   2501 idCompressor * idCompressor::AllocNoCompression() {
   2502 	return new (TAG_IDFILE) idCompressor_None();
   2503 }
   2504 
   2505 /*
   2506 ================
   2507 idCompressor::AllocBitStream
   2508 ================
   2509 */
   2510 idCompressor * idCompressor::AllocBitStream() {
   2511 	return new (TAG_IDFILE) idCompressor_BitStream();
   2512 }
   2513 
   2514 /*
   2515 ================
   2516 idCompressor::AllocRunLength
   2517 ================
   2518 */
   2519 idCompressor * idCompressor::AllocRunLength() {
   2520 	return new (TAG_IDFILE) idCompressor_RunLength();
   2521 }
   2522 
   2523 /*
   2524 ================
   2525 idCompressor::AllocRunLength_ZeroBased
   2526 ================
   2527 */
   2528 idCompressor * idCompressor::AllocRunLength_ZeroBased() {
   2529 	return new (TAG_IDFILE) idCompressor_RunLength_ZeroBased();
   2530 }
   2531 
   2532 /*
   2533 ================
   2534 idCompressor::AllocHuffman
   2535 ================
   2536 */
   2537 idCompressor * idCompressor::AllocHuffman() {
   2538 	return new (TAG_IDFILE) idCompressor_Huffman();
   2539 }
   2540 
   2541 /*
   2542 ================
   2543 idCompressor::AllocArithmetic
   2544 ================
   2545 */
   2546 idCompressor * idCompressor::AllocArithmetic() {
   2547 	return new (TAG_IDFILE) idCompressor_Arithmetic();
   2548 }
   2549 
   2550 /*
   2551 ================
   2552 idCompressor::AllocLZSS
   2553 ================
   2554 */
   2555 idCompressor * idCompressor::AllocLZSS() {
   2556 	return new (TAG_IDFILE) idCompressor_LZSS();
   2557 }
   2558 
   2559 /*
   2560 ================
   2561 idCompressor::AllocLZSS_WordAligned
   2562 ================
   2563 */
   2564 idCompressor * idCompressor::AllocLZSS_WordAligned() {
   2565 	return new (TAG_IDFILE) idCompressor_LZSS_WordAligned();
   2566 }
   2567 
   2568 /*
   2569 ================
   2570 idCompressor::AllocLZW
   2571 ================
   2572 */
   2573 idCompressor * idCompressor::AllocLZW() {
   2574 	return new (TAG_IDFILE) idCompressor_LZW();
   2575 }