home *** CD-ROM | disk | FTP | other *** search
/ rtsi.com / 2014.01.www.rtsi.com.tar / www.rtsi.com / OS9 / OSK / GRAPHICS / jpeglib_5a.lzh / JPEG_5A / rdgif.c < prev    next >
Text File  |  1995-01-14  |  23KB  |  677 lines

  1. /*
  2.  * rdgif.c
  3.  *
  4.  * Copyright (C) 1991-1994, Thomas G. Lane.
  5.  * This file is part of the Independent JPEG Group's software.
  6.  * For conditions of distribution and use, see the accompanying README file.
  7.  *
  8.  * This file contains routines to read input images in GIF format.
  9.  *
  10.  * These routines may need modification for non-Unix environments or
  11.  * specialized applications.  As they stand, they assume input from
  12.  * an ordinary stdio stream.  They further assume that reading begins
  13.  * at the start of the file; input_init may need work if the
  14.  * user interface has already read some data (e.g., to determine that
  15.  * the file is indeed GIF format).
  16.  */
  17.  
  18. /*
  19.  * This code is loosely based on giftoppm from the PBMPLUS distribution
  20.  * of Feb. 1991.  That file contains the following copyright notice:
  21.  * +-------------------------------------------------------------------+
  22.  * | Copyright 1990, David Koblas.                                     |
  23.  * |   Permission to use, copy, modify, and distribute this software   |
  24.  * |   and its documentation for any purpose and without fee is hereby |
  25.  * |   granted, provided that the above copyright notice appear in all |
  26.  * |   copies and that both that copyright notice and this permission  |
  27.  * |   notice appear in supporting documentation.  This software is    |
  28.  * |   provided "as is" without express or implied warranty.           |
  29.  * +-------------------------------------------------------------------+
  30.  *
  31.  * We are also required to state that
  32.  *    "The Graphics Interchange Format(c) is the Copyright property of
  33.  *    CompuServe Incorporated. GIF(sm) is a Service Mark property of
  34.  *    CompuServe Incorporated."
  35.  */
  36.  
  37. #include "cdjpeg.h"        /* Common decls for cjpeg/djpeg applications */
  38.  
  39. #ifdef GIF_SUPPORTED
  40.  
  41.  
  42. #define    MAXCOLORMAPSIZE    256    /* max # of colors in a GIF colormap */
  43. #define NUMCOLORS    3    /* # of colors */
  44. #define CM_RED        0    /* color component numbers */
  45. #define CM_GREEN    1
  46. #define CM_BLUE        2
  47.  
  48. #define    MAX_LZW_BITS    12    /* maximum LZW code size */
  49. #define LZW_TABLE_SIZE    (1<<MAX_LZW_BITS) /* # of possible LZW symbols */
  50.  
  51. /* Macros for extracting header data --- note we assume chars may be signed */
  52.  
  53. #define LM_to_uint(a,b)        ((((b)&0xFF) << 8) | ((a)&0xFF))
  54.  
  55. #define BitSet(byte, bit)    ((byte) & (bit))
  56. #define INTERLACE    0x40    /* mask for bit signifying interlaced image */
  57. #define COLORMAPFLAG    0x80    /* mask for bit signifying colormap presence */
  58.  
  59. #define    ReadOK(file,buffer,len)    (JFREAD(file,buffer,len) == ((size_t) (len)))
  60.  
  61. /* LZW decompression tables look like this:
  62.  *   symbol_head[K] = prefix symbol of any LZW symbol K (0..LZW_TABLE_SIZE-1)
  63.  *   symbol_tail[K] = suffix byte   of any LZW symbol K (0..LZW_TABLE_SIZE-1)
  64.  * Note that entries 0..end_code of the above tables are not used,
  65.  * since those symbols represent raw bytes or special codes.
  66.  *
  67.  * The stack represents the not-yet-used expansion of the last LZW symbol.
  68.  * In the worst case, a symbol could expand to as many bytes as there are
  69.  * LZW symbols, so we allocate LZW_TABLE_SIZE bytes for the stack.
  70.  * (This is conservative since that number includes the raw-byte symbols.)
  71.  *
  72.  * The tables are allocated from FAR heap space since they would use up
  73.  * rather a lot of the near data space in a PC.
  74.  */
  75.  
  76.  
  77. /* Private version of data source object */
  78.  
  79. typedef struct {
  80.   struct cjpeg_source_struct pub; /* public fields */
  81.  
  82.   j_compress_ptr cinfo;        /* back link saves passing separate parm */
  83.  
  84.   JSAMPARRAY colormap;        /* GIF colormap (converted to my format) */
  85.  
  86.   /* State for GetCode and LZWReadByte */
  87.   char code_buf[256+4];        /* current input data block */
  88.   int last_byte;        /* # of bytes in code_buf */
  89.   int last_bit;            /* # of bits in code_buf */
  90.   int cur_bit;            /* next bit index to read */
  91.   boolean out_of_blocks;    /* TRUE if hit terminator data block */
  92.  
  93.   int input_code_size;        /* codesize given in GIF file */
  94.   int clear_code,end_code;    /* values for Clear and End codes */
  95.  
  96.   int code_size;        /* current actual code size */
  97.   int limit_code;        /* 2^code_size */
  98.   int max_code;            /* first unused code value */
  99.   boolean first_time;        /* flags first call to LZWReadByte */
  100.  
  101.   /* Private state for LZWReadByte */
  102.   int oldcode;            /* previous LZW symbol */
  103.   int firstcode;        /* first byte of oldcode's expansion */
  104.  
  105.   /* LZW symbol table and expansion stack */
  106.   UINT16 FAR *symbol_head;    /* => table of prefix symbols */
  107.   UINT8  FAR *symbol_tail;    /* => table of suffix bytes */
  108.   UINT8  FAR *symbol_stack;    /* => stack for symbol expansions */
  109.   UINT8  FAR *sp;        /* stack pointer */
  110.  
  111.   /* State for interlaced image processing */
  112.   boolean is_interlaced;    /* TRUE if have interlaced image */
  113.   jvirt_sarray_ptr interlaced_image; /* full image in interlaced order */
  114.   JDIMENSION cur_row_number;    /* need to know actual row number */
  115.   JDIMENSION pass2_offset;    /* # of pixel rows in pass 1 */
  116.   JDIMENSION pass3_offset;    /* # of pixel rows in passes 1&2 */
  117.   JDIMENSION pass4_offset;    /* # of pixel rows in passes 1,2,3 */
  118. } gif_source_struct;
  119.  
  120. typedef gif_source_struct * gif_source_ptr;
  121.  
  122.  
  123. /* Forward declarations */
  124. METHODDEF JDIMENSION get_pixel_rows
  125.     JPP((j_compress_ptr cinfo, cjpeg_source_ptr sinfo));
  126. METHODDEF JDIMENSION load_interlaced_image
  127.     JPP((j_compress_ptr cinfo, cjpeg_source_ptr sinfo));
  128. METHODDEF JDIMENSION get_interlaced_row
  129.     JPP((j_compress_ptr cinfo, cjpeg_source_ptr sinfo));
  130.  
  131.  
  132. LOCAL int
  133. ReadByte (gif_source_ptr sinfo)
  134. /* Read next byte from GIF file */
  135. {
  136.   register FILE * infile = sinfo->pub.input_file;
  137.   int c;
  138.  
  139.   if ((c = getc(infile)) == EOF)
  140.     ERREXIT(sinfo->cinfo, JERR_INPUT_EOF);
  141.   return c;
  142. }
  143.  
  144.  
  145. LOCAL int
  146. GetDataBlock (gif_source_ptr sinfo, char *buf)
  147. /* Read a GIF data block, which has a leading count byte */
  148. /* A zero-length block marks the end of a data block sequence */
  149. {
  150.   int count;
  151.  
  152.   count = ReadByte(sinfo);
  153.   if (count > 0) {
  154.     if (! ReadOK(sinfo->pub.input_file, buf, count))
  155.       ERREXIT(sinfo->cinfo, JERR_INPUT_EOF);
  156.   }
  157.   return count;
  158. }
  159.  
  160.  
  161. LOCAL void
  162. SkipDataBlocks (gif_source_ptr sinfo)
  163. /* Skip a series of data blocks, until a block terminator is found */
  164. {
  165.   char buf[256];
  166.  
  167.   while (GetDataBlock(sinfo, buf) > 0)
  168.     /* skip */;
  169. }
  170.  
  171.  
  172. LOCAL void
  173. ReInitLZW (gif_source_ptr sinfo)
  174. /* (Re)initialize LZW state; shared code for startup and Clear processing */
  175. {
  176.   sinfo->code_size = sinfo->input_code_size + 1;
  177.   sinfo->limit_code = sinfo->clear_code << 1;    /* 2^code_size */
  178.   sinfo->max_code = sinfo->clear_code + 2;    /* first unused code value */
  179.   sinfo->sp = sinfo->symbol_stack;        /* init stack to empty */
  180. }
  181.  
  182.  
  183. LOCAL void
  184. InitLZWCode (gif_source_ptr sinfo)
  185. /* Initialize for a series of LZWReadByte (and hence GetCode) calls */
  186. {
  187.   /* GetCode initialization */
  188.   sinfo->last_byte = 2;        /* make safe to "recopy last two bytes" */
  189.   sinfo->last_bit = 0;        /* nothing in the buffer */
  190.   sinfo->cur_bit = 0;        /* force buffer load on first call */
  191.   sinfo->out_of_blocks = FALSE;
  192.  
  193.   /* LZWReadByte initialization: */
  194.   /* compute special code values (note that these do not change later) */
  195.   sinfo->clear_code = 1 << sinfo->input_code_size;
  196.   sinfo->end_code = sinfo->clear_code + 1;
  197.   sinfo->first_time = TRUE;
  198.   ReInitLZW(sinfo);
  199. }
  200.  
  201.  
  202. LOCAL int
  203. GetCode (gif_source_ptr sinfo)
  204. /* Fetch the next code_size bits from the GIF data */
  205. /* We assume code_size is less than 16 */
  206. {
  207.   register INT32 accum;
  208.   int offs, ret, count;
  209.  
  210.   while ( (sinfo->cur_bit + sinfo->code_size) > sinfo->last_bit) {
  211.     /* Time to reload the buffer */
  212.     if (sinfo->out_of_blocks) {
  213.       WARNMS(sinfo->cinfo, JWRN_GIF_NOMOREDATA);
  214.       return sinfo->end_code;    /* fake something useful */
  215.     }
  216.     /* preserve last two bytes of what we have -- assume code_size <= 16 */
  217.     sinfo->code_buf[0] = sinfo->code_buf[sinfo->last_byte-2];
  218.     sinfo->code_buf[1] = sinfo->code_buf[sinfo->last_byte-1];
  219.     /* Load more bytes; set flag if we reach the terminator block */
  220.     if ((count = GetDataBlock(sinfo, &sinfo->code_buf[2])) == 0) {
  221.       sinfo->out_of_blocks = TRUE;
  222.       WARNMS(sinfo->cinfo, JWRN_GIF_NOMOREDATA);
  223.       return sinfo->end_code;    /* fake something useful */
  224.     }
  225.     /* Reset counters */
  226.     sinfo->cur_bit = (sinfo->cur_bit - sinfo->last_bit) + 16;
  227.     sinfo->last_byte = 2 + count;
  228.     sinfo->last_bit = sinfo->last_byte * 8;
  229.   }
  230.  
  231.   /* Form up next 24 bits in accum */
  232.   offs = sinfo->cur_bit >> 3;    /* byte containing cur_bit */
  233. #ifdef CHAR_IS_UNSIGNED
  234.   accum = sinfo->code_buf[offs+2];
  235.   accum <<= 8;
  236.   accum |= sinfo->code_buf[offs+1];
  237.   accum <<= 8;
  238.   accum |= sinfo->code_buf[offs];
  239. #else
  240.   accum = sinfo->code_buf[offs+2] & 0xFF;
  241.   accum <<= 8;
  242.   accum |= sinfo->code_buf[offs+1] & 0xFF;
  243.   accum <<= 8;
  244.   accum |= sinfo->code_buf[offs] & 0xFF;
  245. #endif
  246.  
  247.   /* Right-align cur_bit in accum, then mask off desired number of bits */
  248.   accum >>= (sinfo->cur_bit & 7);
  249.   ret = ((int) accum) & ((1 << sinfo->code_size) - 1);
  250.   
  251.   sinfo->cur_bit += sinfo->code_size;
  252.   return ret;
  253. }
  254.  
  255.  
  256. LOCAL int
  257. LZWReadByte (gif_source_ptr sinfo)
  258. /* Read an LZW-compressed byte */
  259. {
  260.   register int code;        /* current working code */
  261.   int incode;            /* saves actual input code */
  262.  
  263.   /* First time, just eat the expected Clear code(s) and return next code, */
  264.   /* which is expected to be a raw byte. */
  265.   if (sinfo->first_time) {
  266.     sinfo->first_time = FALSE;
  267.     code = sinfo->clear_code;    /* enables sharing code with Clear case */
  268.   } else {
  269.  
  270.     /* If any codes are stacked from a previously read symbol, return them */
  271.     if (sinfo->sp > sinfo->symbol_stack)
  272.       return (int) *(-- sinfo->sp);
  273.  
  274.     /* Time to read a new symbol */
  275.     code = GetCode(sinfo);
  276.  
  277.   }
  278.  
  279.   if (code == sinfo->clear_code) {
  280.     /* Reinit state, swallow any extra Clear codes, and */
  281.     /* return next code, which is expected to be a raw byte. */
  282.     ReInitLZW(sinfo);
  283.     do {
  284.       code = GetCode(sinfo);
  285.     } while (code == sinfo->clear_code);
  286.     if (code > sinfo->clear_code) { /* make sure it is a raw byte */
  287.       WARNMS(sinfo->cinfo, JWRN_GIF_BADDATA);
  288.       code = 0;            /* use something valid */
  289.     }
  290.     /* make firstcode, oldcode valid! */
  291.     sinfo->firstcode = sinfo->oldcode = code;
  292.     return code;
  293.   }
  294.  
  295.   if (code == sinfo->end_code) {
  296.     /* Skip the rest of the image, unless GetCode already read terminator */
  297.     if (! sinfo->out_of_blocks) {
  298.       SkipDataBlocks(sinfo);
  299.       sinfo->out_of_blocks = TRUE;
  300.     }
  301.     /* Complain that there's not enough data */
  302.     WARNMS(sinfo->cinfo, JWRN_GIF_ENDCODE);
  303.     /* Pad data with 0's */
  304.     return 0;            /* fake something usable */
  305.   }
  306.  
  307.   /* Got normal raw byte or LZW symbol */
  308.   incode = code;        /* save for a moment */
  309.   
  310.   if (code >= sinfo->max_code) { /* special case for not-yet-defined symbol */
  311.     /* code == max_code is OK; anything bigger is bad data */
  312.     if (code > sinfo->max_code) {
  313.       WARNMS(sinfo->cinfo, JWRN_GIF_BADDATA);
  314.       incode = 0;        /* prevent creation of loops in symbol table */
  315.     }
  316.     /* this symbol will be defined as oldcode/firstcode */
  317.     *(sinfo->sp++) = (UINT8) sinfo->firstcode;
  318.     code = sinfo->oldcode;
  319.   }
  320.  
  321.   /* If it's a symbol, expand it into the stack */
  322.   while (code >= sinfo->clear_code) {
  323.     *(sinfo->sp++) = sinfo->symbol_tail[code]; /* tail is a byte value */
  324.     code = sinfo->symbol_head[code]; /* head is another LZW symbol */
  325.   }
  326.   /* At this point code just represents a raw byte */
  327.   sinfo->firstcode = code;    /* save for possible future use */
  328.  
  329.   /* If there's room in table, */
  330.   if ((code = sinfo->max_code) < LZW_TABLE_SIZE) {
  331.     /* Define a new symbol = prev sym + head of this sym's expansion */
  332.     sinfo->symbol_head[code] = sinfo->oldcode;
  333.     sinfo->symbol_tail[code] = (UINT8) sinfo->firstcode;
  334.     sinfo->max_code++;
  335.     /* Is it time to increase code_size? */
  336.     if ((sinfo->max_code >= sinfo->limit_code) &&
  337.     (sinfo->code_size < MAX_LZW_BITS)) {
  338.       sinfo->code_size++;
  339.       sinfo->limit_code <<= 1;    /* keep equal to 2^code_size */
  340.     }
  341.   }
  342.   
  343.   sinfo->oldcode = incode;    /* save last input symbol for future use */
  344.   return sinfo->firstcode;    /* return first byte of symbol's expansion */
  345. }
  346.  
  347.  
  348. LOCAL void
  349. ReadColorMap (gif_source_ptr sinfo, int cmaplen, JSAMPARRAY cmap)
  350. /* Read a GIF colormap */
  351. {
  352.   int i;
  353.  
  354.   for (i = 0; i < cmaplen; i++) {
  355. #if BITS_IN_JSAMPLE == 8
  356. #define UPSCALE(x)  (x)
  357. #else
  358. #define UPSCALE(x)  ((x) << (BITS_IN_JSAMPLE-8))
  359. #endif
  360.     cmap[CM_RED][i]   = (JSAMPLE) UPSCALE(ReadByte(sinfo));
  361.     cmap[CM_GREEN][i] = (JSAMPLE) UPSCALE(ReadByte(sinfo));
  362.     cmap[CM_BLUE][i]  = (JSAMPLE) UPSCALE(ReadByte(sinfo));
  363.   }
  364. }
  365.  
  366.  
  367. LOCAL void
  368. DoExtension (gif_source_ptr sinfo)
  369. /* Process an extension block */
  370. /* Currently we ignore 'em all */
  371. {
  372.   int extlabel;
  373.  
  374.   /* Read extension label byte */
  375.   extlabel = ReadByte(sinfo);
  376.   TRACEMS1(sinfo->cinfo, 1, JTRC_GIF_EXTENSION, extlabel);
  377.   /* Skip the data block(s) associated with the extension */
  378.   SkipDataBlocks(sinfo);
  379. }
  380.  
  381.  
  382. /*
  383.  * Read the file header; return image size and component count.
  384.  */
  385.  
  386. METHODDEF void
  387. start_input_gif (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
  388. {
  389.   gif_source_ptr source = (gif_source_ptr) sinfo;
  390.   char hdrbuf[10];        /* workspace for reading control blocks */
  391.   unsigned int width, height;    /* image dimensions */
  392.   int colormaplen, aspectRatio;
  393.   int c;
  394.  
  395.   /* Allocate space to store the colormap */
  396.   source->colormap = (*cinfo->mem->alloc_sarray)
  397.     ((j_common_ptr) cinfo, JPOOL_IMAGE,
  398.      (JDIMENSION) MAXCOLORMAPSIZE, (JDIMENSION) NUMCOLORS);
  399.  
  400.   /* Read and verify GIF Header */
  401.   if (! ReadOK(source->pub.input_file, hdrbuf, 6))
  402.     ERREXIT(cinfo, JERR_GIF_NOT);
  403.   if (hdrbuf[0] != 'G' || hdrbuf[1] != 'I' || hdrbuf[2] != 'F')
  404.     ERREXIT(cinfo, JERR_GIF_NOT);
  405.   /* Check for expected version numbers.
  406.    * If unknown version, give warning and try to process anyway;
  407.    * this is per recommendation in GIF89a standard.
  408.    */
  409.   if ((hdrbuf[3] != '8' || hdrbuf[4] != '7' || hdrbuf[5] != 'a') &&
  410.       (hdrbuf[3] != '8' || hdrbuf[4] != '9' || hdrbuf[5] != 'a'))
  411.     TRACEMS3(cinfo, 1, JTRC_GIF_BADVERSION, hdrbuf[3], hdrbuf[4], hdrbuf[5]);
  412.  
  413.   /* Read and decipher Logical Screen Descriptor */
  414.   if (! ReadOK(source->pub.input_file, hdrbuf, 7))
  415.     ERREXIT(cinfo, JERR_INPUT_EOF);
  416.   width = LM_to_uint(hdrbuf[0],hdrbuf[1]);
  417.   height = LM_to_uint(hdrbuf[2],hdrbuf[3]);
  418.   colormaplen = 2 << (hdrbuf[4] & 0x07);
  419.   /* we ignore the color resolution, sort flag, and background color index */
  420.   aspectRatio = hdrbuf[6] & 0xFF;
  421.   if (aspectRatio != 0 && aspectRatio != 49)
  422.     TRACEMS(cinfo, 1, JTRC_GIF_NONSQUARE);
  423.  
  424.   /* Read global colormap if header indicates it is present */
  425.   if (BitSet(hdrbuf[4], COLORMAPFLAG))
  426.     ReadColorMap(source, colormaplen, source->colormap);
  427.  
  428.   /* Scan until we reach start of desired image.
  429.    * We don't currently support skipping images, but could add it easily.
  430.    */
  431.   for (;;) {
  432.     c = ReadByte(source);
  433.  
  434.     if (c == ';')        /* GIF terminator?? */
  435.       ERREXIT(cinfo, JERR_GIF_IMAGENOTFOUND);
  436.  
  437.     if (c == '!') {        /* Extension */
  438.       DoExtension(source);
  439.       continue;
  440.     }
  441.     
  442.     if (c != ',') {        /* Not an image separator? */
  443.       WARNMS1(cinfo, JWRN_GIF_CHAR, c);
  444.       continue;
  445.     }
  446.  
  447.     /* Read and decipher Local Image Descriptor */
  448.     if (! ReadOK(source->pub.input_file, hdrbuf, 9))
  449.       ERREXIT(cinfo, JERR_INPUT_EOF);
  450.     /* we ignore top/left position info, also sort flag */
  451.     width = LM_to_uint(hdrbuf[4],hdrbuf[5]);
  452.     height = LM_to_uint(hdrbuf[6],hdrbuf[7]);
  453.     source->is_interlaced = BitSet(hdrbuf[8], INTERLACE);
  454.  
  455.     /* Read local colormap if header indicates it is present */
  456.     /* Note: if we wanted to support skipping images, */
  457.     /* we'd need to skip rather than read colormap for ignored images */
  458.     if (BitSet(hdrbuf[8], COLORMAPFLAG)) {
  459.       colormaplen = 2 << (hdrbuf[8] & 0x07);
  460.       ReadColorMap(source, colormaplen, source->colormap);
  461.     }
  462.  
  463.     source->input_code_size = ReadByte(source); /* get min-code-size byte */
  464.     if (source->input_code_size < 2 || source->input_code_size >= MAX_LZW_BITS)
  465.       ERREXIT1(cinfo, JERR_GIF_CODESIZE, source->input_code_size);
  466.  
  467.     /* Reached desired image, so break out of loop */
  468.     /* If we wanted to skip this image, */
  469.     /* we'd call SkipDataBlocks and then continue the loop */
  470.     break;
  471.   }
  472.  
  473.   /* Prepare to read selected image: first initialize LZW decompressor */
  474.   source->symbol_head = (UINT16 FAR *)
  475.     (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  476.                 LZW_TABLE_SIZE * SIZEOF(UINT16));
  477.   source->symbol_tail = (UINT8 FAR *)
  478.     (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  479.                 LZW_TABLE_SIZE * SIZEOF(UINT8));
  480.   source->symbol_stack = (UINT8 FAR *)
  481.     (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  482.                 LZW_TABLE_SIZE * SIZEOF(UINT8));
  483.   InitLZWCode(source);
  484.  
  485.   /*
  486.    * If image is interlaced, we read it into a full-size sample array,
  487.    * decompressing as we go; then get_interlaced_row selects rows from the
  488.    * sample array in the proper order.
  489.    */
  490.   if (source->is_interlaced) {
  491.     /* We request the virtual array now, but can't access it until virtual
  492.      * arrays have been allocated.  Hence, the actual work of reading the
  493.      * image is postponed until the first call to get_pixel_rows.
  494.      */
  495.     source->interlaced_image = (*cinfo->mem->request_virt_sarray)
  496.       ((j_common_ptr) cinfo, JPOOL_IMAGE,
  497.        (JDIMENSION) width, (JDIMENSION) height, (JDIMENSION) 1);
  498.     if (cinfo->progress != NULL) {
  499.       cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
  500.       progress->total_extra_passes++; /* count file input as separate pass */
  501.     }
  502.     source->pub.get_pixel_rows = load_interlaced_image;
  503.   } else {
  504.     source->pub.get_pixel_rows = get_pixel_rows;
  505.   }
  506.  
  507.   /* Create compressor input buffer. */
  508.   source->pub.buffer = (*cinfo->mem->alloc_sarray)
  509.     ((j_common_ptr) cinfo, JPOOL_IMAGE,
  510.      (JDIMENSION) width * NUMCOLORS, (JDIMENSION) 1);
  511.   source->pub.buffer_height = 1;
  512.  
  513.   /* Return info about the image. */
  514.   cinfo->in_color_space = JCS_RGB;
  515.   cinfo->input_components = NUMCOLORS;
  516.   cinfo->data_precision = BITS_IN_JSAMPLE; /* we always rescale data to this */
  517.   cinfo->image_width = width;
  518.   cinfo->image_height = height;
  519.  
  520.   TRACEMS3(cinfo, 1, JTRC_GIF, width, height, colormaplen);
  521. }
  522.  
  523.  
  524. /*
  525.  * Read one row of pixels.
  526.  * This version is used for noninterlaced GIF images:
  527.  * we read directly from the GIF file.
  528.  */
  529.  
  530. METHODDEF JDIMENSION
  531. get_pixel_rows (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
  532. {
  533.   gif_source_ptr source = (gif_source_ptr) sinfo;
  534.   register int c;
  535.   register JSAMPROW ptr;
  536.   register JDIMENSION col;
  537.   register JSAMPARRAY colormap = source->colormap;
  538.   
  539.   ptr = source->pub.buffer[0];
  540.   for (col = cinfo->image_width; col > 0; col--) {
  541.     c = LZWReadByte(source);
  542.     *ptr++ = colormap[CM_RED][c];
  543.     *ptr++ = colormap[CM_GREEN][c];
  544.     *ptr++ = colormap[CM_BLUE][c];
  545.   }
  546.   return 1;
  547. }
  548.  
  549.  
  550. /*
  551.  * Read one row of pixels.
  552.  * This version is used for the first call on get_pixel_rows when
  553.  * reading an interlaced GIF file: we read the whole image into memory.
  554.  */
  555.  
  556. METHODDEF JDIMENSION
  557. load_interlaced_image (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
  558. {
  559.   gif_source_ptr source = (gif_source_ptr) sinfo;
  560.   JSAMPARRAY image_ptr;
  561.   register JSAMPROW sptr;
  562.   register JDIMENSION col;
  563.   JDIMENSION row;
  564.   cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
  565.  
  566.   /* Read the interlaced image into the virtual array we've created. */
  567.   for (row = 0; row < cinfo->image_height; row++) {
  568.     if (progress != NULL) {
  569.       progress->pub.pass_counter = (long) row;
  570.       progress->pub.pass_limit = (long) cinfo->image_height;
  571.       (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
  572.     }
  573.     image_ptr = (*cinfo->mem->access_virt_sarray)
  574.       ((j_common_ptr) cinfo, source->interlaced_image, row, TRUE);
  575.     sptr = image_ptr[0];
  576.     for (col = cinfo->image_width; col > 0; col--) {
  577.       *sptr++ = (JSAMPLE) LZWReadByte(source);
  578.     }
  579.   }
  580.   if (progress != NULL)
  581.     progress->completed_extra_passes++;
  582.  
  583.   /* Replace method pointer so subsequent calls don't come here. */
  584.   source->pub.get_pixel_rows = get_interlaced_row;
  585.   /* Initialize for get_interlaced_row, and perform first call on it. */
  586.   source->cur_row_number = 0;
  587.   source->pass2_offset = (cinfo->image_height + 7) / 8;
  588.   source->pass3_offset = source->pass2_offset + (cinfo->image_height + 3) / 8;
  589.   source->pass4_offset = source->pass3_offset + (cinfo->image_height + 1) / 4;
  590.  
  591.   return get_interlaced_row(cinfo, sinfo);
  592. }
  593.  
  594.  
  595. /*
  596.  * Read one row of pixels.
  597.  * This version is used for interlaced GIF images:
  598.  * we read from the virtual array.
  599.  */
  600.  
  601. METHODDEF JDIMENSION
  602. get_interlaced_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
  603. {
  604.   gif_source_ptr source = (gif_source_ptr) sinfo;
  605.   JSAMPARRAY image_ptr;
  606.   register int c;
  607.   register JSAMPROW sptr, ptr;
  608.   register JDIMENSION col;
  609.   register JSAMPARRAY colormap = source->colormap;
  610.   JDIMENSION irow;
  611.  
  612.   /* Figure out which row of interlaced image is needed, and access it. */
  613.   switch ((int) (source->cur_row_number & 7)) {
  614.   case 0:            /* first-pass row */
  615.     irow = source->cur_row_number >> 3;
  616.     break;
  617.   case 4:            /* second-pass row */
  618.     irow = (source->cur_row_number >> 3) + source->pass2_offset;
  619.     break;
  620.   case 2:            /* third-pass row */
  621.   case 6:
  622.     irow = (source->cur_row_number >> 2) + source->pass3_offset;
  623.     break;
  624.   default:            /* fourth-pass row */
  625.     irow = (source->cur_row_number >> 1) + source->pass4_offset;
  626.     break;
  627.   }
  628.   image_ptr = (*cinfo->mem->access_virt_sarray)
  629.     ((j_common_ptr) cinfo, source->interlaced_image, irow, FALSE);
  630.   /* Scan the row, expand colormap, and output */
  631.   sptr = image_ptr[0];
  632.   ptr = source->pub.buffer[0];
  633.   for (col = cinfo->image_width; col > 0; col--) {
  634.     c = GETJSAMPLE(*sptr++);
  635.     *ptr++ = colormap[CM_RED][c];
  636.     *ptr++ = colormap[CM_GREEN][c];
  637.     *ptr++ = colormap[CM_BLUE][c];
  638.   }
  639.   source->cur_row_number++;    /* for next time */
  640.   return 1;
  641. }
  642.  
  643.  
  644. /*
  645.  * Finish up at the end of the file.
  646.  */
  647.  
  648. METHODDEF void
  649. finish_input_gif (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
  650. {
  651.   /* no work */
  652. }
  653.  
  654.  
  655. /*
  656.  * The module selection routine for GIF format input.
  657.  */
  658.  
  659. GLOBAL cjpeg_source_ptr
  660. jinit_read_gif (j_compress_ptr cinfo)
  661. {
  662.   gif_source_ptr source;
  663.  
  664.   /* Create module interface object */
  665.   source = (gif_source_ptr)
  666.       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  667.                   SIZEOF(gif_source_struct));
  668.   source->cinfo = cinfo;    /* make back link for subroutines */
  669.   /* Fill in method ptrs, except get_pixel_rows which start_input sets */
  670.   source->pub.start_input = start_input_gif;
  671.   source->pub.finish_input = finish_input_gif;
  672.  
  673.   return (cjpeg_source_ptr) source;
  674. }
  675.  
  676. #endif /* GIF_SUPPORTED */
  677.