wrgif.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. /*
  2. * wrgif.c
  3. *
  4. * Copyright (C) 1991-1997, Thomas G. Lane.
  5. * Modified 2015 by Guido Vollbeding.
  6. * This file is part of the Independent JPEG Group's software.
  7. * For conditions of distribution and use, see the accompanying README file.
  8. *
  9. * This file contains routines to write output images in GIF format.
  10. *
  11. **************************************************************************
  12. * NOTE: to avoid entanglements with Unisys' patent on LZW compression, *
  13. * this code has been modified to output "uncompressed GIF" files. *
  14. * There is no trace of the LZW algorithm in this file. *
  15. **************************************************************************
  16. *
  17. * These routines may need modification for non-Unix environments or
  18. * specialized applications. As they stand, they assume output to
  19. * an ordinary stdio stream.
  20. */
  21. /*
  22. * This code is loosely based on ppmtogif from the PBMPLUS distribution
  23. * of Feb. 1991. That file contains the following copyright notice:
  24. * Based on GIFENCODE by David Rowley <[email protected]>.
  25. * Lempel-Ziv compression based on "compress" by Spencer W. Thomas et al.
  26. * Copyright (C) 1989 by Jef Poskanzer.
  27. * Permission to use, copy, modify, and distribute this software and its
  28. * documentation for any purpose and without fee is hereby granted, provided
  29. * that the above copyright notice appear in all copies and that both that
  30. * copyright notice and this permission notice appear in supporting
  31. * documentation. This software is provided "as is" without express or
  32. * implied warranty.
  33. *
  34. * We are also required to state that
  35. * "The Graphics Interchange Format(c) is the Copyright property of
  36. * CompuServe Incorporated. GIF(sm) is a Service Mark property of
  37. * CompuServe Incorporated."
  38. */
  39. #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
  40. #ifdef GIF_SUPPORTED
  41. /* Private version of data destination object */
  42. typedef struct {
  43. struct djpeg_dest_struct pub; /* public fields */
  44. j_decompress_ptr cinfo; /* back link saves passing separate parm */
  45. /* State for packing variable-width codes into a bitstream */
  46. int n_bits; /* current number of bits/code */
  47. int maxcode; /* maximum code, given n_bits */
  48. INT32 cur_accum; /* holds bits not yet output */
  49. int cur_bits; /* # of bits in cur_accum */
  50. /* State for GIF code assignment */
  51. int ClearCode; /* clear code (doesn't change) */
  52. int EOFCode; /* EOF code (ditto) */
  53. int code_counter; /* counts output symbols */
  54. /* GIF data packet construction buffer */
  55. int bytesinpkt; /* # of bytes in current packet */
  56. char packetbuf[256]; /* workspace for accumulating packet */
  57. } gif_dest_struct;
  58. typedef gif_dest_struct * gif_dest_ptr;
  59. /* Largest value that will fit in N bits */
  60. #define MAXCODE(n_bits) ((1 << (n_bits)) - 1)
  61. /*
  62. * Routines to package finished data bytes into GIF data blocks.
  63. * A data block consists of a count byte (1..255) and that many data bytes.
  64. */
  65. LOCAL(void)
  66. flush_packet (gif_dest_ptr dinfo)
  67. /* flush any accumulated data */
  68. {
  69. if (dinfo->bytesinpkt > 0) { /* never write zero-length packet */
  70. dinfo->packetbuf[0] = (char) dinfo->bytesinpkt++;
  71. if (JFWRITE(dinfo->pub.output_file, dinfo->packetbuf, dinfo->bytesinpkt)
  72. != (size_t) dinfo->bytesinpkt)
  73. ERREXIT(dinfo->cinfo, JERR_FILE_WRITE);
  74. dinfo->bytesinpkt = 0;
  75. }
  76. }
  77. /* Add a character to current packet; flush to disk if necessary */
  78. #define CHAR_OUT(dinfo,c) \
  79. { (dinfo)->packetbuf[++(dinfo)->bytesinpkt] = (char) (c); \
  80. if ((dinfo)->bytesinpkt >= 255) \
  81. flush_packet(dinfo); \
  82. }
  83. /* Routine to convert variable-width codes into a byte stream */
  84. LOCAL(void)
  85. output (gif_dest_ptr dinfo, int code)
  86. /* Emit a code of n_bits bits */
  87. /* Uses cur_accum and cur_bits to reblock into 8-bit bytes */
  88. {
  89. dinfo->cur_accum |= ((INT32) code) << dinfo->cur_bits;
  90. dinfo->cur_bits += dinfo->n_bits;
  91. while (dinfo->cur_bits >= 8) {
  92. CHAR_OUT(dinfo, dinfo->cur_accum & 0xFF);
  93. dinfo->cur_accum >>= 8;
  94. dinfo->cur_bits -= 8;
  95. }
  96. }
  97. /* The pseudo-compression algorithm.
  98. *
  99. * In this module we simply output each pixel value as a separate symbol;
  100. * thus, no compression occurs. In fact, there is expansion of one bit per
  101. * pixel, because we use a symbol width one bit wider than the pixel width.
  102. *
  103. * GIF ordinarily uses variable-width symbols, and the decoder will expect
  104. * to ratchet up the symbol width after a fixed number of symbols.
  105. * To simplify the logic and keep the expansion penalty down, we emit a
  106. * GIF Clear code to reset the decoder just before the width would ratchet up.
  107. * Thus, all the symbols in the output file will have the same bit width.
  108. * Note that emitting the Clear codes at the right times is a mere matter of
  109. * counting output symbols and is in no way dependent on the LZW patent.
  110. *
  111. * With a small basic pixel width (low color count), Clear codes will be
  112. * needed very frequently, causing the file to expand even more. So this
  113. * simplistic approach wouldn't work too well on bilevel images, for example.
  114. * But for output of JPEG conversions the pixel width will usually be 8 bits
  115. * (129 to 256 colors), so the overhead added by Clear symbols is only about
  116. * one symbol in every 256.
  117. */
  118. LOCAL(void)
  119. compress_init (gif_dest_ptr dinfo, int i_bits)
  120. /* Initialize pseudo-compressor */
  121. {
  122. /* init all the state variables */
  123. dinfo->n_bits = i_bits;
  124. dinfo->maxcode = MAXCODE(dinfo->n_bits);
  125. dinfo->ClearCode = (1 << (i_bits - 1));
  126. dinfo->EOFCode = dinfo->ClearCode + 1;
  127. dinfo->code_counter = dinfo->ClearCode + 2;
  128. /* init output buffering vars */
  129. dinfo->bytesinpkt = 0;
  130. dinfo->cur_accum = 0;
  131. dinfo->cur_bits = 0;
  132. /* GIF specifies an initial Clear code */
  133. output(dinfo, dinfo->ClearCode);
  134. }
  135. LOCAL(void)
  136. compress_pixel (gif_dest_ptr dinfo, int c)
  137. /* Accept and "compress" one pixel value.
  138. * The given value must be less than n_bits wide.
  139. */
  140. {
  141. /* Output the given pixel value as a symbol. */
  142. output(dinfo, c);
  143. /* Issue Clear codes often enough to keep the reader from ratcheting up
  144. * its symbol size.
  145. */
  146. if (dinfo->code_counter < dinfo->maxcode) {
  147. dinfo->code_counter++;
  148. } else {
  149. output(dinfo, dinfo->ClearCode);
  150. dinfo->code_counter = dinfo->ClearCode + 2; /* reset the counter */
  151. }
  152. }
  153. LOCAL(void)
  154. compress_term (gif_dest_ptr dinfo)
  155. /* Clean up at end */
  156. {
  157. /* Send an EOF code */
  158. output(dinfo, dinfo->EOFCode);
  159. /* Flush the bit-packing buffer */
  160. if (dinfo->cur_bits > 0) {
  161. CHAR_OUT(dinfo, dinfo->cur_accum & 0xFF);
  162. }
  163. /* Flush the packet buffer */
  164. flush_packet(dinfo);
  165. }
  166. /* GIF header construction */
  167. LOCAL(void)
  168. put_word (gif_dest_ptr dinfo, unsigned int w)
  169. /* Emit a 16-bit word, LSB first */
  170. {
  171. putc(w & 0xFF, dinfo->pub.output_file);
  172. putc((w >> 8) & 0xFF, dinfo->pub.output_file);
  173. }
  174. LOCAL(void)
  175. put_3bytes (gif_dest_ptr dinfo, int val)
  176. /* Emit 3 copies of same byte value --- handy subr for colormap construction */
  177. {
  178. putc(val, dinfo->pub.output_file);
  179. putc(val, dinfo->pub.output_file);
  180. putc(val, dinfo->pub.output_file);
  181. }
  182. LOCAL(void)
  183. emit_header (gif_dest_ptr dinfo, int num_colors, JSAMPARRAY colormap)
  184. /* Output the GIF file header, including color map */
  185. /* If colormap==NULL, synthesize a grayscale colormap */
  186. {
  187. int BitsPerPixel, ColorMapSize, InitCodeSize, FlagByte;
  188. int cshift = dinfo->cinfo->data_precision - 8;
  189. int i;
  190. if (num_colors > 256)
  191. ERREXIT1(dinfo->cinfo, JERR_TOO_MANY_COLORS, num_colors);
  192. /* Compute bits/pixel and related values */
  193. BitsPerPixel = 1;
  194. while (num_colors > (1 << BitsPerPixel))
  195. BitsPerPixel++;
  196. ColorMapSize = 1 << BitsPerPixel;
  197. if (BitsPerPixel <= 1)
  198. InitCodeSize = 2;
  199. else
  200. InitCodeSize = BitsPerPixel;
  201. /*
  202. * Write the GIF header.
  203. * Note that we generate a plain GIF87 header for maximum compatibility.
  204. */
  205. putc('G', dinfo->pub.output_file);
  206. putc('I', dinfo->pub.output_file);
  207. putc('F', dinfo->pub.output_file);
  208. putc('8', dinfo->pub.output_file);
  209. putc('7', dinfo->pub.output_file);
  210. putc('a', dinfo->pub.output_file);
  211. /* Write the Logical Screen Descriptor */
  212. put_word(dinfo, (unsigned int) dinfo->cinfo->output_width);
  213. put_word(dinfo, (unsigned int) dinfo->cinfo->output_height);
  214. FlagByte = 0x80; /* Yes, there is a global color table */
  215. FlagByte |= (BitsPerPixel-1) << 4; /* color resolution */
  216. FlagByte |= (BitsPerPixel-1); /* size of global color table */
  217. putc(FlagByte, dinfo->pub.output_file);
  218. putc(0, dinfo->pub.output_file); /* Background color index */
  219. putc(0, dinfo->pub.output_file); /* Reserved (aspect ratio in GIF89) */
  220. /* Write the Global Color Map */
  221. /* If the color map is more than 8 bits precision, */
  222. /* we reduce it to 8 bits by shifting */
  223. for (i=0; i < ColorMapSize; i++) {
  224. if (i < num_colors) {
  225. if (colormap != NULL) {
  226. if (dinfo->cinfo->out_color_space == JCS_RGB) {
  227. /* Normal case: RGB color map */
  228. putc(GETJSAMPLE(colormap[0][i]) >> cshift, dinfo->pub.output_file);
  229. putc(GETJSAMPLE(colormap[1][i]) >> cshift, dinfo->pub.output_file);
  230. putc(GETJSAMPLE(colormap[2][i]) >> cshift, dinfo->pub.output_file);
  231. } else {
  232. /* Grayscale "color map": possible if quantizing grayscale image */
  233. put_3bytes(dinfo, GETJSAMPLE(colormap[0][i]) >> cshift);
  234. }
  235. } else {
  236. /* Create a grayscale map of num_colors values, range 0..255 */
  237. put_3bytes(dinfo, (i * 255 + (num_colors-1)/2) / (num_colors-1));
  238. }
  239. } else {
  240. /* fill out the map to a power of 2 */
  241. put_3bytes(dinfo, 0);
  242. }
  243. }
  244. /* Write image separator and Image Descriptor */
  245. putc(',', dinfo->pub.output_file); /* separator */
  246. put_word(dinfo, 0); /* left/top offset */
  247. put_word(dinfo, 0);
  248. put_word(dinfo, (unsigned int) dinfo->cinfo->output_width); /* image size */
  249. put_word(dinfo, (unsigned int) dinfo->cinfo->output_height);
  250. /* flag byte: not interlaced, no local color map */
  251. putc(0x00, dinfo->pub.output_file);
  252. /* Write Initial Code Size byte */
  253. putc(InitCodeSize, dinfo->pub.output_file);
  254. /* Initialize for "compression" of image data */
  255. compress_init(dinfo, InitCodeSize+1);
  256. }
  257. /*
  258. * Startup: write the file header.
  259. */
  260. METHODDEF(void)
  261. start_output_gif (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
  262. {
  263. gif_dest_ptr dest = (gif_dest_ptr) dinfo;
  264. if (cinfo->quantize_colors)
  265. emit_header(dest, cinfo->actual_number_of_colors, cinfo->colormap);
  266. else
  267. emit_header(dest, 256, (JSAMPARRAY) NULL);
  268. }
  269. /*
  270. * Write some pixel data.
  271. * In this module rows_supplied will always be 1.
  272. */
  273. METHODDEF(void)
  274. put_pixel_rows (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo,
  275. JDIMENSION rows_supplied)
  276. {
  277. gif_dest_ptr dest = (gif_dest_ptr) dinfo;
  278. register JSAMPROW ptr;
  279. register JDIMENSION col;
  280. ptr = dest->pub.buffer[0];
  281. for (col = cinfo->output_width; col > 0; col--) {
  282. compress_pixel(dest, GETJSAMPLE(*ptr++));
  283. }
  284. }
  285. /*
  286. * Finish up at the end of the file.
  287. */
  288. METHODDEF(void)
  289. finish_output_gif (j_decompress_ptr cinfo, djpeg_dest_ptr dinfo)
  290. {
  291. gif_dest_ptr dest = (gif_dest_ptr) dinfo;
  292. /* Flush "compression" mechanism */
  293. compress_term(dest);
  294. /* Write a zero-length data block to end the series */
  295. putc(0, dest->pub.output_file);
  296. /* Write the GIF terminator mark */
  297. putc(';', dest->pub.output_file);
  298. /* Make sure we wrote the output file OK */
  299. fflush(dest->pub.output_file);
  300. if (ferror(dest->pub.output_file))
  301. ERREXIT(cinfo, JERR_FILE_WRITE);
  302. }
  303. /*
  304. * The module selection routine for GIF format output.
  305. */
  306. GLOBAL(djpeg_dest_ptr)
  307. jinit_write_gif (j_decompress_ptr cinfo)
  308. {
  309. gif_dest_ptr dest;
  310. /* Create module interface object, fill in method pointers */
  311. dest = (gif_dest_ptr)
  312. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  313. SIZEOF(gif_dest_struct));
  314. dest->cinfo = cinfo; /* make back link for subroutines */
  315. dest->pub.start_output = start_output_gif;
  316. dest->pub.put_pixel_rows = put_pixel_rows;
  317. dest->pub.finish_output = finish_output_gif;
  318. if (cinfo->out_color_space != JCS_GRAYSCALE &&
  319. cinfo->out_color_space != JCS_RGB)
  320. ERREXIT(cinfo, JERR_GIF_COLORSPACE);
  321. /* Force quantization if color or if > 8 bits input */
  322. if (cinfo->out_color_space != JCS_GRAYSCALE || cinfo->data_precision > 8) {
  323. /* Force quantization to at most 256 colors */
  324. cinfo->quantize_colors = TRUE;
  325. if (cinfo->desired_number_of_colors > 256)
  326. cinfo->desired_number_of_colors = 256;
  327. }
  328. /* Calculate output image dimensions so we can allocate space */
  329. jpeg_calc_output_dimensions(cinfo);
  330. if (cinfo->output_components != 1) /* safety check: just one component? */
  331. ERREXIT(cinfo, JERR_GIF_BUG);
  332. /* Create decompressor output buffer. */
  333. dest->pub.buffer = (*cinfo->mem->alloc_sarray)
  334. ((j_common_ptr) cinfo, JPOOL_IMAGE, cinfo->output_width, (JDIMENSION) 1);
  335. dest->pub.buffer_height = 1;
  336. return &dest->pub;
  337. }
  338. #endif /* GIF_SUPPORTED */