8 * Copyright (C) 1991-1997, Thomas G. Lane.
9 * This file is part of the Independent JPEG Group's software.
10 * For conditions of distribution and use, see the accompanying README file.
12 * This file contains routines to write output images in GIF format.
14 **************************************************************************
15 * NOTE: to avoid entanglements with Unisys' patent on LZW compression, *
16 * this code has been modified to output "uncompressed GIF" files. *
17 * There is no trace of the LZW algorithm in this file. *
18 **************************************************************************
20 * These routines may need modification for non-Unix environments or
21 * specialized applications. As they stand, they assume output to
22 * an ordinary stdio stream.
26 * This code is loosely based on ppmtogif from the PBMPLUS distribution
27 * of Feb. 1991. That file contains the following copyright notice:
28 * Based on GIFENCODE by David Rowley <mgardi@watdscu.waterloo.edu>.
29 * Lempel-Ziv compression based on "compress" by Spencer W. Thomas et al.
30 * Copyright (C) 1989 by Jef Poskanzer.
31 * Permission to use, copy, modify, and distribute this software and its
32 * documentation for any purpose and without fee is hereby granted, provided
33 * that the above copyright notice appear in all copies and that both that
34 * copyright notice and this permission notice appear in supporting
35 * documentation. This software is provided "as is" without express or
38 * We are also required to state that
39 * "The Graphics Interchange Format(c) is the Copyright property of
40 * CompuServe Incorporated. GIF(sm) is a Service Mark property of
41 * CompuServe Incorporated."
44 #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
49 /* Private version of data destination object */
52 struct djpeg_dest_struct pub
; /* public fields */
54 j_decompress_ptr cinfo
; /* back link saves passing separate parm */
56 /* State for packing variable-width codes into a bitstream */
57 int n_bits
; /* current number of bits/code */
58 int maxcode
; /* maximum code, given n_bits */
59 INT32 cur_accum
; /* holds bits not yet output */
60 int cur_bits
; /* # of bits in cur_accum */
62 /* State for GIF code assignment */
63 int ClearCode
; /* clear code (doesn't change) */
64 int EOFCode
; /* EOF code (ditto) */
65 int code_counter
; /* counts output symbols */
67 /* GIF data packet construction buffer */
68 int bytesinpkt
; /* # of bytes in current packet */
69 char packetbuf
[256]; /* workspace for accumulating packet */
73 typedef gif_dest_struct
* gif_dest_ptr
;
75 /* Largest value that will fit in N bits */
76 #define MAXCODE(n_bits) ((1 << (n_bits)) - 1)
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.
85 flush_packet (gif_dest_ptr dinfo
)
86 /* flush any accumulated data */
88 if (dinfo
->bytesinpkt
> 0) { /* never write zero-length packet */
89 dinfo
->packetbuf
[0] = (char) dinfo
->bytesinpkt
++;
90 if (JFWRITE(dinfo
->pub
.output_file
, dinfo
->packetbuf
, dinfo
->bytesinpkt
)
91 != (size_t) dinfo
->bytesinpkt
)
92 ERREXIT(dinfo
->cinfo
, JERR_FILE_WRITE
);
93 dinfo
->bytesinpkt
= 0;
98 /* Add a character to current packet; flush to disk if necessary */
99 #define CHAR_OUT(dinfo,c) \
100 { (dinfo)->packetbuf[++(dinfo)->bytesinpkt] = (char) (c); \
101 if ((dinfo)->bytesinpkt >= 255) \
102 flush_packet(dinfo); \
106 /* Routine to convert variable-width codes into a byte stream */
109 output (gif_dest_ptr dinfo
, int code
)
110 /* Emit a code of n_bits bits */
111 /* Uses cur_accum and cur_bits to reblock into 8-bit bytes */
113 dinfo
->cur_accum
|= ((INT32
) code
) << dinfo
->cur_bits
;
114 dinfo
->cur_bits
+= dinfo
->n_bits
;
116 while (dinfo
->cur_bits
>= 8) {
117 CHAR_OUT(dinfo
, dinfo
->cur_accum
& 0xFF);
118 dinfo
->cur_accum
>>= 8;
119 dinfo
->cur_bits
-= 8;
124 /* The pseudo-compression algorithm.
126 * In this module we simply output each pixel value as a separate symbol;
127 * thus, no compression occurs. In fact, there is expansion of one bit per
128 * pixel, because we use a symbol width one bit wider than the pixel width.
130 * GIF ordinarily uses variable-width symbols, and the decoder will expect
131 * to ratchet up the symbol width after a fixed number of symbols.
132 * To simplify the logic and keep the expansion penalty down, we emit a
133 * GIF Clear code to reset the decoder just before the width would ratchet up.
134 * Thus, all the symbols in the output file will have the same bit width.
135 * Note that emitting the Clear codes at the right times is a mere matter of
136 * counting output symbols and is in no way dependent on the LZW patent.
138 * With a small basic pixel width (low color count), Clear codes will be
139 * needed very frequently, causing the file to expand even more. So this
140 * simplistic approach wouldn't work too well on bilevel images, for example.
141 * But for output of JPEG conversions the pixel width will usually be 8 bits
142 * (129 to 256 colors), so the overhead added by Clear symbols is only about
143 * one symbol in every 256.
147 compress_init (gif_dest_ptr dinfo
, int i_bits
)
148 /* Initialize pseudo-compressor */
150 /* init all the state variables */
151 dinfo
->n_bits
= i_bits
;
152 dinfo
->maxcode
= MAXCODE(dinfo
->n_bits
);
153 dinfo
->ClearCode
= (1 << (i_bits
- 1));
154 dinfo
->EOFCode
= dinfo
->ClearCode
+ 1;
155 dinfo
->code_counter
= dinfo
->ClearCode
+ 2;
156 /* init output buffering vars */
157 dinfo
->bytesinpkt
= 0;
158 dinfo
->cur_accum
= 0;
160 /* GIF specifies an initial Clear code */
161 output(dinfo
, dinfo
->ClearCode
);
166 compress_pixel (gif_dest_ptr dinfo
, int c
)
167 /* Accept and "compress" one pixel value.
168 * The given value must be less than n_bits wide.
171 /* Output the given pixel value as a symbol. */
173 /* Issue Clear codes often enough to keep the reader from ratcheting up
176 if (dinfo
->code_counter
< dinfo
->maxcode
) {
177 dinfo
->code_counter
++;
179 output(dinfo
, dinfo
->ClearCode
);
180 dinfo
->code_counter
= dinfo
->ClearCode
+ 2; /* reset the counter */
186 compress_term (gif_dest_ptr dinfo
)
187 /* Clean up at end */
189 /* Send an EOF code */
190 output(dinfo
, dinfo
->EOFCode
);
191 /* Flush the bit-packing buffer */
192 if (dinfo
->cur_bits
> 0) {
193 CHAR_OUT(dinfo
, dinfo
->cur_accum
& 0xFF);
195 /* Flush the packet buffer */
200 /* GIF header construction */
204 put_word (gif_dest_ptr dinfo
, unsigned int w
)
205 /* Emit a 16-bit word, LSB first */
207 putc(w
& 0xFF, dinfo
->pub
.output_file
);
208 putc((w
>> 8) & 0xFF, dinfo
->pub
.output_file
);
213 put_3bytes (gif_dest_ptr dinfo
, int val
)
214 /* Emit 3 copies of same byte value --- handy subr for colormap construction */
216 putc(val
, dinfo
->pub
.output_file
);
217 putc(val
, dinfo
->pub
.output_file
);
218 putc(val
, dinfo
->pub
.output_file
);
223 emit_header (gif_dest_ptr dinfo
, int num_colors
, JSAMPARRAY colormap
)
224 /* Output the GIF file header, including color map */
225 /* If colormap==NULL, synthesize a gray-scale colormap */
227 int BitsPerPixel
, ColorMapSize
, InitCodeSize
, FlagByte
;
228 int cshift
= dinfo
->cinfo
->data_precision
- 8;
231 if (num_colors
> 256)
232 ERREXIT1(dinfo
->cinfo
, JERR_TOO_MANY_COLORS
, num_colors
);
233 /* Compute bits/pixel and related values */
235 while (num_colors
> (1 << BitsPerPixel
))
237 ColorMapSize
= 1 << BitsPerPixel
;
238 if (BitsPerPixel
<= 1)
241 InitCodeSize
= BitsPerPixel
;
243 * Write the GIF header.
244 * Note that we generate a plain GIF87 header for maximum compatibility.
246 putc('G', dinfo
->pub
.output_file
);
247 putc('I', dinfo
->pub
.output_file
);
248 putc('F', dinfo
->pub
.output_file
);
249 putc('8', dinfo
->pub
.output_file
);
250 putc('7', dinfo
->pub
.output_file
);
251 putc('a', dinfo
->pub
.output_file
);
252 /* Write the Logical Screen Descriptor */
253 put_word(dinfo
, (unsigned int) dinfo
->cinfo
->output_width
);
254 put_word(dinfo
, (unsigned int) dinfo
->cinfo
->output_height
);
255 FlagByte
= 0x80; /* Yes, there is a global color table */
256 FlagByte
|= (BitsPerPixel
-1) << 4; /* color resolution */
257 FlagByte
|= (BitsPerPixel
-1); /* size of global color table */
258 putc(FlagByte
, dinfo
->pub
.output_file
);
259 putc(0, dinfo
->pub
.output_file
); /* Background color index */
260 putc(0, dinfo
->pub
.output_file
); /* Reserved (aspect ratio in GIF89) */
261 /* Write the Global Color Map */
262 /* If the color map is more than 8 bits precision, */
263 /* we reduce it to 8 bits by shifting */
264 for (i
=0; i
< ColorMapSize
; i
++) {
265 if (i
< num_colors
) {
266 if (colormap
!= NULL
) {
267 if (dinfo
->cinfo
->out_color_space
== JCS_RGB
) {
268 /* Normal case: RGB color map */
269 putc(GETJSAMPLE(colormap
[0][i
]) >> cshift
, dinfo
->pub
.output_file
);
270 putc(GETJSAMPLE(colormap
[1][i
]) >> cshift
, dinfo
->pub
.output_file
);
271 putc(GETJSAMPLE(colormap
[2][i
]) >> cshift
, dinfo
->pub
.output_file
);
273 /* Grayscale "color map": possible if quantizing grayscale image */
274 put_3bytes(dinfo
, GETJSAMPLE(colormap
[0][i
]) >> cshift
);
277 /* Create a gray-scale map of num_colors values, range 0..255 */
278 put_3bytes(dinfo
, (i
* 255 + (num_colors
-1)/2) / (num_colors
-1));
281 /* fill out the map to a power of 2 */
282 put_3bytes(dinfo
, 0);
285 /* Write image separator and Image Descriptor */
286 putc(',', dinfo
->pub
.output_file
); /* separator */
287 put_word(dinfo
, 0); /* left/top offset */
289 put_word(dinfo
, (unsigned int) dinfo
->cinfo
->output_width
); /* image size */
290 put_word(dinfo
, (unsigned int) dinfo
->cinfo
->output_height
);
291 /* flag byte: not interlaced, no local color map */
292 putc(0x00, dinfo
->pub
.output_file
);
293 /* Write Initial Code Size byte */
294 putc(InitCodeSize
, dinfo
->pub
.output_file
);
296 /* Initialize for "compression" of image data */
297 compress_init(dinfo
, InitCodeSize
+1);
302 * Startup: write the file header.
306 start_output_gif (j_decompress_ptr cinfo
, djpeg_dest_ptr dinfo
)
308 gif_dest_ptr dest
= (gif_dest_ptr
) dinfo
;
310 if (cinfo
->quantize_colors
)
311 emit_header(dest
, cinfo
->actual_number_of_colors
, cinfo
->colormap
);
313 emit_header(dest
, 256, (JSAMPARRAY
) NULL
);
318 * Write some pixel data.
319 * In this module rows_supplied will always be 1.
323 put_pixel_rows (j_decompress_ptr cinfo
, djpeg_dest_ptr dinfo
,
324 JDIMENSION rows_supplied
)
326 gif_dest_ptr dest
= (gif_dest_ptr
) dinfo
;
327 register JSAMPROW ptr
;
328 register JDIMENSION col
;
330 ptr
= dest
->pub
.buffer
[0];
331 for (col
= cinfo
->output_width
; col
> 0; col
--) {
332 compress_pixel(dest
, GETJSAMPLE(*ptr
++));
338 * Finish up at the end of the file.
342 finish_output_gif (j_decompress_ptr cinfo
, djpeg_dest_ptr dinfo
)
344 gif_dest_ptr dest
= (gif_dest_ptr
) dinfo
;
346 /* Flush "compression" mechanism */
348 /* Write a zero-length data block to end the series */
349 putc(0, dest
->pub
.output_file
);
350 /* Write the GIF terminator mark */
351 putc(';', dest
->pub
.output_file
);
352 /* Make sure we wrote the output file OK */
353 fflush(dest
->pub
.output_file
);
354 if (ferror(dest
->pub
.output_file
))
355 ERREXIT(cinfo
, JERR_FILE_WRITE
);
360 * The module selection routine for GIF format output.
363 JGLOBAL(djpeg_dest_ptr
)
364 jinit_write_gif (j_decompress_ptr cinfo
)
368 /* Create module interface object, fill in method pointers */
369 dest
= (gif_dest_ptr
)
370 (*cinfo
->mem
->alloc_small
) ((j_common_ptr
) cinfo
, JPOOL_IMAGE
,
371 SIZEOF(gif_dest_struct
));
372 dest
->cinfo
= cinfo
; /* make back link for subroutines */
373 dest
->pub
.start_output
= start_output_gif
;
374 dest
->pub
.put_pixel_rows
= put_pixel_rows
;
375 dest
->pub
.finish_output
= finish_output_gif
;
377 if (cinfo
->out_color_space
!= JCS_GRAYSCALE
&&
378 cinfo
->out_color_space
!= JCS_RGB
)
379 ERREXIT(cinfo
, JERR_GIF_COLORSPACE
);
381 /* Force quantization if color or if > 8 bits input */
382 if (cinfo
->out_color_space
!= JCS_GRAYSCALE
|| cinfo
->data_precision
> 8) {
383 /* Force quantization to at most 256 colors */
384 cinfo
->quantize_colors
= TRUE
;
385 if (cinfo
->desired_number_of_colors
> 256)
386 cinfo
->desired_number_of_colors
= 256;
389 /* Calculate output image dimensions so we can allocate space */
390 jpeg_calc_output_dimensions(cinfo
);
392 if (cinfo
->output_components
!= 1) /* safety check: just one component? */
393 ERREXIT(cinfo
, JERR_GIF_BUG
);
395 /* Create decompressor output buffer. */
396 dest
->pub
.buffer
= (*cinfo
->mem
->alloc_sarray
)
397 ((j_common_ptr
) cinfo
, JPOOL_IMAGE
, cinfo
->output_width
, (JDIMENSION
) 1);
398 dest
->pub
.buffer_height
= 1;
400 return (djpeg_dest_ptr
) dest
;
403 #endif /* GIF_SUPPORTED */