DS_HuffmanEncodingTree.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. /*
  2. * Copyright (c) 2014, Oculus VR, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. *
  9. */
  10. #include "DS_HuffmanEncodingTree.h"
  11. #include "DS_Queue.h"
  12. #include "BitStream.h"
  13. #include "RakAssert.h"
  14. #ifdef _MSC_VER
  15. #pragma warning( push )
  16. #endif
  17. using namespace RakNet;
  18. HuffmanEncodingTree::HuffmanEncodingTree()
  19. {
  20. root = 0;
  21. }
  22. HuffmanEncodingTree::~HuffmanEncodingTree()
  23. {
  24. FreeMemory();
  25. }
  26. void HuffmanEncodingTree::FreeMemory( void )
  27. {
  28. if ( root == 0 )
  29. return ;
  30. // Use an in-order traversal to delete the tree
  31. DataStructures::Queue<HuffmanEncodingTreeNode *> nodeQueue;
  32. HuffmanEncodingTreeNode *node;
  33. nodeQueue.Push( root, _FILE_AND_LINE_ );
  34. while ( nodeQueue.Size() > 0 )
  35. {
  36. node = nodeQueue.Pop();
  37. if ( node->left )
  38. nodeQueue.Push( node->left, _FILE_AND_LINE_ );
  39. if ( node->right )
  40. nodeQueue.Push( node->right, _FILE_AND_LINE_ );
  41. RakNet::OP_DELETE(node, _FILE_AND_LINE_);
  42. }
  43. // Delete the encoding table
  44. for ( int i = 0; i < 256; i++ )
  45. rakFree_Ex(encodingTable[ i ].encoding, _FILE_AND_LINE_ );
  46. root = 0;
  47. }
  48. ////#include <stdio.h>
  49. // Given a frequency table of 256 elements, all with a frequency of 1 or more, generate the tree
  50. void HuffmanEncodingTree::GenerateFromFrequencyTable( unsigned int frequencyTable[ 256 ] )
  51. {
  52. int counter;
  53. HuffmanEncodingTreeNode * node;
  54. HuffmanEncodingTreeNode *leafList[ 256 ]; // Keep a copy of the pointers to all the leaves so we can generate the encryption table bottom-up, which is easier
  55. // 1. Make 256 trees each with a weight equal to the frequency of the corresponding character
  56. DataStructures::LinkedList<HuffmanEncodingTreeNode *> huffmanEncodingTreeNodeList;
  57. FreeMemory();
  58. for ( counter = 0; counter < 256; counter++ )
  59. {
  60. node = RakNet::OP_NEW<HuffmanEncodingTreeNode>( _FILE_AND_LINE_ );
  61. node->left = 0;
  62. node->right = 0;
  63. node->value = (unsigned char) counter;
  64. node->weight = frequencyTable[ counter ];
  65. if ( node->weight == 0 )
  66. node->weight = 1; // 0 weights are illegal
  67. leafList[ counter ] = node; // Used later to generate the encryption table
  68. InsertNodeIntoSortedList( node, &huffmanEncodingTreeNodeList ); // Insert and maintain sort order.
  69. }
  70. // 2. While there is more than one tree, take the two smallest trees and merge them so that the two trees are the left and right
  71. // children of a new node, where the new node has the weight the sum of the weight of the left and right child nodes.
  72. #ifdef _MSC_VER
  73. #pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant
  74. #endif
  75. while ( 1 )
  76. {
  77. huffmanEncodingTreeNodeList.Beginning();
  78. HuffmanEncodingTreeNode *lesser, *greater;
  79. lesser = huffmanEncodingTreeNodeList.Pop();
  80. greater = huffmanEncodingTreeNodeList.Pop();
  81. node = RakNet::OP_NEW<HuffmanEncodingTreeNode>( _FILE_AND_LINE_ );
  82. node->left = lesser;
  83. node->right = greater;
  84. node->weight = lesser->weight + greater->weight;
  85. lesser->parent = node; // This is done to make generating the encryption table easier
  86. greater->parent = node; // This is done to make generating the encryption table easier
  87. if ( huffmanEncodingTreeNodeList.Size() == 0 )
  88. {
  89. // 3. Assign the one remaining node in the list to the root node.
  90. root = node;
  91. root->parent = 0;
  92. break;
  93. }
  94. // Put the new node back into the list at the correct spot to maintain the sort. Linear search time
  95. InsertNodeIntoSortedList( node, &huffmanEncodingTreeNodeList );
  96. }
  97. bool tempPath[ 256 ]; // Maximum path length is 256
  98. unsigned short tempPathLength;
  99. HuffmanEncodingTreeNode *currentNode;
  100. RakNet::BitStream bitStream;
  101. // Generate the encryption table. From before, we have an array of pointers to all the leaves which contain pointers to their parents.
  102. // This can be done more efficiently but this isn't bad and it's way easier to program and debug
  103. for ( counter = 0; counter < 256; counter++ )
  104. {
  105. // Already done at the end of the loop and before it!
  106. tempPathLength = 0;
  107. // Set the current node at the leaf
  108. currentNode = leafList[ counter ];
  109. do
  110. {
  111. if ( currentNode->parent->left == currentNode ) // We're storing the paths in reverse order.since we are going from the leaf to the root
  112. tempPath[ tempPathLength++ ] = false;
  113. else
  114. tempPath[ tempPathLength++ ] = true;
  115. currentNode = currentNode->parent;
  116. }
  117. while ( currentNode != root );
  118. // Write to the bitstream in the reverse order that we stored the path, which gives us the correct order from the root to the leaf
  119. while ( tempPathLength-- > 0 )
  120. {
  121. if ( tempPath[ tempPathLength ] ) // Write 1's and 0's because writing a bool will write the BitStream TYPE_CHECKING validation bits if that is defined along with the actual data bit, which is not what we want
  122. bitStream.Write1();
  123. else
  124. bitStream.Write0();
  125. }
  126. // Read data from the bitstream, which is written to the encoding table in bits and bitlength. Note this function allocates the encodingTable[counter].encoding pointer
  127. encodingTable[ counter ].bitLength = ( unsigned char ) bitStream.CopyData( &encodingTable[ counter ].encoding );
  128. // Reset the bitstream for the next iteration
  129. bitStream.Reset();
  130. }
  131. }
  132. // Pass an array of bytes to array and a preallocated BitStream to receive the output
  133. void HuffmanEncodingTree::EncodeArray( unsigned char *input, size_t sizeInBytes, RakNet::BitStream * output )
  134. {
  135. unsigned counter;
  136. // For each input byte, Write out the corresponding series of 1's and 0's that give the encoded representation
  137. for ( counter = 0; counter < sizeInBytes; counter++ )
  138. {
  139. output->WriteBits( encodingTable[ input[ counter ] ].encoding, encodingTable[ input[ counter ] ].bitLength, false ); // Data is left aligned
  140. }
  141. // Byte align the output so the unassigned remaining bits don't equate to some actual value
  142. if ( output->GetNumberOfBitsUsed() % 8 != 0 )
  143. {
  144. // Find an input that is longer than the remaining bits. Write out part of it to pad the output to be byte aligned.
  145. unsigned char remainingBits = (unsigned char) ( 8 - ( output->GetNumberOfBitsUsed() % 8 ) );
  146. for ( counter = 0; counter < 256; counter++ )
  147. if ( encodingTable[ counter ].bitLength > remainingBits )
  148. {
  149. output->WriteBits( encodingTable[ counter ].encoding, remainingBits, false ); // Data is left aligned
  150. break;
  151. }
  152. #ifdef _DEBUG
  153. RakAssert( counter != 256 ); // Given 256 elements, we should always be able to find an input that would be >= 7 bits
  154. #endif
  155. }
  156. }
  157. unsigned HuffmanEncodingTree::DecodeArray( RakNet::BitStream * input, BitSize_t sizeInBits, size_t maxCharsToWrite, unsigned char *output )
  158. {
  159. HuffmanEncodingTreeNode * currentNode;
  160. unsigned outputWriteIndex;
  161. outputWriteIndex = 0;
  162. currentNode = root;
  163. // For each bit, go left if it is a 0 and right if it is a 1. When we reach a leaf, that gives us the desired value and we restart from the root
  164. for ( unsigned counter = 0; counter < sizeInBits; counter++ )
  165. {
  166. if ( input->ReadBit() == false ) // left!
  167. currentNode = currentNode->left;
  168. else
  169. currentNode = currentNode->right;
  170. if ( currentNode->left == 0 && currentNode->right == 0 ) // Leaf
  171. {
  172. if ( outputWriteIndex < maxCharsToWrite )
  173. output[ outputWriteIndex ] = currentNode->value;
  174. outputWriteIndex++;
  175. currentNode = root;
  176. }
  177. }
  178. return outputWriteIndex;
  179. }
  180. // Pass an array of encoded bytes to array and a preallocated BitStream to receive the output
  181. void HuffmanEncodingTree::DecodeArray( unsigned char *input, BitSize_t sizeInBits, RakNet::BitStream * output )
  182. {
  183. HuffmanEncodingTreeNode * currentNode;
  184. if ( sizeInBits <= 0 )
  185. return ;
  186. RakNet::BitStream bitStream( input, BITS_TO_BYTES(sizeInBits), false );
  187. currentNode = root;
  188. // For each bit, go left if it is a 0 and right if it is a 1. When we reach a leaf, that gives us the desired value and we restart from the root
  189. for ( unsigned counter = 0; counter < sizeInBits; counter++ )
  190. {
  191. if ( bitStream.ReadBit() == false ) // left!
  192. currentNode = currentNode->left;
  193. else
  194. currentNode = currentNode->right;
  195. if ( currentNode->left == 0 && currentNode->right == 0 ) // Leaf
  196. {
  197. output->WriteBits( &( currentNode->value ), sizeof( char ) * 8, true ); // Use WriteBits instead of Write(char) because we want to avoid TYPE_CHECKING
  198. currentNode = root;
  199. }
  200. }
  201. }
  202. // Insertion sort. Slow but easy to write in this case
  203. void HuffmanEncodingTree::InsertNodeIntoSortedList( HuffmanEncodingTreeNode * node, DataStructures::LinkedList<HuffmanEncodingTreeNode *> *huffmanEncodingTreeNodeList ) const
  204. {
  205. if ( huffmanEncodingTreeNodeList->Size() == 0 )
  206. {
  207. huffmanEncodingTreeNodeList->Insert( node );
  208. return ;
  209. }
  210. huffmanEncodingTreeNodeList->Beginning();
  211. unsigned counter = 0;
  212. #ifdef _MSC_VER
  213. #pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant
  214. #endif
  215. while ( 1 )
  216. {
  217. if ( huffmanEncodingTreeNodeList->Peek()->weight < node->weight )
  218. ++( *huffmanEncodingTreeNodeList );
  219. else
  220. {
  221. huffmanEncodingTreeNodeList->Insert( node );
  222. break;
  223. }
  224. // Didn't find a spot in the middle - add to the end
  225. if ( ++counter == huffmanEncodingTreeNodeList->Size() )
  226. {
  227. huffmanEncodingTreeNodeList->End();
  228. huffmanEncodingTreeNodeList->Add( node )
  229. ; // Add to the end
  230. break;
  231. }
  232. }
  233. }
  234. #ifdef _MSC_VER
  235. #pragma warning( pop )
  236. #endif
粤ICP备19079148号