wrgif.c
上传用户:zlh9724
上传日期:2007-01-04
资源大小:1991k
文件大小:15k
源码类别:

浏览器

开发平台:

Unix_Linux

  1. /*
  2.  * wrgif.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.  **************************************************************************
  9.  * WARNING: You will need an LZW patent license from Unisys in order to   *
  10.  * use this file legally in any commercial or shareware application.      *
  11.  **************************************************************************
  12.  *
  13.  * This file contains routines to write output images in GIF format.
  14.  *
  15.  * These routines may need modification for non-Unix environments or
  16.  * specialized applications.  As they stand, they assume output to
  17.  * an ordinary stdio stream.
  18.  */
  19. /*
  20.  * This code is loosely based on ppmtogif from the PBMPLUS distribution
  21.  * of Feb. 1991.  That file contains the following copyright notice:
  22.  *    Based on GIFENCODE by David Rowley <mgardi@watdscu.waterloo.edu>.
  23.  *    Lempel-Ziv compression based on "compress" by Spencer W. Thomas et al.
  24.  *    Copyright (C) 1989 by Jef Poskanzer.
  25.  *    Permission to use, copy, modify, and distribute this software and its
  26.  *    documentation for any purpose and without fee is hereby granted, provided
  27.  *    that the above copyright notice appear in all copies and that both that
  28.  *    copyright notice and this permission notice appear in supporting
  29.  *    documentation.  This software is provided "as is" without express or
  30.  *    implied warranty.
  31.  *
  32.  * We are also required to state that
  33.  *    "The Graphics Interchange Format(c) is the Copyright property of
  34.  *    CompuServe Incorporated. GIF(sm) is a Service Mark property of
  35.  *    CompuServe Incorporated."
  36.  */
  37. #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
  38. #ifdef GIF_SUPPORTED
  39. #define MAX_LZW_BITS 12 /* maximum LZW code size (4096 symbols) */
  40. typedef INT16 code_int; /* must hold -1 .. 2**MAX_LZW_BITS */
  41. #define LZW_TABLE_SIZE ((code_int) 1 << MAX_LZW_BITS)
  42. #define HSIZE 5003 /* hash table size for 80% occupancy */
  43. typedef int hash_int; /* must hold -2*HSIZE..2*HSIZE */
  44. #define MAXCODE(n_bits) (((code_int) 1 << (n_bits)) - 1)
  45. /*
  46.  * The LZW hash table consists of two parallel arrays:
  47.  *   hash_code[i] code of symbol in slot i, or 0 if empty slot
  48.  *   hash_value[i] symbol's value; undefined if empty slot
  49.  * where slot values (i) range from 0 to HSIZE-1.  The symbol value is
  50.  * its prefix symbol's code concatenated with its suffix character.
  51.  *
  52.  * Algorithm:  use open addressing double hashing (no chaining) on the
  53.  * prefix code / suffix character combination.  We do a variant of Knuth's
  54.  * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
  55.  * secondary probe.
  56.  *
  57.  * The hash_value[] table is allocated from FAR heap space since it would
  58.  * use up rather a lot of the near data space in a PC.
  59.  */
  60. typedef INT32 hash_entry; /* must hold (code_int<<8) | byte */
  61. #define HASH_ENTRY(prefix,suffix)  ((((hash_entry) (prefix)) << 8) | (suffix))
  62. /* Private version of data destination object */
  63. typedef struct {
  64.   struct djpeg_dest_struct pub; /* public fields */
  65.   j_decompress_ptr cinfo; /* back link saves passing separate parm */
  66.   /* State for packing variable-width codes into a bitstream */
  67.   int n_bits; /* current number of bits/code */
  68.   code_int maxcode; /* maximum code, given n_bits */
  69.   int init_bits; /* initial n_bits ... restored after clear */
  70.   INT32 cur_accum; /* holds bits not yet output */
  71.   int cur_bits; /* # of bits in cur_accum */
  72.   /* LZW string construction */
  73.   code_int waiting_code; /* symbol not yet output; may be extendable */
  74.   boolean first_byte; /* if TRUE, waiting_code is not valid */
  75.   /* State for LZW code assignment */
  76.   code_int ClearCode; /* clear code (doesn't change) */
  77.   code_int EOFCode; /* EOF code (ditto) */
  78.   code_int free_code; /* first not-yet-used symbol code */
  79.   /* LZW hash table */
  80.   code_int *hash_code; /* => hash table of symbol codes */
  81.   hash_entry FAR *hash_value; /* => hash table of symbol values */
  82.   /* GIF data packet construction buffer */
  83.   int bytesinpkt; /* # of bytes in current packet */
  84.   char packetbuf[256]; /* workspace for accumulating packet */
  85. } gif_dest_struct;
  86. typedef gif_dest_struct * gif_dest_ptr;
  87. /*
  88.  * Routines to package compressed data bytes into GIF data blocks.
  89.  * A data block consists of a count byte (1..255) and that many data bytes.
  90.  */
  91. LOCAL void
  92. flush_packet (gif_dest_ptr dinfo)
  93. /* flush any accumulated data */
  94. {
  95.   if (dinfo->bytesinpkt > 0) { /* never write zero-length packet */
  96.     dinfo->packetbuf[0] = (char) dinfo->bytesinpkt++;
  97.     if (JFWRITE(dinfo->pub.output_file, dinfo->packetbuf, dinfo->bytesinpkt)
  98. != (size_t) dinfo->bytesinpkt)
  99.       ERREXIT(dinfo->cinfo, JERR_FILE_WRITE);
  100.     dinfo->bytesinpkt = 0;
  101.   }
  102. }
  103. /* Add a character to current packet; flush to disk if necessary */
  104. #define CHAR_OUT(dinfo,c)  
  105. { (dinfo)->packetbuf[++(dinfo)->bytesinpkt] = (char) (c);  
  106.     if ((dinfo)->bytesinpkt >= 255)  
  107.       flush_packet(dinfo);  
  108. }
  109. /* Routine to convert variable-width codes into a byte stream */
  110. LOCAL void
  111. output (gif_dest_ptr dinfo, code_int code)
  112. /* Emit a code of n_bits bits */
  113. /* Uses cur_accum and cur_bits to reblock into 8-bit bytes */
  114. {
  115.   dinfo->cur_accum |= ((INT32) code) << dinfo->cur_bits;
  116.   dinfo->cur_bits += dinfo->n_bits;
  117.   while (dinfo->cur_bits >= 8) {
  118.     CHAR_OUT(dinfo, dinfo->cur_accum & 0xFF);
  119.     dinfo->cur_accum >>= 8;
  120.     dinfo->cur_bits -= 8;
  121.   }
  122.   /*
  123.    * If the next entry is going to be too big for the code size,
  124.    * then increase it, if possible.  We do this here to ensure
  125.    * that it's done in sync with the decoder's codesize increases.
  126.    */
  127.   if (dinfo->free_code > dinfo->maxcode) {
  128.     dinfo->n_bits++;
  129.     if (dinfo->n_bits == MAX_LZW_BITS)
  130.       dinfo->maxcode = LZW_TABLE_SIZE; /* free_code will never exceed this */
  131.     else
  132.       dinfo->maxcode = MAXCODE(dinfo->n_bits);
  133.   }
  134. }
  135. /* The LZW algorithm proper */
  136. LOCAL void
  137. clear_hash (gif_dest_ptr dinfo)
  138. /* Fill the hash table with empty entries */
  139. {
  140.   /* It's sufficient to zero hash_code[] */
  141.   MEMZERO(dinfo->hash_code, HSIZE * SIZEOF(code_int));
  142. }
  143. LOCAL void
  144. clear_block (gif_dest_ptr dinfo)
  145. /* Reset compressor and issue a Clear code */
  146. {
  147.   clear_hash(dinfo); /* delete all the symbols */
  148.   dinfo->free_code = dinfo->ClearCode + 2;
  149.   output(dinfo, dinfo->ClearCode); /* inform decoder */
  150.   dinfo->n_bits = dinfo->init_bits; /* reset code size */
  151.   dinfo->maxcode = MAXCODE(dinfo->n_bits);
  152. }
  153. LOCAL void
  154. compress_init (gif_dest_ptr dinfo, int i_bits)
  155. /* Initialize LZW compressor */
  156. {
  157.   /* init all the state variables */
  158.   dinfo->n_bits = dinfo->init_bits = i_bits;
  159.   dinfo->maxcode = MAXCODE(dinfo->n_bits);
  160.   dinfo->ClearCode = ((code_int) 1 << (i_bits - 1));
  161.   dinfo->EOFCode = dinfo->ClearCode + 1;
  162.   dinfo->free_code = dinfo->ClearCode + 2;
  163.   dinfo->first_byte = TRUE; /* no waiting symbol yet */
  164.   /* init output buffering vars */
  165.   dinfo->bytesinpkt = 0;
  166.   dinfo->cur_accum = 0;
  167.   dinfo->cur_bits = 0;
  168.   /* clear hash table */
  169.   clear_hash(dinfo);
  170.   /* GIF specifies an initial Clear code */
  171.   output(dinfo, dinfo->ClearCode);
  172. }
  173. LOCAL void
  174. compress_byte (gif_dest_ptr dinfo, int c)
  175. /* Accept and compress one 8-bit byte */
  176. {
  177.   register hash_int i;
  178.   register hash_int disp;
  179.   register hash_entry probe_value;
  180.   if (dinfo->first_byte) { /* need to initialize waiting_code */
  181.     dinfo->waiting_code = c;
  182.     dinfo->first_byte = FALSE;
  183.     return;
  184.   }
  185.   /* Probe hash table to see if a symbol exists for
  186.    * waiting_code followed by c.
  187.    * If so, replace waiting_code by that symbol and return.
  188.    */
  189.   i = ((hash_int) c << (MAX_LZW_BITS-8)) + dinfo->waiting_code;
  190.   /* i is less than twice 2**MAX_LZW_BITS, therefore less than twice HSIZE */
  191.   if (i >= HSIZE)
  192.     i -= HSIZE;
  193.   probe_value = HASH_ENTRY(dinfo->waiting_code, c);
  194.   
  195.   if (dinfo->hash_code[i] != 0) { /* is first probed slot empty? */
  196.     if (dinfo->hash_value[i] == probe_value) {
  197.       dinfo->waiting_code = dinfo->hash_code[i];
  198.       return;
  199.     }
  200.     if (i == 0) /* secondary hash (after G. Knott) */
  201.       disp = 1;
  202.     else
  203.       disp = HSIZE - i;
  204.     for (;;) {
  205.       i -= disp;
  206.       if (i < 0)
  207. i += HSIZE;
  208.       if (dinfo->hash_code[i] == 0)
  209. break; /* hit empty slot */
  210.       if (dinfo->hash_value[i] == probe_value) {
  211. dinfo->waiting_code = dinfo->hash_code[i];
  212. return;
  213.       }
  214.     }
  215.   }
  216.   /* here when hashtable[i] is an empty slot; desired symbol not in table */
  217.   output(dinfo, dinfo->waiting_code);
  218.   if (dinfo->free_code < LZW_TABLE_SIZE) {
  219.     dinfo->hash_code[i] = dinfo->free_code++; /* add symbol to hashtable */
  220.     dinfo->hash_value[i] = probe_value;
  221.   } else
  222.     clear_block(dinfo);
  223.   dinfo->waiting_code = c;
  224. }
  225. LOCAL void
  226. compress_term (gif_dest_ptr dinfo)
  227. /* Clean up at end */
  228. {
  229.   /* Flush out the buffered code */
  230.   if (! dinfo->first_byte)
  231.     output(dinfo, dinfo->waiting_code);
  232.   /* Send an EOF code */
  233.   output(dinfo, dinfo->EOFCode);
  234.   /* Flush the bit-packing buffer */
  235.   if (dinfo->cur_bits > 0) {
  236.     CHAR_OUT(dinfo, dinfo->cur_accum & 0xFF);
  237.   }
  238.   /* Flush the packet buffer */
  239.   flush_packet(dinfo);
  240. }
  241. /* GIF header construction */
  242. LOCAL void
  243. put_word (gif_dest_ptr dinfo, unsigned int w)
  244. /* Emit a 16-bit word, LSB first */
  245. {
  246.   putc(w & 0xFF, dinfo->pub.output_file);
  247.   putc((w >> 8) & 0xFF, dinfo->pub.output_file);
  248. }
  249. LOCAL void
  250. put_3bytes (gif_dest_ptr dinfo, int val)
  251. /* Emit 3 copies of same byte value --- handy subr for colormap construction */
  252. {
  253.   putc(val, dinfo->pub.output_file);
  254.   putc(val, dinfo->pub.output_file);
  255.   putc(val, dinfo->pub.output_file);
  256. }
  257. LOCAL void
  258. emit_header (gif_dest_ptr dinfo, int num_colors, JSAMPARRAY colormap)
  259. /* Output the GIF file header, including color map */
  260. /* If colormap==NULL, synthesize a gray-scale colormap */
  261. {
  262.   int BitsPerPixel, ColorMapSize, InitCodeSize, FlagByte;
  263.   int cshift = dinfo->cinfo->data_precision - 8;
  264.   int i;
  265.   if (num_colors > 256)
  266.     ERREXIT1(dinfo->cinfo, JERR_TOO_MANY_COLORS, num_colors);
  267.   /* Compute bits/pixel and related values */
  268.   BitsPerPixel = 1;
  269.   while (num_colors > (1 << BitsPerPixel))
  270.     BitsPerPixel++;
  271.   ColorMapSize = 1 << BitsPerPixel;
  272.   if (BitsPerPixel <= 1)
  273.     InitCodeSize = 2;
  274.   else
  275.     InitCodeSize = BitsPerPixel;
  276.   /*
  277.    * Write the GIF header.
  278.    * Note that we generate a plain GIF87 header for maximum compatibility.
  279.    */
  280.   putc('G', dinfo->pub.output_file);
  281.   putc('I', dinfo->pub.output_file);
  282.   putc('F', dinfo->pub.output_file);
  283.   putc('8', dinfo->pub.output_file);
  284.   putc('7', dinfo->pub.output_file);
  285.   putc('a', dinfo->pub.output_file);
  286.   /* Write the Logical Screen Descriptor */
  287.   put_word(dinfo, (unsigned int) dinfo->cinfo->output_width);
  288.   put_word(dinfo, (unsigned int) dinfo->cinfo->output_height);
  289.   FlagByte = 0x80; /* Yes, there is a global color table */
  290.   FlagByte |= (BitsPerPixel-1) << 4; /* color resolution */
  291.   FlagByte |= (BitsPerPixel-1); /* size of global color table */
  292.   putc(FlagByte, dinfo->pub.output_file);
  293.   putc(0, dinfo->pub.output_file); /* Background color index */
  294.   putc(0, dinfo->pub.output_file); /* Reserved (aspect ratio in GIF89) */
  295.   /* Write the Global Color Map */
  296.   /* If the color map is more than 8 bits precision, */
  297.   /* we reduce it to 8 bits by shifting */
  298.   for (i=0; i < ColorMapSize; i++) {
  299.     if (i < num_colors) {
  300.       if (colormap != NULL) {
  301. if (dinfo->cinfo->out_color_space == JCS_RGB) {
  302.   /* Normal case: RGB color map */
  303.   putc(GETJSAMPLE(colormap[0][i]) >> cshift, dinfo->pub.output_file);
  304.   putc(GETJSAMPLE(colormap[1][i]) >> cshift, dinfo->pub.output_file);
  305.   putc(GETJSAMPLE(colormap[2][i]) >> cshift, dinfo->pub.output_file);
  306. } else {
  307.   /* Grayscale "color map": possible if quantizing grayscale image */
  308.   put_3bytes(dinfo, GETJSAMPLE(colormap[0][i]) >> cshift);
  309. }
  310.       } else {
  311. /* Create a gray-scale map of num_colors values, range 0..255 */
  312. put_3bytes(dinfo, (i * 255 + (num_colors-1)/2) / (num_colors-1));
  313.       }
  314.     } else {
  315.       /* fill out the map to a power of 2 */
  316.       put_3bytes(dinfo, 0);
  317.     }
  318.   }
  319.   /* Write image separator and Image Descriptor */
  320.   putc(',', dinfo->pub.output_file); /* separator */
  321.   put_word(dinfo, 0); /* left/top offset */
  322.   put_word(dinfo, 0);
  323.   put_word(dinfo, (unsigned int) dinfo->cinfo->output_width); /* image size */
  324.   put_word(dinfo, (unsigned int) dinfo->cinfo->output_height);
  325.   /* flag byte: not interlaced, no local color map */
  326.   putc(0x00, dinfo->pub.output_file);
  327.   /* Write Initial Code Size byte */
  328.   putc(InitCodeSize, dinfo->pub.output_file);
  329.   /* Initialize for LZW compression of image data */
  330.   compress_init(dinfo, InitCodeSize+1);
  331. }
  332. /*
  333.  * Startup: write the file header.
  334.  */
  335. METHODDEF void
  336. start_output_gif (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
  337. {
  338.   gif_dest_ptr dest = (gif_dest_ptr) dinfo;
  339.   if (cinfo->quantize_colors)
  340.     emit_header(dest, cinfo->actual_number_of_colors, cinfo->colormap);
  341.   else
  342.     emit_header(dest, 256, (JSAMPARRAY) NULL);
  343. }
  344. /*
  345.  * Write some pixel data.
  346.  * In this module rows_supplied will always be 1.
  347.  */
  348. METHODDEF void
  349. put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
  350. JDIMENSION rows_supplied)
  351. {
  352.   gif_dest_ptr dest = (gif_dest_ptr) dinfo;
  353.   register JSAMPROW ptr;
  354.   register JDIMENSION col;
  355.   ptr = dest->pub.buffer[0];
  356.   for (col = cinfo->output_width; col > 0; col--) {
  357.     compress_byte(dest, GETJSAMPLE(*ptr++));
  358.   }
  359. }
  360. /*
  361.  * Finish up at the end of the file.
  362.  */
  363. METHODDEF void
  364. finish_output_gif (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
  365. {
  366.   gif_dest_ptr dest = (gif_dest_ptr) dinfo;
  367.   /* Flush LZW mechanism */
  368.   compress_term(dest);
  369.   /* Write a zero-length data block to end the series */
  370.   putc(0, dest->pub.output_file);
  371.   /* Write the GIF terminator mark */
  372.   putc(';', dest->pub.output_file);
  373.   /* Make sure we wrote the output file OK */
  374.   fflush(dest->pub.output_file);
  375.   if (ferror(dest->pub.output_file))
  376.     ERREXIT(cinfo, JERR_FILE_WRITE);
  377. }
  378. /*
  379.  * The module selection routine for GIF format output.
  380.  */
  381. GLOBAL djpeg_dest_ptr
  382. jinit_write_gif (j_decompress_ptr cinfo)
  383. {
  384.   gif_dest_ptr dest;
  385.   /* Create module interface object, fill in method pointers */
  386.   dest = (gif_dest_ptr)
  387.       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  388.   SIZEOF(gif_dest_struct));
  389.   dest->cinfo = cinfo; /* make back link for subroutines */
  390.   dest->pub.start_output = start_output_gif;
  391.   dest->pub.put_pixel_rows = put_pixel_rows;
  392.   dest->pub.finish_output = finish_output_gif;
  393.   if (cinfo->out_color_space != JCS_GRAYSCALE &&
  394.       cinfo->out_color_space != JCS_RGB)
  395.     ERREXIT(cinfo, JERR_GIF_COLORSPACE);
  396.   /* Force quantization if color or if > 8 bits input */
  397.   if (cinfo->out_color_space != JCS_GRAYSCALE || cinfo->data_precision > 8) {
  398.     /* Force quantization to at most 256 colors */
  399.     cinfo->quantize_colors = TRUE;
  400.     if (cinfo->desired_number_of_colors > 256)
  401.       cinfo->desired_number_of_colors = 256;
  402.   }
  403.   /* Calculate output image dimensions so we can allocate space */
  404.   jpeg_calc_output_dimensions(cinfo);
  405.   if (cinfo->output_components != 1) /* safety check: just one component? */
  406.     ERREXIT(cinfo, JERR_GIF_BUG);
  407.   /* Create decompressor output buffer. */
  408.   dest->pub.buffer = (*cinfo->mem->alloc_sarray)
  409.     ((j_common_ptr) cinfo, JPOOL_IMAGE, cinfo->output_width, (JDIMENSION) 1);
  410.   dest->pub.buffer_height = 1;
  411.   /* Allocate space for hash table */
  412.   dest->hash_code = (code_int *)
  413.     (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  414. HSIZE * SIZEOF(code_int));
  415.   dest->hash_value = (hash_entry FAR *)
  416.     (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  417. HSIZE * SIZEOF(hash_entry));
  418.   return (djpeg_dest_ptr) dest;
  419. }
  420. #endif /* GIF_SUPPORTED */