home *** CD-ROM | disk | FTP | other *** search
/ Compressed Image File Formats / CompressedImageFileFormatsJohnMiano.iso / pc / Library / source / jpenhuff.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  1998-12-17  |  12.9 KB  |  439 lines

  1. //
  2. // Copyright (c) 1997,1998 Colosseum Builders, Inc.
  3. // All rights reserved.
  4. //
  5. // Colosseum Builders, Inc. makes no warranty, expressed or implied
  6. // with regards to this software. It is provided as is.
  7. //
  8. // See the README.TXT file that came with this software for restrictions
  9. // on the use and redistribution of this file or send E-mail to
  10. // info@colosseumbuilders.com
  11. //
  12.  
  13. //
  14. // JPEG Encoder Library.
  15. //
  16. // Title:   EncoderHuffmanTable Class Implementation
  17. //
  18. // Author: John M. Miano  miano@colosseumbuilders.com
  19. //
  20. //
  21.  
  22. #include "jpenhuff.h"
  23. #include "jpegenco.h"
  24. #include "jpgexcep.h"
  25.  
  26. //
  27. //  Description:
  28. //
  29. //    Class default constructor
  30. //
  31. JpegEncoderHuffmanTable::JpegEncoderHuffmanTable ()
  32. {
  33.   Reset () ;
  34.   return ;
  35. }
  36.  
  37. //
  38. //  Description:
  39. //
  40. //    After Huffman codes have been generated the object is in a state
  41. //    where it cannot be used to create a new set of code. This function
  42. //    places the object in a state where it can be reused to generate a
  43. //    new set of Huffman Codes.
  44. //
  45.  
  46. void JpegEncoderHuffmanTable::Reset ()
  47. {
  48.   memset (frequencies, 0, sizeof (frequencies)) ;
  49.   // We add a dummy Huffman value at the end of the table with a minimumal
  50.   // frequency. Since we create the Huffman codes using the in the frequency
  51.   // table this dummy value will be assigned the longest all one huffman code.
  52.   // This ensures that no Huffman code consists entirely of 1s.
  53.   frequencies [256] = 1 ;
  54.   sizes_found = false ;
  55.   return ;
  56. }
  57.  
  58. //
  59. //  Description:
  60. //
  61. //    Function to increment the frequency for a value.
  62. //
  63. //  Parameters:
  64. //    value:  The value whose frequency is to be incremented
  65. //
  66.  
  67. void JpegEncoderHuffmanTable::IncrementFrequency (unsigned int value)
  68. {
  69.   // Once the Huffman codes have been generated for this object, the Reset()
  70.   // function must be called before we can gather data again.
  71.   if (sizes_found)
  72.     throw EJpegFatal ("INTERNAL ERROR - Huffman Code sizes already found") ;
  73.  
  74.   if (value >= JpegMaxNumberOfHuffmanCodes)
  75.     throw EJpegIndexOutOfRange () ;
  76.  
  77.   ++ frequencies [value] ;
  78.   return ;
  79. }
  80.  
  81. //
  82. //  Description:
  83. //
  84. //    This function generates the Huffman Codes using the frequency data. The code
  85. //    generation process is taken directly from the JPEG standard.
  86. //
  87. //    The outputs from this function are the following member variables:
  88. //   
  89. //     ehufsi [n] : The length of the Huffman Code for value "n"
  90. //     ehufco [n] : The Huffman Code for value "n"
  91. //     huff_bits [n] : The number of Huffman codes of length "n+1"
  92. //     huff_values [n] : The Huffman Values sorted by code length.
  93. //
  94. //    The first two arrays are used to encode Huffman values. The last two
  95. //    are for writing the table to the output file.
  96. //
  97. //    The code generation process is:
  98. //
  99. //    1. Arrange the Huffman Values into a binary tree so that the most
  100. //       frequently used codes are closest to the root of the tree. At the end
  101. //       of this process the temporary array codesize [n] contains the length
  102. //       of the pure Huffman code for the value "n"
  103. //
  104. //    2. Determine the number of Huffman Codes of for each code length. This
  105. //       step places the number of codes of length "n+1" in huff_bits[].
  106. //
  107. //    3. The JPEG standard only allows Huffman codes of up to 16-bits. If any
  108. //       codes longer than 16-bits were generated in the previous steps then
  109. //       we need to reduce the maximum depth of the tree created in step 1.
  110. //       The input and output to this step is the array huff_bits[] created in
  111. //       the previous step.
  112. //
  113. //    4. Remove the dummy all 1-bit code (See the Reset() function).
  114. //
  115. //    5. Sort the Huffman values in code length order. codesize [n] is the
  116. //       input to this step and huff_values [n] is the output. At this point
  117. //       all the information needed to write the Huffman Table to the output
  118. //       stream has been found.
  119. //
  120. //    6. Determine the code size for each value. At the end of this step
  121. //       the temporary array huffsizes [n] is the Huffman code length for
  122. //       huff_values [n].
  123. //
  124. //    7. Determine the Huffman code for each value. The temporary array
  125. //       huffcodes [n] is the Huffman Code of length huffsizes [n] for
  126. //       the value huff_value [n].
  127. //
  128. //    8. Using huffsizes [] and huffcodes created in steps 6 and 7 create
  129. //       the arrays ehufco [n] and ehufsi [n] giving the Huffman Code and
  130. //       Code Size for n.
  131. //
  132. void JpegEncoderHuffmanTable::BuildTable ()
  133. {
  134.   // We need this because MSVC++ does not support standard
  135.   // scoping in for statements.
  136.   int ii, kk ;
  137.  
  138.   // See if we have already calculated the Huffman codes.
  139.   if (sizes_found)
  140.     return ;
  141.  
  142.   // The tmp array is used for validating the integrity of the Huffman code
  143.   // table. We need a temporary array since frequencies [] gets trashed
  144.   // during the code generation process.
  145.     unsigned int tmp [JpegMaxNumberOfHuffmanCodes + 1] ;
  146.   for (ii = 0 ; ii < JpegMaxNumberOfHuffmanCodes + 1 ; ++ ii)
  147.        tmp [ii] = frequencies [ii] ;
  148.  
  149.   // Figure K.1
  150.   // Build the Huffman Code Length Lists
  151.   int others [JpegMaxNumberOfHuffmanCodes + 1] ;
  152.   for (ii = 0 ; ii < JpegMaxNumberOfHuffmanCodes + 1 ; ++ ii)
  153.     others [ii] = -1 ;
  154.  
  155.   unsigned int codesize [JpegMaxNumberOfHuffmanCodes + 1] ;
  156.   memset (codesize, 0, sizeof (codesize)) ;
  157.   while (true)
  158.   {
  159.     // Find the two smallest non-zero values
  160.     int v1 = -1 ;
  161.     int v2 = -1 ;
  162.     for (unsigned int ii = 0 ; ii < JpegMaxNumberOfHuffmanCodes + 1 ; ++ ii)
  163.     {
  164.       if (frequencies [ii] != 0)
  165.       {
  166.         // K.2 says to take the highest value value for v1 and v2
  167.         // in case of a tie. This ensures the dummy value gets
  168.         // the last Huffman code.
  169.         if (v1 < 0 || frequencies [ii] <= frequencies [v1])
  170.         {
  171.           v2 = v1 ;
  172.           v1 = ii ;
  173.         }
  174.         else if (v2 < 0 || frequencies [ii] <= frequencies [v2])
  175.         {
  176.           v2 = ii ;
  177.         }
  178.       }
  179.     }
  180.     if (v2 < 0)
  181.       break ;
  182.  
  183.     // Join the two tree nodes.
  184.     frequencies [v1] = frequencies [v1] + frequencies [v2] ;
  185.     frequencies [v2] = 0 ;
  186.  
  187.     for (++ codesize [v1] ; others [v1] >= 0 ; ++ codesize [v1])
  188.       v1 = others [v1] ;
  189.  
  190.     others [v1] = v2 ;
  191.  
  192.     for (++ codesize [v2] ; others [v2] >= 0 ; ++ codesize [v2])
  193.       v2 = others [v2] ;
  194.   }
  195.  
  196.   // Figure K.2
  197.   // Determine the number of codes of length [n]
  198.   memset (huff_bits, 0, sizeof (huff_bits)) ;
  199.   for (ii = 0 ; ii < JpegMaxNumberOfHuffmanCodes + 1 ; ++ ii)
  200.   {
  201.     if (codesize [ii] != 0)
  202.     {
  203.       ++ huff_bits [codesize [ii] - 1] ;
  204.     }
  205.   }
  206.  
  207.   // Figure K.3
  208.   // Ensure that no code is longer than 16-bits.
  209.   for (ii = 2 * JpegMaxHuffmanCodeLength -  1 ;
  210.        ii >= JpegMaxHuffmanCodeLength ;
  211.        -- ii)
  212.   {
  213.     while (huff_bits [ii] != 0)
  214.     {
  215.       unsigned int jj = ii - 1 ;
  216.       do
  217.       {
  218.         -- jj ;
  219.       }
  220.       while (huff_bits [jj] == 0) ;
  221.  
  222.       huff_bits [ii] -= 2 ;
  223.       ++ huff_bits [ii - 1] ;
  224.       huff_bits [jj + 1] += 2 ;
  225.       -- huff_bits [jj] ;
  226.     }
  227.   }
  228.  
  229.   // Remove the reserved code from the end of the list.
  230.   for (ii = JpegMaxHuffmanCodeLength - 1 ; ii >= 0 ; -- ii)
  231.   {
  232.     if (huff_bits [ii] != 0)
  233.     {
  234.       -- huff_bits [ii] ;
  235.       break ;
  236.     }
  237.   }
  238.  
  239.   // Make sure that the total number of symbols is correct.
  240.   unsigned int count = 0 ;
  241.   for (ii = 0 ; ii < JpegMaxHuffmanCodeLength ; ++ ii)
  242.   {
  243.     count += huff_bits [ii] ;
  244.   }
  245.   if (count >= JpegMaxNumberOfHuffmanCodes)
  246.     throw EJpegFatal ("INTERNAL ERROR - Too many codes defined") ;
  247.  
  248.   // Figure K.4
  249.   // Sort the values in order of code length
  250.   memset (huff_values, 0, sizeof (huff_values)) ;
  251.   for (ii = 1, kk = 0 ; ii < 2 * JpegMaxHuffmanCodeLength ; ++ ii)
  252.   {
  253.     for (unsigned int jj = 0 ; jj < JpegMaxNumberOfHuffmanCodes ; ++ jj)
  254.     {
  255.       if (codesize [jj]  == ii)
  256.       {
  257.         huff_values [kk] = jj ;
  258.         ++ kk ;
  259.       }
  260.     }
  261.   }
  262.  
  263.   // Section C.2 Figure C.1
  264.   // Convert the array "huff_bits" containing the count of codes for each
  265.   // length 1..16 into an array containing the length for each code.
  266.   unsigned int huffsizes [JpegMaxNumberOfHuffmanCodes] ;
  267.   memset (huffsizes, 0, sizeof (huffsizes)) ;
  268.   for (ii = 0, kk = 0 ; ii < JpegMaxHuffmanCodeLength ; ++ ii)
  269.   {
  270.      for (int jj = 0 ; jj < huff_bits [ii] ; ++ jj)
  271.      {
  272.         huffsizes [kk] = ii + 1 ;
  273.         ++ kk ;
  274.      }
  275.      huffsizes [kk] = 0 ;
  276.   }
  277.  
  278.   // Section C.2 Figure C.2
  279.   // Calculate the Huffman code for each Huffman value.
  280.   UBYTE2 code = 0 ;
  281.   unsigned int huffcodes [JpegMaxNumberOfHuffmanCodes] ;
  282.   memset (huffcodes, 0, sizeof (huffcodes)) ;
  283.   unsigned int si ;
  284.   for (kk = 0, si = huffsizes [0] ;
  285.        huffsizes [kk] != 0  ;
  286.        ++ si, code <<= 1)
  287.   {
  288.      for ( ; huffsizes [kk] == si ; ++ code, ++ kk)
  289.      {
  290.         huffcodes [kk] = code ;
  291.      }
  292.   }
  293.  
  294.   // Section C.2 Figure C.3
  295.   memset (ehufco, 0, sizeof (ehufco)) ;
  296.   memset (ehufsi, 0, sizeof (ehufsi)) ;
  297.   for (kk = 0 ; kk < JpegMaxNumberOfHuffmanCodes ; ++ kk)
  298.   {
  299.     if (huffsizes [kk] != 0)
  300.     {
  301.       unsigned int ii = huff_values [kk] ;
  302.       ehufco [ii] = huffcodes [kk] ;
  303.       ehufsi [ii] = huffsizes [kk] ;
  304.     }
  305.   }
  306.  
  307.   // Validations
  308.   // This remaining code is not necessary other than to ensure the
  309.   // integrity of the Huffman table that is generated.
  310.  
  311.   // Make sure each value is used exactly once.
  312.   for (ii = 0 ; ii < JpegMaxNumberOfHuffmanCodes ; ++ ii)
  313.   {
  314.     int count = 0 ;
  315.     if (tmp [ii] != 0)
  316.     {
  317.       if (ehufsi [ii] == 0)
  318.         throw EJpegFatal ("INTERNAL ERROR - Missing Huffman Code Size") ;
  319.  
  320.       for (unsigned int jj = 0 ; jj < JpegMaxNumberOfHuffmanCodes ; ++ jj)
  321.       {
  322.         if (ii == huff_values [jj] && huffsizes [jj] != 0)
  323.           ++ count ;
  324.         if (count > 1)
  325.           throw EJpegFatal ("INTERNAL ERROR - Duplicate Huffman Value") ;
  326.       }
  327.       if (count == 0)
  328.         throw EJpegFatal ("INTERNAL ERROR - Missing Huffman Value") ;
  329.     }
  330.   }
  331.  
  332.   // Ensure that each huffman code is used once annd that the values
  333.   // are in range.
  334.   for (ii = 0 ; ii < JpegMaxNumberOfHuffmanCodes ; ++ ii)
  335.   {
  336.     if (ehufsi [ii] != 0)
  337.     {
  338.       if (ehufsi [ii] > JpegMaxHuffmanCodeLength)
  339.         throw EJpegFatal ("INTERNAL ERROR - Invalid Huffman Range") ;
  340.  
  341.       for (int jj = ii + 1 ; jj < JpegMaxNumberOfHuffmanCodes ; ++ jj)
  342.       {
  343.         if (ehufco [ii] == ehufco [jj] && ehufsi [jj] != 0)
  344.           throw EJpegFatal ("INTERNAL ERROR - Duplicate Huffman Code") ;
  345.       }
  346.     }
  347.   }
  348.  
  349.   sizes_found = true ;
  350.   return ;
  351. }
  352.  
  353. //
  354. //  Description:
  355. //
  356. //    This function returns the Huffman Code and Code Size for a given value.
  357. //
  358. //  Parameters:
  359. //    value:  The value to encode
  360. //    code:   The Huffman Code
  361. //    size:   The Huffman Code Length
  362. //
  363. void JpegEncoderHuffmanTable::Encode (unsigned int value,
  364.                                       UBYTE2 &code,
  365.                                       UBYTE1 &size) const
  366. {
  367.   if (value >= JpegMaxNumberOfHuffmanCodes)
  368.     throw EJpegIndexOutOfRange () ;
  369.  
  370.   if (ehufsi [value] == 0)
  371.     throw EJpegFatal ("INTERNAL ERROR - Missing Huffman Code") ;
  372.  
  373.   code = ehufco [value] ;
  374.   size = ehufsi [value] ;
  375.   return ;
  376. }
  377.  
  378. //
  379. //  Description:
  380. //
  381. //    This function writes the Huffman table data to the output stream in the
  382. //    format specified by the JPEG standard.
  383. //
  384. //  Parameters:
  385. //    encoder:    The JpegEncoder that defines the output stream.
  386. //
  387. void JpegEncoderHuffmanTable::PrintTable (JpegEncoder &encoder) const
  388. {
  389.   // We need this declaration here because MSVC++ does not support
  390.   // standard scoping in for statements.
  391.   unsigned int ii ;
  392.  
  393.   // B.2.4.2
  394.   UBYTE1 data ;
  395.   unsigned int count = 0 ; // Number of codes in the table.
  396.  
  397.   // Write 16 1-byte values containing the count of codes for
  398.   // each possible Huffman code length and count the number of
  399.   // codes used.
  400.   for (ii = 0 ; ii < JpegMaxHuffmanCodeLength ; ++ ii)
  401.   {
  402.     count += huff_bits [ii] ;
  403.     data = huff_bits [ii] ;
  404.     encoder.OutputByte (data) ;
  405.   }
  406.  
  407.   // Write the variable length part of the table, the Huffman values
  408.   // sorted by Huffman Code.
  409.   for (ii = 0 ; ii < count ; ++ ii)
  410.   {
  411.     data = huff_values [ii] ;
  412.     encoder.OutputByte (data) ;
  413.   }
  414.   return ;
  415. }
  416. //
  417. //  Description:
  418. //
  419. //    This function determines the size of the Huffman table when it is
  420. //    written to a DHT marker. This function is used to calculate the
  421. //    2-byte marker length that comes right after the FF-DHT sequence in
  422. //    the output stream. Therefore we need to find the length before we
  423. //    actually write the table.
  424. //
  425. unsigned int JpegEncoderHuffmanTable::OutputSize () const
  426. {
  427.   unsigned int count = 0 ;
  428.   for (unsigned int ii = 0 ; ii < JpegMaxHuffmanCodeLength ; ++ ii)
  429.   {
  430.     count += huff_bits [ii] ;
  431.   }
  432.  
  433.   // 1 byte for each value + one byte for each of 16 code lengths +
  434.   // 1 byte for the table class and ID.
  435.   return count + JpegMaxHuffmanCodeLength + 1 ;
  436. }
  437.  
  438.  
  439.