1
/* -----------------------------------------------------------------------------
4
* GIF encoding with broken compression algorithm to avoid LZW.
6
* Author(s) : David Beazley (beazley@cs.uchicago.edu)
7
* Copyright (C) 1995-1996
9
* See the file LICENSE for information on usage and redistribution.
10
* ----------------------------------------------------------------------------- */
13
* xvgifwr.c - handles writing of GIF files. based on flgife.c and
14
* flgifc.c from the FBM Library, by Michael Maudlin
17
* WriteGIF(fp, pic, ptype, w, h, rmap, gmap, bmap, numcols, colorstyle,
20
* Note: slightly brain-damaged, in that it'll only write non-interlaced
21
* GIF files (in the interests of speed, or something)
25
/*****************************************************************
26
* Portions of this code Copyright (C) 1989 by Michael Mauldin.
27
* Permission is granted to use this file in whole or in
28
* part for any purpose, educational, recreational or commercial,
29
* provided that this copyright notice is retained unchanged.
30
* This software is available to all free of charge by anonymous
31
* FTP and in the UUNET archives.
34
* Authors: Michael Mauldin (mlm@cs.cmu.edu)
35
* David Rowley (mgardi@watdcsu.waterloo.edu)
37
* Based on: compress.c - File compression ala IEEE Computer, June 1984.
39
* Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)
40
* Jim McKie (decvax!mcvax!jim)
41
* Steve Davies (decvax!vax135!petsd!peora!srd)
42
* Ken Turkowski (decvax!decwrl!turtlevax!ken)
43
* James A. Woods (decvax!ihnp4!ames!jaw)
44
* Joe Orost (decvax!vax135!petsd!joe)
45
*****************************************************************/
49
typedef long int count_int;
50
typedef unsigned char byte;
53
static unsigned char *op;
54
static int Width, Height;
55
static int curx, cury;
58
static void putgifword(int);
59
static void compress(int, byte **, int);
60
static void output_GIF(int);
61
static void cl_block(void);
62
static void cl_hash(count_int);
63
static void char_init(void);
64
static void char_out(int);
65
static void flush_char(void);
66
static void *OutBuffer;
67
static int OutBufSize;
68
static FrameBuffer *GIF_frame;
70
static unsigned char pc2nc[256],r1[256],g1[256],b1[256];
72
/*************************************************************/
73
int FrameBuffer_makeGIF(FrameBuffer *f, ColorMap *c, void *outbuffer, unsigned int outbufsize)
77
int ColorMapSize, InitCodeSize, Background, BitsPerPixel;
79
char *rmap, *gmap, *bmap;
85
OutBuffer = outbuffer;
86
OutBufSize = outbufsize;
88
cmap = (char *) c->cmap;
90
op = (unsigned char *) outbuffer;
92
for (i=0; i<256; i++) { pc2nc[i] = r1[i] = g1[i] = b1[i] = 0; }
94
/* compute number of unique colors */
100
for (i=0; i<256; i++) {
101
/* see if color #i is already used */
102
for (j=0; j<i; j++) {
103
if (rmap[i] == rmap[j] && gmap[i] == gmap[j] &&
104
bmap[i] == bmap[j]) break;
107
if (j==i) { /* wasn't found */
114
else pc2nc[i] = pc2nc[j];
117
/* figure out 'BitsPerPixel' */
119
if ( (1<<i) >= nc) break;
123
ColorMapSize = 1 << BitsPerPixel;
125
RWidth = Width = f->width;
126
RHeight = Height = f->height;
127
LeftOfs = TopOfs = 0;
129
if (BitsPerPixel <= 1) InitCodeSize = 2;
130
else InitCodeSize = BitsPerPixel;
133
cury = f->height - 1;
135
strcpy((char *) op,"GIF89a"); /* Put in GIF magic number */
137
putgifword(RWidth); /* screen descriptor */
140
i = 0x80; /* Yes, there is a color map */
141
i |= (8-1)<<4; /* OR in the color resolution (hardwired 8) */
142
i |= (BitsPerPixel - 1); /* OR in the # of bits per pixel */
144
*(op++) = Background; /* background color */
146
for (i=0; i<ColorMapSize; i++) { /* write out Global colormap */
152
*(op++) = ','; /* image separator */
154
/* Write the Image header */
160
*(op++) = InitCodeSize;
162
compress(InitCodeSize+1, f->pixels, f->width*f->height);
167
count = (op - (unsigned char *) OutBuffer);
168
if (gif_error) return -1;
172
/******************************/
173
static void putgifword(w)
176
/* writes a 16-bit integer in GIF order (LSB first) */
178
*(op++) = (w>>8)&0xff;
181
/***********************************************************************/
184
static unsigned long cur_accum = 0;
185
static int cur_bits = 0;
190
#define GP_BITS 12 /* BITS was already defined on some systems */
192
#define HSIZE 5003 /* 80% occupancy */
194
typedef unsigned char char_type;
196
static int n_bits; /* number of bits/code */
197
static int maxbits = GP_BITS; /* user settable max # bits/code */
198
static int maxcode; /* maximum code, given n_bits */
199
static int maxmaxcode = 1 << GP_BITS; /* NEVER generate this */
201
#define MAXCODE(n_bits) ( (1 << (n_bits)) - 1)
203
static count_int *htab;
204
static unsigned short *codetab;
205
static GIFOutBufSize;
207
/* static count_int htab [HSIZE];
208
static unsigned short codetab [HSIZE]; */
210
#define HashTabOf(i) htab[i]
211
#define CodeTabOf(i) codetab[i]
213
static int hsize = HSIZE; /* for dynamic table sizing */
216
* To save much memory, we overlay the table used by compress() with those
217
* used by decompress(). The tab_prefix table is the same size and type
218
* as the codetab. The tab_suffix table needs 2**BITS characters. We
219
* get this from the beginning of htab. The output stack uses the rest
220
* of htab, and contains characters. There is plenty of room for any
221
* possible stack (stack used to be 8000 characters).
224
#define tab_prefixof(i) CodeTabOf(i)
225
#define tab_suffixof(i) ((char_type *)(htab))[i]
226
#define de_stack ((char_type *)&tab_suffixof(1<<GP_BITS))
228
static int free_ent = 0; /* first unused entry */
231
* block compression parameters -- after all codes are used up,
232
* and compression rate changes, start over.
234
static int clear_flg = 0;
236
static long int out_count = 0; /* # of codes output (for debugging) */
239
* compress stdin to stdout
241
* Algorithm: use open addressing double hashing (no chaining) on the
242
* prefix code / next character combination. We do a variant of Knuth's
243
* algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
244
* secondary probe. Here, the modular division first probe is gives way
245
* to a faster exclusive-or manipulation. Also do block compression with
246
* an adaptive reset, whereby the code table is cleared when the compression
247
* ratio decreases, but after the table fills. The variable-length output
248
* codes are re-sized at this point, and a special CLEAR code is generated
249
* for the decompressor. Late addition: construct the table according to
250
* file size for noticeable speed improvement on small files. Please direct
251
* questions about this implementation to ames!jaw.
254
static int g_init_bits;
256
static int ClearCode;
260
/********************************************************/
261
static void compress(init_bits, data, len)
263
unsigned char **data;
271
register int hsize_reg;
275
/* Use the output buffer as temporary storage for GIF data */
277
if (OutBufSize < HSIZE*(sizeof(count_int) + sizeof(unsigned short))) {
282
/* Put htab and codetab arrays into the output buffer */
284
GIFOutBufSize = OutBufSize - HSIZE*(sizeof(count_int) + sizeof(unsigned short)) - 16;
285
GIFOutBufSize = GIFOutBufSize & (~0x3); /* Make sure it's double word alligned */
287
htab = (count_int *) ((char *) OutBuffer + GIFOutBufSize);
288
codetab = (unsigned short *) ((char *) OutBuffer + GIFOutBufSize + HSIZE*sizeof(count_int));
291
* Set up the globals: g_init_bits - initial number of bits
292
* g_outfile - pointer to output file
294
g_init_bits = init_bits;
297
/* initialize 'compress' globals */
299
maxmaxcode = 1<<GP_BITS;
300
memset(htab,0,sizeof(htab));
301
memset(codetab,0,sizeof(codetab));
310
* Set up the necessary values
314
maxcode = MAXCODE(n_bits = g_init_bits);
316
ClearCode = (1 << (init_bits - 1));
317
EOFCode = ClearCode + 1;
318
free_ent = ClearCode + 2;
321
ent = pc2nc[data[cury][curx]];
323
if (curx >= GIF_frame->width) {
330
for ( fcode = (long) hsize; fcode < 65536L; fcode *= 2L )
332
hshift = 8 - hshift; /* set hash code range bound */
335
cl_hash( (count_int) hsize_reg); /* clear hash table */
337
output_GIF(ClearCode);
339
c = pc2nc[data[cury][curx]];
341
if (curx >= GIF_frame->width) {
347
/* Uncompressed GIF */
350
if (code_count >= ClearCode-2) {
351
output_GIF(ClearCode);
357
/* Put out the final code */
363
/*****************************************************************
366
* Output the given code.
368
* code: A n_bits-bit integer. If == -1, then EOF. This assumes
369
* that n_bits =< (long)wordsize - 1.
371
* Outputs code to the file.
373
* Chars are 8 bits long.
375
* Maintain a BITS character long buffer (so that 8 codes will
376
* fit in it exactly). Use the VAX insv instruction to insert each
377
* code in turn. When the buffer fills up empty it and start over.
381
unsigned long masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F,
382
0x001F, 0x003F, 0x007F, 0x00FF,
383
0x01FF, 0x03FF, 0x07FF, 0x0FFF,
384
0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
386
static void output_GIF(code)
389
cur_accum &= masks[cur_bits];
392
cur_accum |= ((long)code << cur_bits);
398
while( cur_bits >= 8 ) {
399
char_out( (int) (cur_accum & 0xff) );
405
* If the next entry is going to be too big for the code size,
406
* then increase it, if possible.
409
if (free_ent > maxcode || clear_flg) {
412
maxcode = MAXCODE (n_bits = g_init_bits);
417
if ( n_bits == maxbits )
418
maxcode = maxmaxcode;
420
maxcode = MAXCODE(n_bits);
424
if( code == EOFCode ) {
425
/* At EOF, write the rest of the buffer */
426
while( cur_bits > 0 ) {
427
char_out( (int)(cur_accum & 0xff) );
437
/********************************/
438
static void cl_block () /* table clear for block compress */
440
/* Clear out the hash table */
442
cl_hash ( (count_int) hsize );
443
free_ent = ClearCode + 2;
446
output_GIF(ClearCode);
450
/********************************/
451
static void cl_hash(hsize) /* reset code table */
452
register count_int hsize;
454
register count_int *htab_p = htab+hsize;
456
register long m1 = -1;
459
do { /* might use Sys V memset(3) here */
477
} while ((i -= 16) >= 0);
479
for ( i += 16; i > 0; i-- )
484
/******************************************************************************
486
* GIF Specific routines
488
******************************************************************************/
491
* Number of characters so far in this 'packet'
496
* Set up the 'byte output' routine
498
static void char_init()
504
* Define the storage for the packet accumulator
506
static char accum[ 256 ];
509
* Add a character to the end of the current packet, and if it is 254
510
* characters, flush the packet to disk.
512
static void char_out(c)
515
accum[ a_count++ ] = c;
521
* Flush the packet to disk, and reset the accumulator
523
static void flush_char()
525
if (gif_error) return;
528
memcpy(op,accum,a_count);
532
if (op > (unsigned char *) ((char *) OutBuffer + (GIFOutBufSize - 2048))) {
539
/* ----------------------------------------------------------------------
540
int FrameBuffer_writeGIF(char *filename)
542
Write a GIF file to filename
543
----------------------------------------------------------------------- */
545
int FrameBuffer_writeGIF(FrameBuffer *f, ColorMap *c, char *filename) {
552
file = fopen(filename,"wb");
553
if (file == NULL) return -1;
555
bufsize = (f->width*f->height*3)/2;
556
buffer = (void *) malloc(bufsize);
557
nbytes = FrameBuffer_makeGIF(f,c,buffer,bufsize);
563
fwrite(buffer,nbytes,1,file);