wrgif.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. /*
  2. * wrgif.c
  3. *
  4. * Copyright (C) 1991-1996, 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. if (dinfo->hash_code[i] != 0) { /* is first probed slot empty? */
  195. if (dinfo->hash_value[i] == probe_value) {
  196. dinfo->waiting_code = dinfo->hash_code[i];
  197. return;
  198. }
  199. if (i == 0) /* secondary hash (after G. Knott) */
  200. disp = 1;
  201. else
  202. disp = HSIZE - i;
  203. for (;;) {
  204. i -= disp;
  205. if (i < 0)
  206. i += HSIZE;
  207. if (dinfo->hash_code[i] == 0)
  208. break; /* hit empty slot */
  209. if (dinfo->hash_value[i] == probe_value) {
  210. dinfo->waiting_code = dinfo->hash_code[i];
  211. return;
  212. }
  213. }
  214. }
  215. /* here when hashtable[i] is an empty slot; desired symbol not in table */
  216. output(dinfo, dinfo->waiting_code);
  217. if (dinfo->free_code < LZW_TABLE_SIZE) {
  218. dinfo->hash_code[i] = dinfo->free_code++; /* add symbol to hashtable */
  219. dinfo->hash_value[i] = probe_value;
  220. } else
  221. clear_block(dinfo);
  222. dinfo->waiting_code = c;
  223. }
  224. LOCAL(void)
  225. compress_term (gif_dest_ptr dinfo)
  226. /* Clean up at end */
  227. {
  228. /* Flush out the buffered code */
  229. if (! dinfo->first_byte)
  230. output(dinfo, dinfo->waiting_code);
  231. /* Send an EOF code */
  232. output(dinfo, dinfo->EOFCode);
  233. /* Flush the bit-packing buffer */
  234. if (dinfo->cur_bits > 0) {
  235. CHAR_OUT(dinfo, dinfo->cur_accum & 0xFF);
  236. }
  237. /* Flush the packet buffer */
  238. flush_packet(dinfo);
  239. }
  240. /* GIF header construction */
  241. LOCAL(void)
  242. put_word (gif_dest_ptr dinfo, unsigned int w)
  243. /* Emit a 16-bit word, LSB first */
  244. {
  245. putc(w & 0xFF, dinfo->pub.output_file);
  246. putc((w >> 8) & 0xFF, dinfo->pub.output_file);
  247. }
  248. LOCAL(void)
  249. put_3bytes (gif_dest_ptr dinfo, int val)
  250. /* Emit 3 copies of same byte value --- handy subr for colormap construction */
  251. {
  252. putc(val, dinfo->pub.output_file);
  253. putc(val, dinfo->pub.output_file);
  254. putc(val, dinfo->pub.output_file);
  255. }
  256. LOCAL(void)
  257. emit_header (gif_dest_ptr dinfo, int num_colors, JSAMPARRAY colormap)
  258. /* Output the GIF file header, including color map */
  259. /* If colormap==NULL, synthesize a gray-scale colormap */
  260. {
  261. int BitsPerPixel, ColorMapSize, InitCodeSize, FlagByte;
  262. int cshift = dinfo->cinfo->data_precision - 8;
  263. int i;
  264. if (num_colors > 256)
  265. ERREXIT1(dinfo->cinfo, JERR_TOO_MANY_COLORS, num_colors);
  266. /* Compute bits/pixel and related values */
  267. BitsPerPixel = 1;
  268. while (num_colors > (1 << BitsPerPixel))
  269. BitsPerPixel++;
  270. ColorMapSize = 1 << BitsPerPixel;
  271. if (BitsPerPixel <= 1)
  272. InitCodeSize = 2;
  273. else
  274. InitCodeSize = BitsPerPixel;
  275. /*
  276. * Write the GIF header.
  277. * Note that we generate a plain GIF87 header for maximum compatibility.
  278. */
  279. putc('G', dinfo->pub.output_file);
  280. putc('I', dinfo->pub.output_file);
  281. putc('F', dinfo->pub.output_file);
  282. putc('8', dinfo->pub.output_file);
  283. putc('7', dinfo->pub.output_file);
  284. putc('a', dinfo->pub.output_file);
  285. /* Write the Logical Screen Descriptor */
  286. put_word(dinfo, (unsigned int) dinfo->cinfo->output_width);
  287. put_word(dinfo, (unsigned int) dinfo->cinfo->output_height);
  288. FlagByte = 0x80; /* Yes, there is a global color table */
  289. FlagByte |= (BitsPerPixel-1) << 4; /* color resolution */
  290. FlagByte |= (BitsPerPixel-1); /* size of global color table */
  291. putc(FlagByte, dinfo->pub.output_file);
  292. putc(0, dinfo->pub.output_file); /* Background color index */
  293. putc(0, dinfo->pub.output_file); /* Reserved (aspect ratio in GIF89) */
  294. /* Write the Global Color Map */
  295. /* If the color map is more than 8 bits precision, */
  296. /* we reduce it to 8 bits by shifting */
  297. for (i=0; i < ColorMapSize; i++) {
  298. if (i < num_colors) {
  299. if (colormap != NULL) {
  300. if (dinfo->cinfo->out_color_space == JCS_RGB) {
  301. /* Normal case: RGB color map */
  302. putc(GETJSAMPLE(colormap[0][i]) >> cshift, dinfo->pub.output_file);
  303. putc(GETJSAMPLE(colormap[1][i]) >> cshift, dinfo->pub.output_file);
  304. putc(GETJSAMPLE(colormap[2][i]) >> cshift, dinfo->pub.output_file);
  305. } else {
  306. /* Grayscale "color map": possible if quantizing grayscale image */
  307. put_3bytes(dinfo, GETJSAMPLE(colormap[0][i]) >> cshift);
  308. }
  309. } else {
  310. /* Create a gray-scale map of num_colors values, range 0..255 */
  311. put_3bytes(dinfo, (i * 255 + (num_colors-1)/2) / (num_colors-1));
  312. }
  313. } else {
  314. /* fill out the map to a power of 2 */
  315. put_3bytes(dinfo, 0);
  316. }
  317. }
  318. /* Write image separator and Image Descriptor */
  319. putc(',', dinfo->pub.output_file); /* separator */
  320. put_word(dinfo, 0); /* left/top offset */
  321. put_word(dinfo, 0);
  322. put_word(dinfo, (unsigned int) dinfo->cinfo->output_width); /* image size */
  323. put_word(dinfo, (unsigned int) dinfo->cinfo->output_height);
  324. /* flag byte: not interlaced, no local color map */
  325. putc(0x00, dinfo->pub.output_file);
  326. /* Write Initial Code Size byte */
  327. putc(InitCodeSize, dinfo->pub.output_file);
  328. /* Initialize for LZW compression of image data */
  329. compress_init(dinfo, InitCodeSize+1);
  330. }
  331. /*
  332. * Startup: write the file header.
  333. */
  334. METHODDEF(void)
  335. start_output_gif (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
  336. {
  337. gif_dest_ptr dest = (gif_dest_ptr) dinfo;
  338. if (cinfo->quantize_colors)
  339. emit_header(dest, cinfo->actual_number_of_colors, cinfo->colormap);
  340. else
  341. emit_header(dest, 256, (JSAMPARRAY) NULL);
  342. }
  343. /*
  344. * Write some pixel data.
  345. * In this module rows_supplied will always be 1.
  346. */
  347. METHODDEF(void)
  348. put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
  349. JDIMENSION rows_supplied)
  350. {
  351. gif_dest_ptr dest = (gif_dest_ptr) dinfo;
  352. register JSAMPROW ptr;
  353. register JDIMENSION col;
  354. ptr = dest->pub.buffer[0];
  355. for (col = cinfo->output_width; col > 0; col--) {
  356. compress_byte(dest, GETJSAMPLE(*ptr++));
  357. }
  358. }
  359. /*
  360. * Finish up at the end of the file.
  361. */
  362. METHODDEF(void)
  363. finish_output_gif (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
  364. {
  365. gif_dest_ptr dest = (gif_dest_ptr) dinfo;
  366. /* Flush LZW mechanism */
  367. compress_term(dest);
  368. /* Write a zero-length data block to end the series */
  369. putc(0, dest->pub.output_file);
  370. /* Write the GIF terminator mark */
  371. putc(';', dest->pub.output_file);
  372. /* Make sure we wrote the output file OK */
  373. fflush(dest->pub.output_file);
  374. if (ferror(dest->pub.output_file))
  375. ERREXIT(cinfo, JERR_FILE_WRITE);
  376. }
  377. /*
  378. * The module selection routine for GIF format output.
  379. */
  380. GLOBAL(djpeg_dest_ptr)
  381. jinit_write_gif (j_decompress_ptr cinfo)
  382. {
  383. gif_dest_ptr dest;
  384. /* Create module interface object, fill in method pointers */
  385. dest = (gif_dest_ptr)
  386. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  387. SIZEOF(gif_dest_struct));
  388. dest->cinfo = cinfo; /* make back link for subroutines */
  389. dest->pub.start_output = start_output_gif;
  390. dest->pub.put_pixel_rows = put_pixel_rows;
  391. dest->pub.finish_output = finish_output_gif;
  392. if (cinfo->out_color_space != JCS_GRAYSCALE &&
  393. cinfo->out_color_space != JCS_RGB)
  394. ERREXIT(cinfo, JERR_GIF_COLORSPACE);
  395. /* Force quantization if color or if > 8 bits input */
  396. if (cinfo->out_color_space != JCS_GRAYSCALE || cinfo->data_precision > 8) {
  397. /* Force quantization to at most 256 colors */
  398. cinfo->quantize_colors = TRUE;
  399. if (cinfo->desired_number_of_colors > 256)
  400. cinfo->desired_number_of_colors = 256;
  401. }
  402. /* Calculate output image dimensions so we can allocate space */
  403. jpeg_calc_output_dimensions(cinfo);
  404. if (cinfo->output_components != 1) /* safety check: just one component? */
  405. ERREXIT(cinfo, JERR_GIF_BUG);
  406. /* Create decompressor output buffer. */
  407. dest->pub.buffer = (*cinfo->mem->alloc_sarray)
  408. ((j_common_ptr) cinfo, JPOOL_IMAGE, cinfo->output_width, (JDIMENSION) 1);
  409. dest->pub.buffer_height = 1;
  410. /* Allocate space for hash table */
  411. dest->hash_code = (code_int *)
  412. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  413. HSIZE * SIZEOF(code_int));
  414. dest->hash_value = (hash_entry FAR *)
  415. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  416. HSIZE * SIZEOF(hash_entry));
  417. return (djpeg_dest_ptr) dest;
  418. }
  419. #endif /* GIF_SUPPORTED */