wrgif.c 18 KB

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