wrgif.c 13 KB

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