home *** CD-ROM | disk | FTP | other *** search
/ Compressed Image File Formats / CompressedImageFileFormatsJohnMiano.iso / pc / Examples / c11 / src / jpegdeco.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  1998-12-22  |  40.4 KB  |  1,530 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 Decoder Class Implementation
  15. //
  16. // Author:  John M. Miano miano@colosseumbuilders.com
  17. //
  18. #include <iostream>
  19. #include "jpegdeco.h"
  20. #include "jfif.h"
  21. #include "jpdehuff.h"
  22. #include "bitimage.h"
  23. #include "jpdequan.h"
  24. #include "jpdecomp.h"
  25. #include <limits.h>
  26.  
  27. using namespace std ;
  28. //
  29. //  Description:
  30. //
  31. //    Class Default Constructor
  32. //
  33. JpegDecoder::JpegDecoder ()
  34. {
  35.   Initialize () ;
  36.   return ;
  37. }
  38. //
  39. //  Description:
  40. //
  41. //    Class copy constructor
  42. //
  43. JpegDecoder::JpegDecoder (const JpegDecoder &source)
  44. {
  45.   Initialize () ;
  46.   DoCopy (source) ;
  47.   return ;
  48. }
  49.  
  50. //
  51. //  Description:
  52. //
  53. //    Class Destructor
  54. //
  55. JpegDecoder::~JpegDecoder ()
  56. {
  57.   delete [] ac_tables ; ac_tables = NULL ;
  58.   delete [] dc_tables ; dc_tables = NULL ;
  59.  
  60.   delete [] quantization_tables ; quantization_tables = NULL ;
  61.   delete [] components ; components = NULL ;
  62.   delete [] component_indices ; component_indices = NULL ;
  63.   delete [] scan_components ; scan_components = NULL ;
  64.   return ;
  65. }
  66. //
  67. //  Description:
  68. //
  69. JpegDecoder &JpegDecoder::operator=(const JpegDecoder &source)
  70. {
  71.   DoCopy (source) ;
  72.   return *this ;
  73. }
  74.  
  75. //
  76. //  Description:
  77. //
  78. //    Class initialization procudure for use by constructors.
  79. //
  80. void JpegDecoder::Initialize ()
  81. {
  82.   verbose_flag = false ;
  83.   strict_jfif = false ;
  84.  
  85.   ac_tables = new JpegHuffmanDecoder [JpegMaxHuffmanTables] ;
  86.   dc_tables = new JpegHuffmanDecoder [JpegMaxHuffmanTables] ;
  87.  
  88.   quantization_tables = new JpegDecoderQuantizationTable [MaxQuantizationTables] ;
  89.   components = new JpegDecoderComponent [JpegMaxComponentsPerFrame] ;
  90.   component_indices = new unsigned int [JpegMaxComponentsPerFrame] ;
  91.  
  92.   scan_components = new JpegDecoderComponent * [JpegMaxComponentsPerScan] ;
  93.   return ;
  94. }
  95. //
  96. //  Description:
  97. //
  98. //    Copy function. This function is called by the assignment operator
  99. //    and copy constructor to copy the state of one object to another.
  100. //    we only copy user configurable parameters. We do not support
  101. //    copying while a decode operation is in progress.
  102. //
  103. void JpegDecoder::DoCopy (const JpegDecoder &source)
  104. {
  105.   verbose_flag = source.verbose_flag ;
  106.   strict_jfif = source.strict_jfif ;
  107.   BitmapImageCoder::operator=(source) ;
  108.   return ;
  109. }
  110. //
  111. //  Description:
  112. //
  113. //    This function returns the next byte from the input stream.
  114. //
  115. UBYTE1 JpegDecoder::ReadByte ()
  116. {
  117.   UBYTE1 value ;
  118.   input_stream->read ((char *) &value, sizeof (value)) ;
  119.   bit_position = 0 ;
  120.  
  121.   if (input_stream->eof ())
  122.     throw EJpegBadData ("Premature end of file") ;
  123.   return value ;
  124. }
  125.  
  126. //
  127. //  Description:
  128. //
  129. //    This function reads the next 2-byte integer from the input stream
  130. //    and returns the value in the correct format for the system.
  131. //
  132.  
  133. UBYTE2 JpegDecoder::ReadWord ()
  134. {
  135.   bit_position = 0 ;
  136.   UBYTE2 value ;
  137.   input_stream->read ((char *) &value, sizeof (value)) ;
  138.   return BigEndianToSystem (value) ;
  139. }
  140.  
  141. //
  142. //  Description:
  143. //
  144. //    Section F.2.2.4
  145. //
  146. //    Extracts the next "count" bits from the input stream.
  147. //
  148. int JpegDecoder::Receive (unsigned int count)
  149. {
  150.   int result = 0 ;
  151.   for (unsigned int ii = 0 ; ii < count ; ++ii)
  152.   {
  153.     result <<= 1 ;
  154.     result |= NextBit () ;
  155.   }
  156.   return result ;
  157. }
  158.  
  159. //
  160. //  Description:
  161. //
  162. //    This function reads the Start of Image Marker and the JFIF APP0
  163. //    marker that begin a JPEG file.
  164. //
  165. //    The JFIF standard states "The JPEG FIF APP0 marker is mandatory
  166. //     right after the SOI marker."
  167. //
  168. //    I have come across some JPEG files that have a COM marker between
  169. //    the SOI marker and APP0. This code will reject these non-conforming
  170. //    files.
  171. //
  172.  
  173. void JpegDecoder::ReadStreamHeader ()
  174. {
  175.   if (ReadByte () != SOB)
  176.     throw EJpegBadData ("Missing SOI Marker") ;
  177.   if (ReadByte () != SOI)
  178.     throw EJpegBadData ("Missing SOI Marker") ;
  179.   if (ReadByte () != SOB)
  180.     throw EJpegBadData ("Missing JFIF APP0 Marker") ;
  181.   if (ReadByte () != APP0)
  182.     throw EJpegBadData ("Missing JFIF APP0 Marker") ;
  183.  
  184.   JfifHeader header ;
  185.   input_stream->read ((char *) &header, sizeof (header)) ;
  186.   if (memcmp ("JFIF", (char *) header.identifier, 4) != 0)
  187.     throw EJpegBadData ("Not a JFIF file") ;
  188.  
  189.   if (verbose_flag)
  190.   {
  191.     cout << "{ Start Of Image }" << endl ;
  192.     cout << "{ JFIF APP0 Marker" << endl ;
  193.     cout << "  Length: " << dec << BigEndianToSystem (header.length) << endl ;
  194.     cout << "  Version: " << dec << (unsigned int) header.version [0]
  195.          << "." << (unsigned int) header.version [0] << endl ;
  196.     // density unit = 0 => Only the aspect ratio is specified.
  197.     // density unit = 1 => Density in pixels per inch.
  198.     // density unit = 2 => Density in pixels per centimeter.
  199.     cout << "  Density Unit: " ;
  200.     switch (header.units)
  201.     {
  202.     case 0:
  203.       cout << " (aspect ratio)" << endl ;
  204.       break ;
  205.     case 1:
  206.       cout << " (pixels per inch)" << endl ;
  207.       break ;
  208.     case 2:
  209.       cout << " (pixels/cm)" << endl ;
  210.       break ;
  211.     default:
  212.       cout << " (????)" << endl ;
  213.       break ;
  214.     }
  215.     cout << "  X Density: " << dec << BigEndianToSystem (header.xdensity) << endl ;
  216.     cout << "  Y Density: " << dec << BigEndianToSystem (header.xdensity) << endl ;
  217.     cout << "  Thumbnail Width: " << dec << (unsigned int) header.xthumbnail << endl ;
  218.     cout << "  Thumbnail Height: " << dec << (unsigned int) header.xthumbnail << endl ;
  219.     cout << "}" << endl ;
  220.   }
  221.  
  222.   // Skip over any thumbnail data.
  223.   for (int ii = sizeof (header) ; ii < BigEndianToSystem (header.length) ; ++ ii)
  224.     (void) ReadByte () ;
  225.  
  226.   return ;
  227. }
  228.  
  229. //
  230. //  Description:
  231. //
  232. //    This function reads the next marker in the input
  233. //    stream. If the marker is followed by a data block
  234. //    this function dispatches a routine to read the
  235. //    data.
  236. //
  237. void JpegDecoder::ReadMarker ()
  238. {
  239.   while (! input_stream->eof ())
  240.   {
  241.     UBYTE1 type = ReadByte () ;
  242.     switch (type)
  243.     {
  244.     case SOB:
  245.       // According to E.1.2, 0xFF is allowed as fill when a
  246.       // marker is expected.
  247.       break ;
  248.     case SOI:
  249.       if (verbose_flag)
  250.         cout << "{ Start Of Image }" << endl ;
  251.       return ; // SOI has no data.
  252.     case DQT:
  253.       ReadQuantization () ;
  254.       return ;
  255.     case DHP:
  256.       throw EJpegBadData ("DHP marker not supported") ;
  257.  
  258.     // The only difference between a Sequential DCT Frame
  259.     // (SOF0) and an extended Sequential DCT Frame (SOF1)
  260.     // is that a baseline frame may only have 2 DC and 2 AC
  261.     // Huffman tables per scan (F.1.2) and and extended
  262.     // Sequential Frame may have up to 4 DC and 4 AC Huffman
  263.     // tables per scan (F.1.3). Both are decoded identically
  264.     // for 8-bit precision. Extended Sequential frames may
  265.     // use 12-bit precision (F, Table B.2) which we do not
  266.     // support.
  267.     case SOF0:
  268.     case SOF1:
  269.     case SOF2:
  270.       ReadStartOfFrame (type) ;
  271.       return ;
  272.     case SOF3:
  273.       throw EJpegBadData ("Lossless Huffman Coding Not Supported") ;
  274.     case SOF5:
  275.       throw EJpegBadData (
  276.         "Differential Sequential Huffman Coding Not Supported") ;
  277.     case SOF6:
  278.       throw EJpegBadData (
  279.         "Differential Progressive Huffman Coding Not Supported") ;
  280.     case SOF7:
  281.       throw EJpegBadData (
  282.         "Differential Lossless Huffman Coding Not Supported") ;
  283.  
  284.     // These are markers for frames using arithmetic coding.
  285.     // Arithmetic coding is covered by patents so we ignore
  286.     // this type.
  287.     case SOF9:
  288.     case SOFA:
  289.     case SOFB:
  290.     case SOFD:
  291.     case SOFE:
  292.     case SOFF:
  293.       throw EJpegBadData (
  294.         "Cannot read image - Arithmetic Coding covered by patents") ;
  295.     case DHT:
  296.       ReadHuffmanTable () ;
  297.       return ;
  298.     case SOS:
  299.       ReadStartOfScan () ;
  300.       return ;
  301.     case DRI:
  302.       ReadRestartInterval () ;
  303.       return ;
  304.     case EOI:
  305.       eoi_found = true ;
  306.       if (verbose_flag)
  307.         cout << "{ End Of Image }" << endl ;
  308.       return ; // End of Image marker has no data
  309.     case APP0:
  310.     case APP1:
  311.     case APP2:
  312.     case APP3:
  313.     case APP4:
  314.     case APP5:
  315.     case APP6:
  316.     case APP7:
  317.     case APP8:
  318.     case APP9:
  319.     case APPA:
  320.     case APPB:
  321.     case APPC:
  322.     case APPD:
  323.     case APPE:
  324.     case APPF:
  325.     case COM:
  326.       ReadApplication (type) ;
  327.       return ;
  328.     default:
  329.       // We call ReadByte to make sure the problem
  330.       // is not a premature EOF.
  331.       (void) ReadByte () ; 
  332.       throw EJpegBadData (
  333.       "Unknown, unsupported, or reserved marker encountered") ;
  334.     }
  335.   }
  336.   throw EJpegBadData ("Premature end of file") ;
  337. }
  338.  
  339. //
  340. //  Description:
  341. //
  342. //    This method reads an application or comment marker
  343. //    from the input stream.
  344. //
  345. //  Parameters:
  346. //    type:  The marker type
  347. //
  348. void JpegDecoder::ReadApplication (UBYTE1 type)
  349. {
  350.   unsigned int length = ReadWord () ;
  351.   char id [512] ;
  352.   int ii = 0 ;
  353.  
  354.   id [ii] = ReadByte () ;
  355.   for (ii = 1 ; id [ii - 1] != '\000'
  356.                 && ii < sizeof (id)
  357.                 && ii < length - sizeof (UBYTE2) ; ++ ii)
  358.   {
  359.     id [ii] = ReadByte () ;
  360.   }
  361.  
  362.   for ( ; ii < length - sizeof (UBYTE2) ; ++ ii)
  363.     (void) ReadByte () ;
  364.  
  365.   if (verbose_flag)
  366.   {
  367.     if (type == COM)
  368.       cout << "( Comment Marker" << endl ;
  369.     else
  370.     cout << "{ APP" << hex << (UBYTE2) (type & 0x0F) << " Marker" << endl ;
  371.     cout << "Length: " << dec << length << endl ;
  372.     cout << "ID: " << id << endl ;
  373.     cout << "}" << endl ;
  374.   }
  375.   return ;
  376. }
  377.  
  378. //
  379. //  Description:
  380. //
  381. //    The function reads a Define Huffman Table marker from the input
  382. //    stream.
  383. //
  384. void JpegDecoder::ReadHuffmanTable ()
  385. {
  386.   // Section B.2.4.2
  387.  
  388.   if (verbose_flag)
  389.     cout << "{ Define Huffman Table" << endl ;
  390.  
  391.   UBYTE2 length = ReadWord () ;
  392.   unsigned int remaining = length - sizeof (length) ;
  393.   while (remaining > 0)
  394.   {
  395.     UBYTE1 data = ReadByte () ; -- remaining ;
  396.  
  397.     // Tc in standard 0=>DC, 1=>AC
  398.     unsigned int tableclass = data >> 4 ; 
  399.     unsigned int id = data & 0x0F ; // Th in standard
  400.     if (id > 3)
  401.     {
  402.       throw EJpegBadData (
  403.         "Huffman Table Index outside range [0..3]") ;
  404.     }
  405.     if (verbose_flag)
  406.     {
  407.       cout << "   Table Index " << (int) id << endl ;
  408.       if (tableclass == 0)
  409.         cout << "   Table Class: DC" << endl ;
  410.       else
  411.         cout << "   Table Class: AC" << endl ;
  412.     }
  413.     if (id > 3)
  414.     {
  415.       cout << "Bad index " << id << endl ;
  416.       return ;
  417.     }
  418.  
  419.     JpegHuffmanDecoder *table ;
  420.     if (tableclass != 0)
  421.       table = &ac_tables [id] ;
  422.     else
  423.        table = &dc_tables [id] ;
  424.  
  425.     // Read the table data into the table object
  426.     remaining -= table->ReadTable (*this) ;
  427.  
  428.     if (verbose_flag)
  429.     {
  430.       table->Dump (cout) ;
  431.     }
  432.   }
  433.  
  434.   if (verbose_flag)
  435.     cout << "}" << endl ;
  436.   return ;
  437. }
  438.  
  439. //
  440. //  Description:
  441. //
  442. //    This function reads a DQT marker from the input stream.
  443. //
  444. void JpegDecoder::ReadQuantization ()
  445. {
  446.   // Defined in Section B.2.4.1
  447.  
  448.   UBYTE2 length = ReadWord () ;
  449.   UBYTE1 data ;
  450.  
  451.   // Maintain a counter for the number of bytes remaining to be read in
  452.   // the quantization table.
  453.   int remaining = length - sizeof (length) ;
  454.  
  455.   if (verbose_flag)
  456.   {
  457.     cout << "{ Define Quantization Table" << endl ;
  458.     cout << "  Length: " << length << endl ;
  459.   }
  460.   while (remaining > 0)
  461.   {
  462.     data = ReadByte () ; -- remaining ;
  463.     unsigned int precision = data >> 4 ;    // Pq in standard
  464.     unsigned int index = data & 0x0F ;      // Tq in standard
  465.  
  466.     if (index >= MaxQuantizationTables)
  467.       throw EJpegBadData ("Quantization Table Index Too Large") ;
  468.  
  469.     if (verbose_flag)
  470.     {
  471.       cout << "  Table Index: " << dec << index << endl ;
  472.       cout << "  Table Precision: " << dec << precision << endl ;
  473.     }
  474.  
  475.     switch (precision)
  476.     {
  477.     case 1:
  478.       remaining -= sizeof(UBYTE2) * JpegSampleSize ;
  479.       break ;
  480.     case 0:
  481.       remaining -= sizeof (UBYTE1) * JpegSampleSize ;
  482.       break ;
  483.     }
  484.  
  485.     // Read the table data into the table object
  486.     quantization_tables [index].ReadTable (*this, precision) ;
  487.  
  488.     if (verbose_flag)
  489.     {
  490.       cout << "  Table Values: " ;
  491.       quantization_tables [index].Print (cout) ;
  492.       cout << endl << "}" << endl ;
  493.     }
  494.   }
  495.   return ;
  496. }
  497.  
  498. //
  499. //  Description:
  500. //
  501. //    This function reads a define restart interval marker
  502. //    from the input stream.
  503. //
  504. void JpegDecoder::ReadRestartInterval ()
  505. {
  506.   // Section B.2.4.4
  507.  
  508.   UBYTE2 length = ReadWord () ;
  509.   restart_interval = ReadWord () ;
  510.   if (verbose_flag)
  511.   {
  512.     cout << "{ Define Restart Interval" << endl ;
  513.     cout << "  Length:  " << dec << length << endl ; // Should be 4
  514.     cout << "  Interval: " << dec << restart_interval << endl ;
  515.     cout << "}" << endl ;
  516.    }
  517.    return ;
  518. }
  519.  
  520. //
  521. //  Description:
  522. //
  523. //    The function reads a start of frame marker from the input stream.
  524. //
  525. //  Parameters:
  526. //    type:  The marker type for the frame
  527. //
  528. void JpegDecoder::ReadStartOfFrame (UBYTE1 type)
  529. {
  530.   if (type == SOF2)
  531.     progressive_frame = true ;
  532.   else
  533.     progressive_frame = false ;
  534.  
  535.   // Section B.2.2
  536.   // Read in the image dimensions
  537.   unsigned int length = ReadWord () ;
  538.   unsigned int dataprecision = ReadByte () ;  // P in standard
  539.   if (dataprecision != 8)
  540.     throw EJpegBadData ("Only 8-bit data supported") ;
  541.  
  542.   frame_height = ReadWord () ;            // Y in standard
  543.   frame_width = ReadWord () ;             // X in standard
  544.   component_count = ReadByte () ;   // Nf in standard
  545.  
  546.   // JFIF only allows 1 or 3 components.
  547.   if (component_count != 1 && component_count != 3)
  548.     throw EJpegBadData ("JFIF only supports 1 and 3 component streams") ;
  549.  
  550.   frame_type = type ;
  551.  
  552.   if (verbose_flag)
  553.   {
  554.     cout << "{ Start Of Frame " << endl ;
  555.     cout << "  Length: " << dec << length << endl ;
  556.     cout << "  Precision: " << dec << dataprecision << endl ;
  557.     cout << "  Height: " << dec << frame_height << endl ;
  558.     cout << "  Width: " << dec << frame_width << endl ;
  559.     cout << "  Component Count: " << component_count << endl ;
  560.   }
  561.  
  562.   if (length != (component_count * 3 + 8))
  563.     throw EJpegBadData ("Invalid Frame Size") ;
  564.  
  565.   // Rread the component descriptions
  566.   max_horizontal_frequency = 0 ;
  567.   max_vertical_frequency = 0 ;
  568.   for (unsigned int ii = 0 ; ii < component_count ; ++ ii)
  569.   {
  570.     unsigned int ID = ReadByte () ;  // Ci in standard
  571.     unsigned int qtable ;
  572.  
  573.     // While JPEG does not put these restrictions on component IDs
  574.     // the JFIF standard does.
  575.     if (strict_jfif)
  576.     {
  577.     if (component_count == 1 && ID != 1)
  578.       throw EJpegBadData ("Component ID not 1") ;
  579.     else if (ID != ii + 1)
  580.       throw EJpegBadData ("Invalid Component ID or ID out of order") ;
  581.     }
  582.     
  583.     component_indices [ii] = ID ;
  584.  
  585.     UBYTE1 data = ReadByte () ;
  586.     components [ID].HorizontalFrequency (data >> 4) ; // Hi in standard
  587.     components [ID].VerticalFrequency (data & 0xF) ;  // Vi in standard
  588.     qtable= ReadByte () ;  // Tqi in standard
  589.     if (qtable >= MaxQuantizationTables)
  590.       throw EJpegBadData ("Bad Quantization Table Index") ;
  591.     components [ID].SetQuantizationTable (quantization_tables [qtable]) ;
  592.  
  593.     // Keep track of the largest values for horizontal and vertical
  594.     // frequency.
  595.     if (components [ID].HorizontalFrequency ()
  596.         > max_horizontal_frequency)
  597.     {
  598.       max_horizontal_frequency =
  599.         components [ID].HorizontalFrequency () ;
  600.     }
  601.  
  602.     if (components [ID].VerticalFrequency ()
  603.           > max_vertical_frequency)
  604.     {
  605.       max_vertical_frequency =
  606.         components [ID].VerticalFrequency () ;
  607.     }
  608.  
  609.     if (verbose_flag)
  610.     {
  611.       cout << "   Component " << ID << endl ;
  612.       cout << "   Horizontal Frequency: "
  613.            << components [ID].HorizontalFrequency () << endl ;
  614.       cout << "   Vertical Frequency: "
  615.            << components [ID].VerticalFrequency () << endl ;
  616.       cout << "   Quantization Table: "
  617.            << qtable << endl ;
  618.     }
  619.   }
  620.  
  621.   CalculateMcuDimensions () ;
  622.  
  623.   // Allocate storage for the image.
  624.   if (component_count == 1)
  625.   {
  626.     current_image->SetSize (1 << 8, 8, frame_width, frame_height) ;
  627.     // For a grey scale image we need to create the color map. Each color
  628.     // has equal amounts of red, green, and blue.
  629.     for (unsigned int ii = 0 ; ii < (1 << 8) ; ++ ii)
  630.     {
  631.       current_image->ColorMap (ii).red = (UBYTE1) ii ;
  632.       current_image->ColorMap (ii).green = (UBYTE1) ii ;
  633.       current_image->ColorMap (ii).blue = (UBYTE1) ii ;
  634.     }
  635.   }
  636.   else
  637.   {
  638.     current_image->SetSize (0,     // Color Table Entries
  639.                             8 * component_count,  // Bits
  640.                             frame_width,
  641.                             frame_height) ;
  642.  
  643.   }
  644.  
  645.   if (verbose_flag)
  646.     cout << "}" << endl ;
  647.  
  648.   sof_found = true ;
  649.   return ;
  650. }
  651.  
  652. //
  653. //  Description:
  654. //
  655. //    This function reads a start of scan marker and the scan data
  656. //    following the marker.
  657. //
  658. void JpegDecoder::ReadStartOfScan ()
  659. {
  660.   unsigned int ii ;
  661.  
  662.   if (! sof_found)
  663.     throw EJpegBadData ("Scan found before frame defined") ;
  664.  
  665.   // Section B.2.3
  666.  
  667.   UBYTE2 length = ReadWord () ;
  668.   if (verbose_flag)
  669.   {
  670.     cout << "{ Start Of Scan " << endl ;
  671.     cout << "  Length:  " << dec << length << endl ;
  672.   }
  673.  
  674.   scan_component_count = ReadByte () ;  // Ns in standard
  675.   // Right now we can only handle up to three components.
  676.   if (scan_component_count > 3 || scan_component_count < 1)
  677.     throw EJpegBadData ("Invalid component count in scan") ;
  678.  
  679.   for (ii = 0 ; ii < scan_component_count ; ++ ii)
  680.   {
  681.     UBYTE1 componentID = ReadByte () ;  // Csi in standard
  682.  
  683.     scan_components [ii] = &components [componentID] ;
  684.     // If the horizontal frequency is zero then the component was not
  685.     // defined in the SOFx marker.
  686.     if (scan_components [ii]->HorizontalFrequency () == 0)
  687.       throw EJpegBadData ("Component Not Defined") ;
  688.  
  689.     UBYTE1 rb = ReadByte () ;
  690.     unsigned int actable = rb & 0x0F ;
  691.     unsigned int dctable = rb >> 4 ;
  692.  
  693.     scan_components [ii]->SetHuffmanTables (
  694.                               dc_tables [dctable],
  695.                               ac_tables [actable]) ;
  696.     if (verbose_flag)
  697.     {
  698.       cout << "  Component ID: "
  699.            << dec << (unsigned int) componentID << endl ;
  700.       cout << "  DC Entropy Table: "
  701.            << dec << dctable << endl  ;
  702.       cout << "  AC Entropy Table: "
  703.            << dec << actable << endl  ;
  704.     }
  705.   }
  706.  
  707.   unsigned int spectralselectionstart = ReadByte () ; // Ss in standard
  708.   unsigned int spectralselectionend = ReadByte ()  ;  // Se in standard
  709.  
  710.   UBYTE1 ssa = ReadByte () ;
  711.   unsigned int successiveapproximationhigh = ssa >> 4 ;  // Ah in standard
  712.   unsigned int successiveapproximationlow = ssa & 0x0F ; // Al in standard
  713.  
  714.   if (verbose_flag)
  715.   {
  716.     cout << " Spectral Selection Start: "
  717.          << dec << (unsigned int) spectralselectionstart << endl ;
  718.     cout << " Spectral Selection End: "
  719.          << dec << (unsigned int) spectralselectionend << endl ;
  720.     cout << " Successive Approximation High: "
  721.          << dec << successiveapproximationhigh << endl ;
  722.     cout << " Successive Approximation Low: "
  723.          << dec << successiveapproximationlow << endl  ;
  724.     cout << "}" << endl ;
  725.   }
  726.  
  727.   for (ii = 0 ; ii < scan_component_count ; ++ ii)
  728.   {
  729.     if (progressive_frame)
  730.     {
  731.       scan_components [ii]->CheckQuantizationTable () ;
  732.       if (spectralselectionstart == 0)
  733.         scan_components [ii]->CheckDcTable () ;
  734.       else
  735.         scan_components [ii]->CheckAcTable () ;
  736.     }
  737.     else
  738.     {
  739.       scan_components [ii]->CheckQuantizationTable () ;
  740.       scan_components [ii]->CheckDcTable () ;
  741.       scan_components [ii]->CheckAcTable () ;
  742.     }
  743.     scan_components [ii]->AllocateComponentBuffers (*this) ;
  744.  
  745.   }
  746.  
  747.   ++ current_scan ;
  748.   if (progressive_frame)
  749.   {
  750.     ReadProgressiveScanData (
  751.                           spectralselectionstart,
  752.                           spectralselectionend,
  753.                           successiveapproximationhigh,
  754.                           successiveapproximationlow) ;
  755.   }
  756.   else
  757.   {
  758.     ReadSequentialScanData () ;
  759.   }
  760.  
  761.   CallProgressFunction (100) ;
  762.   return ;
  763. }
  764.  
  765. //
  766. //  Description:
  767. //
  768. //    This function determines for non-interlaced scans:
  769. //
  770. //     o The dimensions in pixels for an MCU
  771. //     o The number of MCU rows and columns needed to encode the scan.
  772. //
  773. void JpegDecoder::CalculateMcuDimensions ()
  774. {
  775.   mcu_height = max_vertical_frequency * JpegSampleWidth ;
  776.   mcu_width = max_horizontal_frequency * JpegSampleWidth ;
  777.   mcu_rows = (frame_height + mcu_height - 1) / mcu_height ;
  778.   mcu_cols = (frame_width + mcu_width - 1) / mcu_width ;
  779.   return ;
  780. }
  781.  
  782. //
  783. //  Dimensions:
  784. //
  785. //    This function calls the progress function if it has
  786. //    been supplied by the user.
  787. //
  788. //  Parameters:
  789. //    progress: The progress percentage.
  790. //
  791. void JpegDecoder::CallProgressFunction (unsigned int progress)
  792. {
  793.   if (progress_function == NULL)
  794.     return ;
  795.  
  796.   bool abort = false ;
  797.   unsigned int percent = progress ;
  798.   if (percent > 100)
  799.     percent = 100 ;
  800.   if (progress_function != NULL)
  801.   {
  802.     progress_function (*this,
  803.                        progress_data,
  804.                        current_scan,
  805.                        scan_count,
  806.                        percent,
  807.                        abort) ;
  808.   }
  809.  
  810.   if (abort)
  811.     throw EJpegAbort () ;
  812.   return ;
  813. }
  814.  
  815. //
  816. //  Description:
  817. //
  818. //    This function reads the scan data for progressive scans.
  819. //
  820. //    All we do here is determine if we are processing a DC
  821. //    scan (sss==sse==0) or AC scan and if we are processing
  822. //    the first scan for the spectral selection (sah==0) or
  823. //    subsequent scan.
  824. //
  825. //  Parameters:
  826. //    sss: Spectral Selection Start (0..63)
  827. //    sse: Spectral Selection End (sse..63)
  828. //    sah: Successive Approximation High
  829. //    sal: Successive Approximation Low
  830. //
  831. void JpegDecoder::ReadProgressiveScanData (unsigned int sss, unsigned int sse,
  832.                                            unsigned int sah, unsigned int sal)
  833. {
  834.   if (sss == 0)
  835.   {
  836.     if (sse != 0)
  837.       throw EJpegBadData ("Progressive scan contains DC and AC data") ;
  838.  
  839.     if (sah == 0)
  840.     {
  841.       ReadDcFirst (sal) ;
  842.     }
  843.     else
  844.     {
  845.       ReadDcRefine (sal) ;
  846.     }
  847.   }
  848.   else
  849.   {
  850.     if (sah == 0)
  851.     {
  852.       ReadAcFirst (sss, sse, sal) ;
  853.     }
  854.     else
  855.     {
  856.       ReadAcRefine (sss, sse, sal) ;
  857.     }
  858.   }
  859.   return ;
  860. }
  861.  
  862. //
  863. //  Description:
  864. //
  865. //    This funtion reads the scan data for the first DC scan for
  866. //    one or more components.
  867. //
  868. //  Parameters:
  869. //
  870. //    ssa:  Successive Approximation
  871. //
  872. void JpegDecoder::ReadDcFirst (unsigned int ssa)
  873. {
  874.   ResetDcDifferences () ;
  875.   unsigned int restartcount = 0 ;
  876.  
  877.   if (ScanIsInterleaved ())
  878.   {
  879.     for (unsigned int mcurow = 0 ;
  880.          mcurow < mcu_rows ;
  881.          ++ mcurow)
  882.     {
  883.       CallProgressFunction (mcurow * 100 / mcu_rows) ;
  884.       for (unsigned int mcucol = 0 ;
  885.            mcucol < mcu_cols ;
  886.            ++ mcucol, ++restartcount)
  887.       {
  888.         if (restart_interval != 0
  889.             && restart_interval == restartcount)
  890.         {
  891.           ResetDcDifferences () ;
  892.           ProcessRestartMarker () ;
  893.           restartcount = 0 ;
  894.         }
  895.         for (unsigned int cc = 0 ; cc < scan_component_count ; ++ cc)
  896.         {
  897.           for (unsigned int cy = 0 ;
  898.                cy < scan_components [cc]->VerticalFrequency () ;
  899.                ++ cy)
  900.           {
  901.             unsigned int durow = scan_components [cc]->VerticalFrequency ()
  902.                                  * mcurow + cy ;
  903.             for (unsigned int cx = 0 ;
  904.                  cx < scan_components [cc]->HorizontalFrequency () ;
  905.                  ++ cx)
  906.             {
  907.               unsigned int ducol = scan_components [cc]->HorizontalFrequency ()
  908.                                    * mcucol + cx ;
  909.  
  910.               scan_components [cc]->DecodeDcFirst (*this, durow, ducol, ssa) ;
  911.             }
  912.           }
  913.         }
  914.       }
  915.     }
  916.   }
  917.   else
  918.   {
  919.     for (unsigned int row = 0 ;
  920.          row < scan_components [0]->NoninterleavedRows () ;
  921.          ++ row)
  922.     {
  923.       CallProgressFunction (row * 100 / scan_components [0]->NoninterleavedRows ()) ;
  924.       for (unsigned int col = 0 ;
  925.            col < scan_components [0]->NoninterleavedCols () ;
  926.            ++ col, ++restartcount)
  927.       {
  928.         if (restart_interval != 0 && restart_interval == restartcount)
  929.         {
  930.           ResetDcDifferences () ;
  931.           ProcessRestartMarker () ;
  932.           restartcount = 0 ;
  933.         }
  934.         scan_components [0]->DecodeDcFirst (*this, row, col, ssa) ;
  935.       }
  936.     }
  937.   }
  938.   return ;
  939. }
  940.  
  941. //
  942. //  Description:
  943. //
  944. //    This function reads the scan data for a refining DC scan.
  945. //
  946. //  Parameters:
  947. //    ssa:  The successive approximation value for this scan.
  948. //
  949. void JpegDecoder::ReadDcRefine (unsigned int ssa)
  950. {
  951.   ResetDcDifferences () ;
  952.   unsigned int restartcount = 0 ;
  953.  
  954.   if (ScanIsInterleaved ())
  955.   {
  956.     for (unsigned int mcurow = 0 ; mcurow < mcu_rows ; ++ mcurow)
  957.     {
  958.       CallProgressFunction (mcurow * 100 / mcu_rows) ;
  959.       for (unsigned int mcucol = 0 ;
  960.            mcucol < mcu_cols ;
  961.            ++ mcucol, ++restartcount)
  962.       {
  963.         if (restart_interval != 0 && restart_interval == restartcount)
  964.         {
  965.           ResetDcDifferences () ;
  966.           ProcessRestartMarker () ;
  967.           restartcount = 0 ;
  968.         }
  969.         for (unsigned int cc = 0 ; cc < scan_component_count ; ++ cc)
  970.         {
  971.           for (unsigned int cy = 0 ;
  972.                cy < scan_components [cc]->VerticalFrequency () ;
  973.                ++ cy)
  974.           {
  975.             unsigned int durow = scan_components [cc]->VerticalFrequency ()
  976.                                  * mcurow + cy ;
  977.             for (unsigned int cx = 0 ;
  978.                  cx < scan_components [cc]->HorizontalFrequency () ;
  979.                  ++ cx)
  980.             {
  981.               unsigned int ducol = scan_components [cc]->HorizontalFrequency ()
  982.                                    * mcucol + cx ;
  983.  
  984.               scan_components [cc]->DecodeDcRefine (*this, durow, ducol, ssa) ;
  985.             }
  986.           }
  987.         }
  988.       }
  989.     }
  990.   }
  991.   else
  992.   {
  993.     for (unsigned int row = 0 ;
  994.          row < scan_components [0]->NoninterleavedRows () ;
  995.          ++ row)
  996.     {
  997.       CallProgressFunction (row * 100 / scan_components [0]->NoninterleavedRows ()) ;
  998.       for (unsigned int col = 0 ;
  999.            col < scan_components [0]->NoninterleavedCols () ;
  1000.            ++ col, ++restartcount)
  1001.       {
  1002.         if (restart_interval != 0 && restart_interval == restartcount)
  1003.         {
  1004.           ResetDcDifferences () ;
  1005.           ProcessRestartMarker () ;
  1006.           restartcount = 0 ;
  1007.         }
  1008.         scan_components [0]->DecodeDcRefine (*this, row, col, ssa) ;
  1009.       }
  1010.     }
  1011.   }
  1012.   return ;
  1013. }
  1014.  
  1015. //
  1016. //  Description:
  1017. //
  1018. //    This function reads the scan data for the first AC scan for a
  1019. //    component. Progressive scans that read AC data cannot be
  1020. //    interleaved.
  1021. //
  1022. //  Parameters:
  1023. //    sss:  Spectral Selection Start
  1024. //    sse:  Spectral Selection End
  1025. //    ssa:  Spectral Selection
  1026. //
  1027.  
  1028. void JpegDecoder::ReadAcFirst (unsigned int sss,
  1029.                                unsigned int sse,
  1030.                                unsigned int ssa)
  1031. {
  1032.   ResetDcDifferences () ;
  1033.  
  1034.   unsigned int restartcount = 0 ;
  1035.   for (unsigned int row = 0 ;
  1036.        row < scan_components [0]->NoninterleavedRows () ;
  1037.        ++ row)
  1038.   {
  1039.     CallProgressFunction (row * 100 / scan_components [0]->NoninterleavedRows ()) ;
  1040.     for (unsigned int col = 0 ;
  1041.          col < scan_components [0]->NoninterleavedCols () ;
  1042.          ++ col, ++restartcount)
  1043.     {
  1044.       if (restart_interval != 0 && restart_interval == restartcount)
  1045.       {
  1046.         ResetDcDifferences () ;
  1047.         ProcessRestartMarker () ;
  1048.         restartcount = 0 ;
  1049.       }
  1050.       scan_components [0]->DecodeAcFirst (*this,
  1051.                                           row, col,
  1052.                                           sss, sse,
  1053.                                           ssa) ;
  1054.     }
  1055.   }
  1056.   return ;
  1057. }
  1058.  
  1059. //
  1060. //  Description:
  1061. //
  1062. //    This function reads the scan data for a refining AC scan for a
  1063. //    component. Progressive scans that read AC data cannot be
  1064. //    interleaved.
  1065. //
  1066. //  Parameters:
  1067. //    sss:  Spectral Selection Start
  1068. //    sse:  Spectral Selection End
  1069. //    ssa:  Spectral Selection
  1070. //
  1071.  
  1072. void JpegDecoder::ReadAcRefine (unsigned int sss,
  1073.                                 unsigned int sse,
  1074.                                 unsigned int ssa)
  1075. {
  1076.   ResetDcDifferences () ;
  1077.  
  1078.   unsigned int restartcount = 0 ;
  1079.   for (unsigned int row = 0 ;
  1080.        row < scan_components [0]->NoninterleavedRows () ;
  1081.        ++ row)
  1082.   {
  1083.     CallProgressFunction (row * 100 / scan_components [0]->NoninterleavedRows ()) ;
  1084.     for (unsigned int col = 0 ;
  1085.          col < scan_components [0]->NoninterleavedCols () ;
  1086.          ++ col, ++restartcount)
  1087.     {
  1088.       if (restart_interval != 0 && restart_interval == restartcount)
  1089.       {
  1090.         ResetDcDifferences () ;
  1091.         ProcessRestartMarker () ;
  1092.         restartcount = 0 ;
  1093.       }
  1094.       scan_components [0]->DecodeAcRefine (*this,
  1095.                                            row, col,
  1096.                                            sss, sse,
  1097.                                            ssa) ;
  1098.     }
  1099.   }
  1100.   return ;
  1101. }
  1102.  
  1103. //
  1104. //  Parameters:
  1105. //
  1106. //    The function reads the scan data for a sequential scan. All
  1107. //    we do here is determine whether or not we have an interleaved
  1108. //    or non-interleaved scan then call a function that handles
  1109. //    the scan type.
  1110.  
  1111. void JpegDecoder::ReadSequentialScanData ()
  1112. {
  1113.   expected_restart = 0 ;
  1114.   if (ScanIsInterleaved ())
  1115.   {
  1116.     ReadSequentialInterleavedScan () ;
  1117.   }
  1118.   else
  1119.   {
  1120.     ReadSequentialNonInterleavedScan () ;
  1121.   }
  1122.   return ;
  1123. }
  1124.  
  1125. //
  1126. //  Description:
  1127. //
  1128. //    This function reads the scan data for an interleaved scan.
  1129. //
  1130.  
  1131. void JpegDecoder::ReadSequentialInterleavedScan ()
  1132. {
  1133.   ResetDcDifferences () ;
  1134.  
  1135.   unsigned int restartcount = 0 ;
  1136.   for (unsigned int mcurow = 0 ; mcurow < mcu_rows ; ++ mcurow)
  1137.   {
  1138.     CallProgressFunction (mcurow * 100 / mcu_rows) ;
  1139.     for (unsigned int mcucol = 0 ; mcucol < mcu_cols ;
  1140.          ++ mcucol, ++restartcount)
  1141.     {
  1142.       if (restart_interval != 0 && restart_interval == restartcount)
  1143.       {
  1144.         ProcessRestartMarker () ;
  1145.         restartcount = 0 ;
  1146.       }
  1147.       for (unsigned int cc = 0 ; cc < scan_component_count ; ++ cc)
  1148.       {
  1149.         for (unsigned int cy = 0 ;
  1150.              cy < scan_components [cc]->VerticalFrequency () ;
  1151.              ++ cy)
  1152.         {
  1153.           unsigned int durow = scan_components [cc]->VerticalFrequency ()
  1154.                                * mcurow + cy ;
  1155.           for (unsigned int cx = 0 ;
  1156.                cx < scan_components [cc]->HorizontalFrequency () ;
  1157.                ++ cx)
  1158.           {
  1159.             unsigned int ducol =
  1160.                    scan_components [cc]->HorizontalFrequency ()
  1161.                    * mcucol + cx ;
  1162.  
  1163.             scan_components [cc]->DecodeSequential (
  1164.                                       *this,
  1165.                                       durow,
  1166.                                       ducol) ;
  1167.           }
  1168.         }
  1169.       }
  1170.     }
  1171.   }
  1172.   return ;
  1173. }
  1174.  
  1175. //
  1176. //  Description:
  1177. //
  1178. //    This function reads the scan data for a non-interleaved scan.
  1179. //
  1180.  
  1181. void JpegDecoder::ReadSequentialNonInterleavedScan ()
  1182. {
  1183.   ResetDcDifferences () ;
  1184.  
  1185.   unsigned int restartcount = 0 ;
  1186.   for (unsigned int row = 0 ;
  1187.        row < scan_components [0]->NoninterleavedRows () ;
  1188.        ++ row)
  1189.   {
  1190.     CallProgressFunction (row * 100 / scan_components [0]->NoninterleavedRows ()) ;
  1191.     for (unsigned int col = 0 ;
  1192.          col < scan_components [0]->NoninterleavedCols () ;
  1193.          ++ col, ++ restartcount)
  1194.     {
  1195.       if (restart_interval != 0
  1196.           && restart_interval == restartcount)
  1197.       {
  1198.         ProcessRestartMarker () ;
  1199.         restartcount = 0 ;
  1200.       }
  1201.       scan_components [0]->DecodeSequential (*this, row, col) ;
  1202.     }
  1203.   }
  1204.   return ;
  1205. }
  1206.  
  1207. //
  1208. //  Description:
  1209. //
  1210. //    This function resets the DC difference values for all components
  1211. //    for the current scan.
  1212. //
  1213. //    This function gets called before each scan is processed and
  1214. //    whenever a restart marker is read.
  1215. //
  1216.  
  1217. void JpegDecoder::ResetDcDifferences ()
  1218. {
  1219.   for (unsigned int ii = 0 ; ii < scan_component_count ; ++ ii)
  1220.     scan_components [ii]->ResetDcDifference () ;
  1221.   return ;
  1222. }
  1223.  
  1224. //
  1225. //  Description:
  1226. //
  1227. //    This function reads a restart marker from the input stream.
  1228. //    It gets called byte functions that read scan data whenever
  1229. //    a restart marker is expected. An exception is raise if the
  1230. //    correct restart marker is not next in the input stream.
  1231. //
  1232. void JpegDecoder::ProcessRestartMarker ()
  1233. {
  1234.   UBYTE1 data = ReadByte () ;
  1235.   if (data != 0xFF)
  1236.     throw EJpegBadData ("Missing Restart Marker") ;
  1237.   // According to E.1.2 0xFF can be used as a fill character
  1238.   // before the marker.
  1239.   while (data == 0xFF)
  1240.     data = ReadByte () ;
  1241.   if (data < RST0 || data > RST7)
  1242.     throw EJpegBadData ("Missing Restart Marker") ;
  1243.  
  1244.   // Restart markers RST0..RST7 should come in sequence.
  1245.   if ((0x0F & data) != expected_restart)
  1246.     throw EJpegBadData ("Incorrect Restart Marker") ;
  1247.  
  1248.   // Move the counter to the next restart marker
  1249.   ++ expected_restart ;
  1250.   expected_restart %= 8 ;
  1251.  
  1252.   // Reset the DC coefficent differences to zero.
  1253.   ResetDcDifferences () ;
  1254.   return ;
  1255. }
  1256.  
  1257. //
  1258. //  Description:
  1259. //
  1260. //    This function reads an image from a JPEG stream. The
  1261. //    stream needs to have been opened in binary mode.
  1262. //
  1263. //  Parameters:
  1264. //    istrm: Input stream
  1265. //    image: The output image
  1266. //
  1267.  
  1268. void JpegDecoder::ReadImage (std::istream &istrm,
  1269.                              BitmapImage &image)
  1270. {
  1271.   unsigned char data ;
  1272.  
  1273.   current_scan = 0 ;
  1274.   scan_count = 0 ;
  1275.   input_stream = &istrm ;
  1276.   current_image = &image ;
  1277.  
  1278.   if (progress_function != NULL)
  1279.     GetScanCount () ;
  1280.  
  1281.   restart_interval = 0 ;  // Clear the restart interval ;
  1282.   try
  1283.   {
  1284.     current_image->Clear () ;
  1285.     eoi_found = false ;
  1286.     sof_found = false ;
  1287.  
  1288.     // Read the required SOI and APP0 markers at the start of the image.
  1289.     ReadStreamHeader () ;
  1290.  
  1291.     data = ReadByte () ;
  1292.     while (! input_stream->eof () && ! eoi_found)
  1293.     {
  1294.       if (data == SOB)
  1295.       {
  1296.         ReadMarker () ;
  1297.         if (eoi_found)
  1298.           break ;
  1299.       }
  1300.       data = ReadByte () ;
  1301.       if (input_stream->eof ())
  1302.         throw EJpegBadData ("Premature end of file") ;
  1303.     }
  1304.   }
  1305.   catch (EJpegAbort)
  1306.   {
  1307.     FreeAllocatedResources () ;
  1308.     current_image = NULL ;
  1309.   }
  1310.   catch (...)
  1311.   {
  1312.     UpdateImage () ;
  1313.     FreeAllocatedResources () ;
  1314.     current_image = NULL ;
  1315.     throw ;
  1316.   }
  1317.   UpdateImage () ;
  1318.  
  1319.   if (! eoi_found)
  1320.   {
  1321.     throw EJpegBadData("End of Image Marker Not Found") ;
  1322.   }
  1323.   // We do no want an exception so do not call ReadByte ()
  1324.   // Sometimes there can be trailing end of record markers.
  1325.   input_stream->read ((char *) &data, sizeof (data)) ;
  1326.   while ((data == '\r' || data == '\n') && ! input_stream->eof ())
  1327.     input_stream->read ((char *) &data, sizeof (data)) ;
  1328.   if (! input_stream->eof ())
  1329.   {
  1330.     throw EJpegBadData ("Extra Data After End of Image Marker") ;
  1331.   }
  1332.  
  1333.   FreeAllocatedResources () ;
  1334.   current_image = NULL ;
  1335.   return ;
  1336. }
  1337.  
  1338. //
  1339. //  Description:
  1340. //
  1341. //    This function scans a stream and counts the number of scans.  This
  1342. //    allows an exact count for a progress function.
  1343. //
  1344. void JpegDecoder::GetScanCount ()
  1345. {
  1346.   // Save the stream position so we can go back
  1347.   // when we are finished.
  1348.   long startpos = input_stream->tellg () ;
  1349.  
  1350.   // Count the number of SOS markers.
  1351.   scan_count = 0 ;
  1352.   while (! input_stream->eof ())
  1353.   {
  1354.     UBYTE1 data ;
  1355.     input_stream->read ((char *) &data, 1) ;
  1356.     if (data == SOB)
  1357.     {
  1358.       while (data == SOB)
  1359.       {
  1360.         input_stream->read ((char *) &data, 1) ;
  1361.       }
  1362.       if (data == SOS)
  1363.         ++ scan_count ;
  1364.       else if (data == EOI)
  1365.         break ;
  1366.     }
  1367.   }
  1368.   // Go back to where we were in the stream.
  1369.   input_stream->seekg (startpos) ;
  1370.   input_stream->clear () ;  // Clear the EOF flag.
  1371.   return ;
  1372. }
  1373.  
  1374. //
  1375. //  Description:
  1376. //
  1377. //    This function writes the image data that has been read so
  1378. //    far to the image. This function gets called after reading
  1379. //    the entire image stream.  The user can also call this function
  1380. //    from a progress function to display progressive images,
  1381. //    multi-scan sequential images, or just to display the image
  1382. //    as it is being read (slow).
  1383. //
  1384.  
  1385. void JpegDecoder::UpdateImage ()
  1386. {
  1387.   if (current_image == NULL)
  1388.     throw EJpegError ("Not reading an image") ;
  1389.  
  1390.   if (progressive_frame)
  1391.   {
  1392.     for (unsigned int ii = 0 ; ii < component_count ; ++ ii)
  1393.     {
  1394.       components [component_indices [ii]].ProgressiveInverseDct () ;
  1395.       components [component_indices [ii]].Upsample () ;
  1396.     }
  1397.   }
  1398.   else
  1399.   {
  1400.     for (int ii = 0 ; ii < component_count ; ++ ii)
  1401.     {
  1402.       components [component_indices [ii]].Upsample () ;
  1403.     }
  1404.   }
  1405.  
  1406.   switch (component_count)
  1407.   {
  1408.   case 3:
  1409.     JpegDecoderComponent::RGBConvert (components [component_indices [0]],
  1410.                                       components [component_indices [1]],
  1411.                                       components [component_indices [2]],
  1412.                                       *current_image) ;
  1413.     break ;
  1414.   case 1:
  1415.     JpegDecoderComponent::GrayscaleConvert (
  1416.                              components [component_indices [0]],
  1417.                              *current_image) ;
  1418.     break ;
  1419.   }
  1420.   return ;
  1421. }
  1422.  
  1423. //
  1424. //  Description:
  1425. //
  1426. //    This function frees all the memory dynamically allocated
  1427. //    during the image decoding process.  
  1428. //
  1429. void JpegDecoder::FreeAllocatedResources ()
  1430. {
  1431.   for (unsigned int ii = 0 ; ii < component_count ; ++ ii)
  1432.   {
  1433.     components [component_indices [ii]].FreeComponentBuffers () ;
  1434.   }
  1435.   return ;
  1436. }
  1437.  
  1438. //
  1439. //  Description:
  1440. //
  1441. //    This function is only used in progressive images. It refines
  1442. //    a non-zero AC coefficient. It is called at various times while
  1443. //    processing a progressive scan that refines AC coefficients.
  1444. //
  1445. //  Parameters:
  1446. //    value: (in/out) The value to refine
  1447. //    ssa: The succesive approximation for the scan.
  1448. //    decoder: The JPEG decoder
  1449. //
  1450.  
  1451. void JpegDecoder::RefineAcCoefficient (BYTE2 &value, unsigned int ssa)
  1452. {
  1453.   // Section G.1.2.3
  1454.   if (value > 0)
  1455.   {
  1456.     if (Receive (1) != 0)
  1457.     {
  1458.       value += (1 << ssa) ;
  1459.     }
  1460.   }
  1461.   else if (value < 0)
  1462.   {
  1463.     if (Receive (1) != 0)
  1464.     {
  1465.       value += (-1 << ssa) ;
  1466.     }
  1467.   }
  1468.   return ;
  1469. }
  1470.  
  1471. //
  1472. //  Description:
  1473. //
  1474. //    This function returns the next raw bit in the input stream.
  1475. //
  1476. //    Bits are read from high order to low.
  1477. //
  1478. //  Return Value:
  1479. //
  1480. //    The next bit (0, 1)
  1481. //
  1482.  
  1483. // This function returns the next bit in the input stream.
  1484. int JpegDecoder::NextBit ()
  1485. {
  1486.   // Section F.2.2.5 Figure F.18.
  1487.   // CNT is called bitposition
  1488.   // B is called bitdata
  1489.   if (bit_position == 0)
  1490.   {
  1491.     // We are out of data so read the next byte from the input stream.
  1492.     input_stream->read ((char *) &bit_data, sizeof (bit_data)) ;
  1493.     if (input_stream->eof ())
  1494.       throw EJpegBadData ("Premature end of file") ;
  1495.     // Reset the bit read position starting with the highest order bit. We
  1496.     // read high to low.
  1497.     bit_position = CHAR_BIT * sizeof (bit_data) ;
  1498.  
  1499.     if (bit_data == 0xFF)
  1500.     {
  1501.       // 0xFF could start a marker. The sequence 0xFF, 0x00 is used to
  1502.       // to represent the value 0xFF. The only other marker that is legal
  1503.       // at this point is a DNL marker.
  1504.       UBYTE1 b2 ;
  1505.       input_stream->read ((char *) &b2, 1) ;
  1506.       if (input_stream->eof ())
  1507.         throw EJpegBadData ("Premature end of file") ;
  1508.       if (b2 != 0)
  1509.       {
  1510.         if (b2 == DNL)
  1511.         {
  1512.           // DNL markers should not occur within the supported frame types.
  1513.           throw EJpegBadData ("Unexpected Marker DNL") ;
  1514.         }
  1515.         else
  1516.         {
  1517.           throw EJpegBadData ("Unexpected Marker") ;
  1518.         }
  1519.       }
  1520.     }
  1521.   }
  1522.  
  1523.   // Consume one bit of the input.
  1524.   -- bit_position ;
  1525.   // Shift the value to the low order bit position.
  1526.   UBYTE1 result = (UBYTE1) ((bit_data >> bit_position) & 1) ;
  1527.   return result ;
  1528. }
  1529.  
  1530.