home *** CD-ROM | disk | FTP | other *** search
/ Compressed Image File Formats / CompressedImageFileFormatsJohnMiano.iso / pc / Examples / c08 / src / jpegdeco.cpp < prev   
Encoding:
C/C++ Source or Header  |  1998-12-23  |  31.0 KB  |  1,174 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.       ReadStartOfFrame (type) ;
  270.       return ;
  271.     case SOF2:
  272.       throw EJpegBadData ("Progressive JPEG Not Supported") ;
  273.     case SOF3:
  274.       throw EJpegBadData ("Lossless Huffman Coding Not Supported") ;
  275.     case SOF5:
  276.       throw EJpegBadData (
  277.         "Differential Sequential Huffman Coding Not Supported") ;
  278.     case SOF6:
  279.       throw EJpegBadData (
  280.         "Differential Progressive Huffman Coding Not Supported") ;
  281.     case SOF7:
  282.       throw EJpegBadData (
  283.         "Differential Lossless Huffman Coding Not Supported") ;
  284.  
  285.     // These are markers for frames using arithmetic coding.
  286.     // Arithmetic coding is covered by patents so we ignore
  287.     // this type.
  288.     case SOF9:
  289.     case SOFA:
  290.     case SOFB:
  291.     case SOFD:
  292.     case SOFE:
  293.     case SOFF:
  294.       throw EJpegBadData (
  295.         "Cannot read image - Arithmetic Coding covered by patents") ;
  296.     case DHT:
  297.       ReadHuffmanTable () ;
  298.       return ;
  299.     case SOS:
  300.       ReadStartOfScan () ;
  301.       return ;
  302.     case DRI:
  303.       ReadRestartInterval () ;
  304.       return ;
  305.     case EOI:
  306.       eoi_found = true ;
  307.       if (verbose_flag)
  308.         cout << "{ End Of Image }" << endl ;
  309.       return ; // End of Image marker has no data
  310.     case APP0:
  311.     case APP1:
  312.     case APP2:
  313.     case APP3:
  314.     case APP4:
  315.     case APP5:
  316.     case APP6:
  317.     case APP7:
  318.     case APP8:
  319.     case APP9:
  320.     case APPA:
  321.     case APPB:
  322.     case APPC:
  323.     case APPD:
  324.     case APPE:
  325.     case APPF:
  326.     case COM:
  327.       ReadApplication (type) ;
  328.       return ;
  329.     default:
  330.       // We call ReadByte to make sure the problem
  331.       // is not a premature EOF.
  332.       (void) ReadByte () ; 
  333.       throw EJpegBadData (
  334.       "Unknown, unsupported, or reserved marker encountered") ;
  335.     }
  336.   }
  337.   throw EJpegBadData ("Premature end of file") ;
  338. }
  339.  
  340. //
  341. //  Description:
  342. //
  343. //    This method reads an application or comment marker
  344. //    from the input stream.
  345. //
  346. //  Parameters:
  347. //    type:  The marker type
  348. //
  349. void JpegDecoder::ReadApplication (UBYTE1 type)
  350. {
  351.   unsigned int length = ReadWord () ;
  352.   char id [512] ;
  353.   int ii = 0 ;
  354.  
  355.   id [ii] = ReadByte () ;
  356.   for (ii = 1 ; id [ii - 1] != '\000'
  357.                 && ii < sizeof (id)
  358.                 && ii < length - sizeof (UBYTE2) ; ++ ii)
  359.   {
  360.     id [ii] = ReadByte () ;
  361.   }
  362.  
  363.   for ( ; ii < length - sizeof (UBYTE2) ; ++ ii)
  364.     (void) ReadByte () ;
  365.  
  366.   if (verbose_flag)
  367.   {
  368.     if (type == COM)
  369.       cout << "( Comment Marker" << endl ;
  370.     else
  371.     cout << "{ APP" << hex << (UBYTE2) (type & 0x0F) << " Marker" << endl ;
  372.     cout << "Length: " << dec << length << endl ;
  373.     cout << "ID: " << id << endl ;
  374.     cout << "}" << endl ;
  375.   }
  376.   return ;
  377. }
  378.  
  379. //
  380. //  Description:
  381. //
  382. //    The function reads a Define Huffman Table marker from the input
  383. //    stream.
  384. //
  385. void JpegDecoder::ReadHuffmanTable ()
  386. {
  387.   // Section B.2.4.2
  388.  
  389.   if (verbose_flag)
  390.     cout << "{ Define Huffman Table" << endl ;
  391.  
  392.   UBYTE2 length = ReadWord () ;
  393.   unsigned int remaining = length - sizeof (length) ;
  394.   while (remaining > 0)
  395.   {
  396.     UBYTE1 data = ReadByte () ; -- remaining ;
  397.  
  398.     // Tc in standard 0=>DC, 1=>AC
  399.     unsigned int tableclass = data >> 4 ; 
  400.     unsigned int id = data & 0x0F ; // Th in standard
  401.     if (id > 3)
  402.     {
  403.       throw EJpegBadData (
  404.         "Huffman Table Index outside range [0..3]") ;
  405.     }
  406.     if (verbose_flag)
  407.     {
  408.       cout << "   Table Index " << (int) id << endl ;
  409.       if (tableclass == 0)
  410.         cout << "   Table Class: DC" << endl ;
  411.       else
  412.         cout << "   Table Class: AC" << endl ;
  413.     }
  414.     if (id > 3)
  415.     {
  416.       cout << "Bad index " << id << endl ;
  417.       return ;
  418.     }
  419.  
  420.     JpegHuffmanDecoder *table ;
  421.     if (tableclass != 0)
  422.       table = &ac_tables [id] ;
  423.     else
  424.        table = &dc_tables [id] ;
  425.  
  426.     // Read the table data into the table object
  427.     remaining -= table->ReadTable (*this) ;
  428.  
  429.     if (verbose_flag)
  430.     {
  431.       table->Dump (cout) ;
  432.     }
  433.   }
  434.  
  435.   if (verbose_flag)
  436.     cout << "}" << endl ;
  437.   return ;
  438. }
  439.  
  440. //
  441. //  Description:
  442. //
  443. //    This function reads a DQT marker from the input stream.
  444. //
  445. void JpegDecoder::ReadQuantization ()
  446. {
  447.   // Defined in Section B.2.4.1
  448.  
  449.   UBYTE2 length = ReadWord () ;
  450.   UBYTE1 data ;
  451.  
  452.   // Maintain a counter for the number of bytes remaining to be read in
  453.   // the quantization table.
  454.   int remaining = length - sizeof (length) ;
  455.  
  456.   if (verbose_flag)
  457.   {
  458.     cout << "{ Define Quantization Table" << endl ;
  459.     cout << "  Length: " << length << endl ;
  460.   }
  461.   while (remaining > 0)
  462.   {
  463.     data = ReadByte () ; -- remaining ;
  464.     unsigned int precision = data >> 4 ;    // Pq in standard
  465.     unsigned int index = data & 0x0F ;      // Tq in standard
  466.  
  467.     if (index >= MaxQuantizationTables)
  468.       throw EJpegBadData ("Quantization Table Index Too Large") ;
  469.  
  470.     if (verbose_flag)
  471.     {
  472.       cout << "  Table Index: " << dec << index << endl ;
  473.       cout << "  Table Precision: " << dec << precision << endl ;
  474.     }
  475.  
  476.     switch (precision)
  477.     {
  478.     case 1:
  479.       remaining -= sizeof(UBYTE2) * JpegSampleSize ;
  480.       break ;
  481.     case 0:
  482.       remaining -= sizeof (UBYTE1) * JpegSampleSize ;
  483.       break ;
  484.     }
  485.  
  486.     // Read the table data into the table object
  487.     quantization_tables [index].ReadTable (*this, precision) ;
  488.  
  489.     if (verbose_flag)
  490.     {
  491.       cout << "  Table Values: " ;
  492.       quantization_tables [index].Print (cout) ;
  493.       cout << endl << "}" << endl ;
  494.     }
  495.   }
  496.   return ;
  497. }
  498.  
  499. //
  500. //  Description:
  501. //
  502. //    This function reads a define restart interval marker
  503. //    from the input stream.
  504. //
  505. void JpegDecoder::ReadRestartInterval ()
  506. {
  507.   // Section B.2.4.4
  508.  
  509.   UBYTE2 length = ReadWord () ;
  510.   restart_interval = ReadWord () ;
  511.   if (verbose_flag)
  512.   {
  513.     cout << "{ Define Restart Interval" << endl ;
  514.     cout << "  Length:  " << dec << length << endl ; // Should be 4
  515.     cout << "  Interval: " << dec << restart_interval << endl ;
  516.     cout << "}" << endl ;
  517.    }
  518.    return ;
  519. }
  520.  
  521. //
  522. //  Description:
  523. //
  524. //    The function reads a start of frame marker from the input stream.
  525. //
  526. //  Parameters:
  527. //    type:  The marker type for the frame
  528. //
  529. void JpegDecoder::ReadStartOfFrame (UBYTE1 type)
  530. {
  531.   // Section B.2.2
  532.   // Read in the image dimensions
  533.   unsigned int length = ReadWord () ;
  534.   unsigned int dataprecision = ReadByte () ;  // P in standard
  535.   if (dataprecision != 8)
  536.     throw EJpegBadData ("Only 8-bit data supported") ;
  537.  
  538.   frame_height = ReadWord () ;            // Y in standard
  539.   frame_width = ReadWord () ;             // X in standard
  540.   component_count = ReadByte () ;   // Nf in standard
  541.  
  542.   // JFIF only allows 1 or 3 components.
  543.   if (component_count != 1 && component_count != 3)
  544.     throw EJpegBadData ("JFIF only supports 1 and 3 component streams") ;
  545.  
  546.   frame_type = type ;
  547.  
  548.   if (verbose_flag)
  549.   {
  550.     cout << "{ Start Of Frame " << endl ;
  551.     cout << "  Length: " << dec << length << endl ;
  552.     cout << "  Precision: " << dec << dataprecision << endl ;
  553.     cout << "  Height: " << dec << frame_height << endl ;
  554.     cout << "  Width: " << dec << frame_width << endl ;
  555.     cout << "  Component Count: " << component_count << endl ;
  556.   }
  557.  
  558.   if (length != (component_count * 3 + 8))
  559.     throw EJpegBadData ("Invalid Frame Size") ;
  560.  
  561.   // Rread the component descriptions
  562.   max_horizontal_frequency = 0 ;
  563.   max_vertical_frequency = 0 ;
  564.   for (unsigned int ii = 0 ; ii < component_count ; ++ ii)
  565.   {
  566.     unsigned int ID = ReadByte () ;  // Ci in standard
  567.     unsigned int qtable ;
  568.  
  569.     // While JPEG does not put these restrictions on component IDs
  570.     // the JFIF standard does.
  571.     if (strict_jfif)
  572.     {
  573.     if (component_count == 1 && ID != 1)
  574.       throw EJpegBadData ("Component ID not 1") ;
  575.     else if (ID != ii + 1)
  576.       throw EJpegBadData ("Invalid Component ID or ID out of order") ;
  577.     }
  578.     
  579.     component_indices [ii] = ID ;
  580.  
  581.     UBYTE1 data = ReadByte () ;
  582.     components [ID].HorizontalFrequency (data >> 4) ; // Hi in standard
  583.     components [ID].VerticalFrequency (data & 0xF) ;  // Vi in standard
  584.     qtable= ReadByte () ;  // Tqi in standard
  585.     if (qtable >= MaxQuantizationTables)
  586.       throw EJpegBadData ("Bad Quantization Table Index") ;
  587.     components [ID].SetQuantizationTable (quantization_tables [qtable]) ;
  588.  
  589.     // Keep track of the largest values for horizontal and vertical
  590.     // frequency.
  591.     if (components [ID].HorizontalFrequency ()
  592.         > max_horizontal_frequency)
  593.     {
  594.       max_horizontal_frequency =
  595.         components [ID].HorizontalFrequency () ;
  596.     }
  597.  
  598.     if (components [ID].VerticalFrequency ()
  599.           > max_vertical_frequency)
  600.     {
  601.       max_vertical_frequency =
  602.         components [ID].VerticalFrequency () ;
  603.     }
  604.  
  605.     if (verbose_flag)
  606.     {
  607.       cout << "   Component " << ID << endl ;
  608.       cout << "   Horizontal Frequency: "
  609.            << components [ID].HorizontalFrequency () << endl ;
  610.       cout << "   Vertical Frequency: "
  611.            << components [ID].VerticalFrequency () << endl ;
  612.       cout << "   Quantization Table: "
  613.            << qtable << endl ;
  614.     }
  615.   }
  616.  
  617.   CalculateMcuDimensions () ;
  618.  
  619.   // Allocate storage for the image.
  620.   if (component_count == 1)
  621.   {
  622.     current_image->SetSize (1 << 8, 8, frame_width, frame_height) ;
  623.     // For a grey scale image we need to create the color map. Each color
  624.     // has equal amounts of red, green, and blue.
  625.     for (unsigned int ii = 0 ; ii < (1 << 8) ; ++ ii)
  626.     {
  627.       current_image->ColorMap (ii).red = (UBYTE1) ii ;
  628.       current_image->ColorMap (ii).green = (UBYTE1) ii ;
  629.       current_image->ColorMap (ii).blue = (UBYTE1) ii ;
  630.     }
  631.   }
  632.   else
  633.   {
  634.     current_image->SetSize (0,     // Color Table Entries
  635.                             8 * component_count,  // Bits
  636.                             frame_width,
  637.                             frame_height) ;
  638.  
  639.   }
  640.  
  641.   if (verbose_flag)
  642.     cout << "}" << endl ;
  643.  
  644.   sof_found = true ;
  645.   return ;
  646. }
  647.  
  648. //
  649. //  Description:
  650. //
  651. //    This function reads a start of scan marker and the scan data
  652. //    following the marker.
  653. //
  654. void JpegDecoder::ReadStartOfScan ()
  655. {
  656.   unsigned int ii ;
  657.  
  658.   if (! sof_found)
  659.     throw EJpegBadData ("Scan found before frame defined") ;
  660.  
  661.   // Section B.2.3
  662.  
  663.   UBYTE2 length = ReadWord () ;
  664.   if (verbose_flag)
  665.   {
  666.     cout << "{ Start Of Scan " << endl ;
  667.     cout << "  Length:  " << dec << length << endl ;
  668.   }
  669.  
  670.   scan_component_count = ReadByte () ;  // Ns in standard
  671.   // Right now we can only handle up to three components.
  672.   if (scan_component_count > 3 || scan_component_count < 1)
  673.     throw EJpegBadData ("Invalid component count in scan") ;
  674.  
  675.   for (ii = 0 ; ii < scan_component_count ; ++ ii)
  676.   {
  677.     UBYTE1 componentID = ReadByte () ;  // Csi in standard
  678.  
  679.     scan_components [ii] = &components [componentID] ;
  680.     // If the horizontal frequency is zero then the component was not
  681.     // defined in the SOFx marker.
  682.     if (scan_components [ii]->HorizontalFrequency () == 0)
  683.       throw EJpegBadData ("Component Not Defined") ;
  684.  
  685.     UBYTE1 rb = ReadByte () ;
  686.     unsigned int actable = rb & 0x0F ;
  687.     unsigned int dctable = rb >> 4 ;
  688.  
  689.     scan_components [ii]->SetHuffmanTables (
  690.                               dc_tables [dctable],
  691.                               ac_tables [actable]) ;
  692.     if (verbose_flag)
  693.     {
  694.       cout << "  Component ID: "
  695.            << dec << (unsigned int) componentID << endl ;
  696.       cout << "  DC Entropy Table: "
  697.            << dec << dctable << endl  ;
  698.       cout << "  AC Entropy Table: "
  699.            << dec << actable << endl  ;
  700.     }
  701.   }
  702.  
  703.   unsigned int spectralselectionstart = ReadByte () ; // Ss in standard
  704.   unsigned int spectralselectionend = ReadByte ()  ;  // Se in standard
  705.  
  706.   UBYTE1 ssa = ReadByte () ;
  707.   unsigned int successiveapproximationhigh = ssa >> 4 ;  // Ah in standard
  708.   unsigned int successiveapproximationlow = ssa & 0x0F ; // Al in standard
  709.  
  710.   if (verbose_flag)
  711.   {
  712.     cout << " Spectral Selection Start: "
  713.          << dec << (unsigned int) spectralselectionstart << endl ;
  714.     cout << " Spectral Selection End: "
  715.          << dec << (unsigned int) spectralselectionend << endl ;
  716.     cout << " Successive Approximation High: "
  717.          << dec << successiveapproximationhigh << endl ;
  718.     cout << " Successive Approximation Low: "
  719.          << dec << successiveapproximationlow << endl  ;
  720.     cout << "}" << endl ;
  721.   }
  722.  
  723.   for (ii = 0 ; ii < scan_component_count ; ++ ii)
  724.   {
  725.     scan_components [ii]->CheckQuantizationTable () ;
  726.     scan_components [ii]->CheckDcTable () ;
  727.     scan_components [ii]->CheckAcTable () ;
  728.     scan_components [ii]->AllocateComponentBuffers (*this) ;
  729.  
  730.   }
  731.  
  732.   ++ current_scan ;
  733.   ReadSequentialScanData () ;
  734.  
  735.   CallProgressFunction (100) ;
  736.   return ;
  737. }
  738.  
  739. //
  740. //  Description:
  741. //
  742. //    This function determines for non-interlaced scans:
  743. //
  744. //     o The dimensions in pixels for an MCU
  745. //     o The number of MCU rows and columns needed to encode the scan.
  746. //
  747. void JpegDecoder::CalculateMcuDimensions ()
  748. {
  749.   mcu_height = max_vertical_frequency * JpegSampleWidth ;
  750.   mcu_width = max_horizontal_frequency * JpegSampleWidth ;
  751.   mcu_rows = (frame_height + mcu_height - 1) / mcu_height ;
  752.   mcu_cols = (frame_width + mcu_width - 1) / mcu_width ;
  753.   return ;
  754. }
  755.  
  756. //
  757. //  Dimensions:
  758. //
  759. //    This function calls the progress function if it has
  760. //    been supplied by the user.
  761. //
  762. //  Parameters:
  763. //    progress: The progress percentage.
  764. //
  765. void JpegDecoder::CallProgressFunction (unsigned int progress)
  766. {
  767.   if (progress_function == NULL)
  768.     return ;
  769.  
  770.   bool abort = false ;
  771.   unsigned int percent = progress ;
  772.   if (percent > 100)
  773.     percent = 100 ;
  774.   if (progress_function != NULL)
  775.   {
  776.     progress_function (*this,
  777.                        progress_data,
  778.                        current_scan,
  779.                        scan_count,
  780.                        percent,
  781.                        abort) ;
  782.   }
  783.  
  784.   if (abort)
  785.     throw EJpegAbort () ;
  786.   return ;
  787. }
  788.  
  789.  
  790. //
  791. //  Parameters:
  792. //
  793. //    The function reads the scan data for a sequential scan. All
  794. //    we do here is determine whether or not we have an interleaved
  795. //    or non-interleaved scan then call a function that handles
  796. //    the scan type.
  797.  
  798. void JpegDecoder::ReadSequentialScanData ()
  799. {
  800.   expected_restart = 0 ;
  801.   if (ScanIsInterleaved ())
  802.   {
  803.     ReadSequentialInterleavedScan () ;
  804.   }
  805.   else
  806.   {
  807.     ReadSequentialNonInterleavedScan () ;
  808.   }
  809.   return ;
  810. }
  811.  
  812. //
  813. //  Description:
  814. //
  815. //    This function reads the scan data for an interleaved scan.
  816. //
  817.  
  818. void JpegDecoder::ReadSequentialInterleavedScan ()
  819. {
  820.   ResetDcDifferences () ;
  821.  
  822.   unsigned int restartcount = 0 ;
  823.   for (unsigned int mcurow = 0 ; mcurow < mcu_rows ; ++ mcurow)
  824.   {
  825.     CallProgressFunction (mcurow * 100 / mcu_rows) ;
  826.     for (unsigned int mcucol = 0 ; mcucol < mcu_cols ;
  827.          ++ mcucol, ++restartcount)
  828.     {
  829.       if (restart_interval != 0 && restart_interval == restartcount)
  830.       {
  831.         ProcessRestartMarker () ;
  832.         restartcount = 0 ;
  833.       }
  834.       for (unsigned int cc = 0 ; cc < scan_component_count ; ++ cc)
  835.       {
  836.         for (unsigned int cy = 0 ;
  837.              cy < scan_components [cc]->VerticalFrequency () ;
  838.              ++ cy)
  839.         {
  840.           unsigned int durow = scan_components [cc]->VerticalFrequency ()
  841.                                * mcurow + cy ;
  842.           for (unsigned int cx = 0 ;
  843.                cx < scan_components [cc]->HorizontalFrequency () ;
  844.                ++ cx)
  845.           {
  846.             unsigned int ducol =
  847.                    scan_components [cc]->HorizontalFrequency ()
  848.                    * mcucol + cx ;
  849.  
  850.             scan_components [cc]->DecodeSequential (
  851.                                       *this,
  852.                                       durow,
  853.                                       ducol) ;
  854.           }
  855.         }
  856.       }
  857.     }
  858.   }
  859.   return ;
  860. }
  861.  
  862. //
  863. //  Description:
  864. //
  865. //    This function reads the scan data for a non-interleaved scan.
  866. //
  867.  
  868. void JpegDecoder::ReadSequentialNonInterleavedScan ()
  869. {
  870.   ResetDcDifferences () ;
  871.  
  872.   unsigned int restartcount = 0 ;
  873.   for (unsigned int row = 0 ;
  874.        row < scan_components [0]->NoninterleavedRows () ;
  875.        ++ row)
  876.   {
  877.     CallProgressFunction (row * 100 / scan_components [0]->NoninterleavedRows ()) ;
  878.     for (unsigned int col = 0 ;
  879.          col < scan_components [0]->NoninterleavedCols () ;
  880.          ++ col, ++ restartcount)
  881.     {
  882.       if (restart_interval != 0
  883.           && restart_interval == restartcount)
  884.       {
  885.         ProcessRestartMarker () ;
  886.         restartcount = 0 ;
  887.       }
  888.       scan_components [0]->DecodeSequential (*this, row, col) ;
  889.     }
  890.   }
  891.   return ;
  892. }
  893.  
  894. //
  895. //  Description:
  896. //
  897. //    This function resets the DC difference values for all components
  898. //    for the current scan.
  899. //
  900. //    This function gets called before each scan is processed and
  901. //    whenever a restart marker is read.
  902. //
  903.  
  904. void JpegDecoder::ResetDcDifferences ()
  905. {
  906.   for (unsigned int ii = 0 ; ii < scan_component_count ; ++ ii)
  907.     scan_components [ii]->ResetDcDifference () ;
  908.   return ;
  909. }
  910.  
  911. //
  912. //  Description:
  913. //
  914. //    This function reads a restart marker from the input stream.
  915. //    It gets called byte functions that read scan data whenever
  916. //    a restart marker is expected. An exception is raise if the
  917. //    correct restart marker is not next in the input stream.
  918. //
  919. void JpegDecoder::ProcessRestartMarker ()
  920. {
  921.   UBYTE1 data = ReadByte () ;
  922.   if (data != 0xFF)
  923.     throw EJpegBadData ("Missing Restart Marker") ;
  924.   // According to E.1.2 0xFF can be used as a fill character
  925.   // before the marker.
  926.   while (data == 0xFF)
  927.     data = ReadByte () ;
  928.   if (data < RST0 || data > RST7)
  929.     throw EJpegBadData ("Missing Restart Marker") ;
  930.  
  931.   // Restart markers RST0..RST7 should come in sequence.
  932.   if ((0x0F & data) != expected_restart)
  933.     throw EJpegBadData ("Incorrect Restart Marker") ;
  934.  
  935.   // Move the counter to the next restart marker
  936.   ++ expected_restart ;
  937.   expected_restart %= 8 ;
  938.  
  939.   // Reset the DC coefficent differences to zero.
  940.   ResetDcDifferences () ;
  941.   return ;
  942. }
  943.  
  944. //
  945. //  Description:
  946. //
  947. //    This function reads an image from a JPEG stream. The
  948. //    stream needs to have been opened in binary mode.
  949. //
  950. //  Parameters:
  951. //    istrm: Input stream
  952. //    image: The output image
  953. //
  954.  
  955. void JpegDecoder::ReadImage (std::istream &istrm,
  956.                              BitmapImage &image)
  957. {
  958.   unsigned char data ;
  959.  
  960.   current_scan = 0 ;
  961.   scan_count = 0 ;
  962.   input_stream = &istrm ;
  963.   current_image = &image ;
  964.  
  965.   if (progress_function != NULL)
  966.     GetScanCount () ;
  967.  
  968.   restart_interval = 0 ;  // Clear the restart interval ;
  969.   try
  970.   {
  971.     current_image->Clear () ;
  972.     eoi_found = false ;
  973.     sof_found = false ;
  974.  
  975.     // Read the required SOI and APP0 markers at the start of the image.
  976.     ReadStreamHeader () ;
  977.  
  978.     data = ReadByte () ;
  979.     while (! input_stream->eof () && ! eoi_found)
  980.     {
  981.       if (data == SOB)
  982.       {
  983.         ReadMarker () ;
  984.         if (eoi_found)
  985.           break ;
  986.       }
  987.       data = ReadByte () ;
  988.       if (input_stream->eof ())
  989.         throw EJpegBadData ("Premature end of file") ;
  990.     }
  991.   }
  992.   catch (EJpegAbort)
  993.   {
  994.     FreeAllocatedResources () ;
  995.     current_image = NULL ;
  996.   }
  997.   catch (...)
  998.   {
  999.     UpdateImage () ;
  1000.     FreeAllocatedResources () ;
  1001.     current_image = NULL ;
  1002.     throw ;
  1003.   }
  1004.   UpdateImage () ;
  1005.  
  1006.   if (! eoi_found)
  1007.   {
  1008.     throw EJpegBadData("End of Image Marker Not Found") ;
  1009.   }
  1010.   // We do no want an exception so do not call ReadByte ()
  1011.   // Sometimes there can be trailing end of record markers.
  1012.   input_stream->read ((char *) &data, sizeof (data)) ;
  1013.   while ((data == '\r' || data == '\n') && ! input_stream->eof ())
  1014.     input_stream->read ((char *) &data, sizeof (data)) ;
  1015.   if (! input_stream->eof ())
  1016.   {
  1017.     throw EJpegBadData ("Extra Data After End of Image Marker") ;
  1018.   }
  1019.  
  1020.   FreeAllocatedResources () ;
  1021.   current_image = NULL ;
  1022.   return ;
  1023. }
  1024.  
  1025. //
  1026. //  Description:
  1027. //
  1028. //    This function scans a stream and counts the number of scans.  This
  1029. //    allows an exact count for a progress function.
  1030. //
  1031. void JpegDecoder::GetScanCount ()
  1032. {
  1033.   // Save the stream position so we can go back
  1034.   // when we are finished.
  1035.   long startpos = input_stream->tellg () ;
  1036.  
  1037.   // Count the number of SOS markers.
  1038.   scan_count = 0 ;
  1039.   while (! input_stream->eof ())
  1040.   {
  1041.     UBYTE1 data ;
  1042.     input_stream->read ((char *) &data, 1) ;
  1043.     if (data == SOB)
  1044.     {
  1045.       while (data == SOB)
  1046.       {
  1047.         input_stream->read ((char *) &data, 1) ;
  1048.       }
  1049.       if (data == SOS)
  1050.         ++ scan_count ;
  1051.       else if (data == EOI)
  1052.         break ;
  1053.     }
  1054.   }
  1055.   // Go back to where we were in the stream.
  1056.   input_stream->seekg (startpos) ;
  1057.   input_stream->clear () ;  // Clear the EOF flag.
  1058.   return ;
  1059. }
  1060.  
  1061. //
  1062. //  Description:
  1063. //
  1064. //    This function writes the image data that has been read so
  1065. //    far to the image. This function gets called after reading
  1066. //    the entire image stream.  The user can also call this function
  1067. //    from a progress function to display progressive images,
  1068. //    multi-scan sequential images, or just to display the image
  1069. //    as it is being read (slow).
  1070. //
  1071.  
  1072. void JpegDecoder::UpdateImage ()
  1073. {
  1074.   if (current_image == NULL)
  1075.     throw EJpegError ("Not reading an image") ;
  1076.  
  1077.   for (int ii = 0 ; ii < component_count ; ++ ii)
  1078.   {
  1079.     components [component_indices [ii]].Upsample () ;
  1080.   }
  1081.  
  1082.   switch (component_count)
  1083.   {
  1084.   case 3:
  1085.     JpegDecoderComponent::RGBConvert (components [component_indices [0]],
  1086.                                       components [component_indices [1]],
  1087.                                       components [component_indices [2]],
  1088.                                       *current_image) ;
  1089.     break ;
  1090.   case 1:
  1091.     JpegDecoderComponent::GrayscaleConvert (
  1092.                              components [component_indices [0]],
  1093.                              *current_image) ;
  1094.     break ;
  1095.   }
  1096.   return ;
  1097. }
  1098.  
  1099. //
  1100. //  Description:
  1101. //
  1102. //    This function frees all the memory dynamically allocated
  1103. //    during the image decoding process.  
  1104. //
  1105. void JpegDecoder::FreeAllocatedResources ()
  1106. {
  1107.   for (unsigned int ii = 0 ; ii < component_count ; ++ ii)
  1108.   {
  1109.     components [component_indices [ii]].FreeComponentBuffers () ;
  1110.   }
  1111.   return ;
  1112. }
  1113.  
  1114.  
  1115. //
  1116. //  Description:
  1117. //
  1118. //    This function returns the next raw bit in the input stream.
  1119. //
  1120. //    Bits are read from high order to low.
  1121. //
  1122. //  Return Value:
  1123. //
  1124. //    The next bit (0, 1)
  1125. //
  1126.  
  1127. // This function returns the next bit in the input stream.
  1128. int JpegDecoder::NextBit ()
  1129. {
  1130.   // Section F.2.2.5 Figure F.18.
  1131.   // CNT is called bitposition
  1132.   // B is called bitdata
  1133.   if (bit_position == 0)
  1134.   {
  1135.     // We are out of data so read the next byte from the input stream.
  1136.     input_stream->read ((char *) &bit_data, sizeof (bit_data)) ;
  1137.     if (input_stream->eof ())
  1138.       throw EJpegBadData ("Premature end of file") ;
  1139.     // Reset the bit read position starting with the highest order bit. We
  1140.     // read high to low.
  1141.     bit_position = CHAR_BIT * sizeof (bit_data) ;
  1142.  
  1143.     if (bit_data == 0xFF)
  1144.     {
  1145.       // 0xFF could start a marker. The sequence 0xFF, 0x00 is used to
  1146.       // to represent the value 0xFF. The only other marker that is legal
  1147.       // at this point is a DNL marker.
  1148.       UBYTE1 b2 ;
  1149.       input_stream->read ((char *) &b2, 1) ;
  1150.       if (input_stream->eof ())
  1151.         throw EJpegBadData ("Premature end of file") ;
  1152.       if (b2 != 0)
  1153.       {
  1154.         if (b2 == DNL)
  1155.         {
  1156.           // DNL markers should not occur within the supported frame types.
  1157.           throw EJpegBadData ("Unexpected Marker DNL") ;
  1158.         }
  1159.         else
  1160.         {
  1161.           throw EJpegBadData ("Unexpected Marker") ;
  1162.         }
  1163.       }
  1164.     }
  1165.   }
  1166.  
  1167.   // Consume one bit of the input.
  1168.   -- bit_position ;
  1169.   // Shift the value to the low order bit position.
  1170.   UBYTE1 result = (UBYTE1) ((bit_data >> bit_position) & 1) ;
  1171.   return result ;
  1172. }
  1173.  
  1174.