1 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2  * Copyright by The HDF Group.                                               *
3  * Copyright by the Board of Trustees of the University of Illinois.         *
4  * All rights reserved.                                                      *
5  *                                                                           *
6  * This file is part of HDF5.  The full HDF5 copyright notice, including     *
7  * terms governing use, modification, and redistribution, is contained in    *
8  * the COPYING file, which can be found at the root of the source code       *
9  * distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases.  *
10  * If you do not have access to either file, you may request a copy from     *
11  * help@hdfgroup.org.                                                        *
12  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
13 
14 /*
15  * hdfgifwr.c  - handles writing of GIF files.
16  *
17  * Contains:
18  *   hdfWriteGIF(fp, pic, ptype, w, h, rmap, gmap, bmap, numcols, colorstyle,
19  *               comment)
20  *
21  * Note: slightly brain-damaged, in that it'll only write non-interlaced
22  *       GIF files (in the interests of speed, or something)
23  */
24 
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.
32  *
33  *
34  * Authors:  Michael Mauldin (mlm@cs.cmu.edu)
35  *           David Rowley (mgardi@watdcsu.waterloo.edu)
36  *
37  * Based on: compress.c - File compression ala IEEE Computer, June 1984.
38  *
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  *****************************************************************/
46 
47 
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 
52 #include "gif.h"
53 
54 typedef BYTE  byte;
55 typedef long int count_int;
56 
57 #ifdef __STDC__
58 static void compress(int, FILE *, byte *, int);
59 static void output(int);
60 static void cl_block(void);
61 static void cl_hash(count_int);
62 static void char_init(void);
63 static void char_out(int);
64 static void flush_char(void);
65 #else
66 static void compress(), output(), cl_block(), cl_hash();
67 static void char_init(), char_out(), flush_char();
68 #endif  /* __STDC__ */
69 
70 static byte pc2nc[256];
71 
72 /*************************************************************/
hdfWriteGIF(FILE * fp,byte * pic,int ptype,int w,int h,byte * rmap,byte * gmap,byte * bmap,byte * pc2ncmap,int numcols,int colorstyle,int BitsPerPixel)73 int hdfWriteGIF(FILE *fp, byte *pic, int ptype, int w, int h, byte *rmap,
74                 byte *gmap, byte *bmap, byte *pc2ncmap, int numcols,
75                 int colorstyle, int BitsPerPixel)
76 {
77     int InitCodeSize;
78     int i;
79     byte *pic8 = pic;
80 
81     /* Shut compiler up... */
82     ptype=ptype;
83     rmap=rmap;
84     gmap=gmap;
85     bmap=bmap;
86     numcols=numcols;
87     colorstyle=colorstyle;
88 
89     for (i = 0; i < 256; i++) {
90       pc2nc[i] = pc2ncmap[i];
91     }
92 
93     if (BitsPerPixel <= 1)
94         InitCodeSize = 2;
95     else
96         InitCodeSize = BitsPerPixel;
97 
98     if (!fp) {
99         fprintf(stderr,  "WriteGIF: file not open for writing\n" );
100         return (1);
101     }
102 
103     compress(InitCodeSize+1, fp, pic8, w*h);
104 
105     if (ferror(fp))
106         return -1;
107 
108     return  0 ;
109 }
110 
111 /***********************************************************************/
112 static unsigned long cur_accum = 0;
113 static int           cur_bits = 0;
114 
115 #define MAXCODE(n_bits)     ( (1 << (n_bits)) - 1)
116 #define XV_BITS 12    /* BITS was already defined on some systems */
117 #define HSIZE  5003            /* 80% occupancy */
118 
119 typedef unsigned char   char_type;
120 
121 static int n_bits;                    /* number of bits/code */
122 static int maxbits = XV_BITS;         /* user settable max # bits/code */
123 static int maxcode;                   /* maximum code, given n_bits */
124 static int maxmaxcode = 1 << XV_BITS; /* NEVER generate this */
125 
126 static  count_int      htab [HSIZE];
127 static  unsigned short codetab [HSIZE];
128 
129 #define HashTabOf(i)   htab[i]
130 #define CodeTabOf(i)   codetab[i]
131 
132 static int hsize = HSIZE;            /* for dynamic table sizing */
133 
134 /*
135  * To save much memory, we overlay the table used by compress() with those
136  * used by decompress().  The tab_prefix table is the same size and type as
137  * the codetab.  The tab_suffix table needs 2**BITS characters.  We get this
138  * from the beginning of htab.  The output stack uses the rest of htab, and
139  * contains characters.  There is plenty of room for any possible stack (stack
140  * used to be 8000 characters).
141  */
142 
143 static int free_ent = 0;                  /* first unused entry */
144 
145 /*
146  * block compression parameters -- after all codes are used up,
147  * and compression rate changes, start over.
148  */
149 static int clear_flg = 0;
150 
151 static long int in_count = 1;            /* length of input */
152 static long int out_count = 0;           /* # of codes output (for debugging) */
153 
154 /*
155  * compress stdin to stdout
156  *
157  * Algorithm:  use open addressing double hashing (no chaining) on the prefix
158  * code / next character combination.  We do a variant of Knuth's algorithm D
159  * (vol. 3, sec. 6.4) along with G. Knott's relatively-prime secondary probe.
160  * Here, the modular division first probe is gives way to a faster
161  * exclusive-or manipulation.  Also do block compression with an adaptive
162  * reset, whereby the code table is cleared when the compression ratio
163  * decreases, but after the table fills.  The variable-length output codes are
164  * re-sized at this point, and a special CLEAR code is generated for the
165  * decompressor.  Late addition:  construct the table according to file size
166  * for noticeable speed improvement on small files.  Please direct questions
167  * about this implementation to ames!jaw.
168  */
169 
170 static int g_init_bits;
171 static FILE *g_outfile;
172 
173 static int ClearCode;
174 static int EOFCode;
175 
176 /********************************************************/
compress(int init_bits,FILE * outfile,byte * data,int len)177 static void compress(int init_bits, FILE *outfile, byte *data, int len)
178 {
179     register long fcode;
180     register int i = 0;
181     register int c;
182     register int ent;
183     register int disp;
184     register int hsize_reg;
185     register int hshift;
186 
187     /*
188      * Set up the globals:  g_init_bits - initial number of bits g_outfile -
189      * pointer to output file
190      */
191     g_init_bits = init_bits;
192     g_outfile   = outfile;
193 
194     /* initialize 'compress' globals */
195     maxbits = XV_BITS;
196     maxmaxcode = 1<<XV_BITS;
197     memset(htab, 0, sizeof(htab));
198     memset(codetab, 0, sizeof(codetab));
199     hsize = HSIZE;
200     free_ent = 0;
201     clear_flg = 0;
202     in_count = 1;
203     out_count = 0;
204     cur_accum = 0;
205     cur_bits = 0;
206 
207     /* Set up the necessary values */
208     out_count = 0;
209     clear_flg = 0;
210     in_count = 1;
211     maxcode = MAXCODE(n_bits = g_init_bits);
212 
213     ClearCode = (1 << (init_bits - 1));
214     EOFCode = ClearCode + 1;
215     free_ent = ClearCode + 2;
216 
217     char_init();
218     ent = pc2nc[*data++];
219     len--;
220 
221     hshift = 0;
222     for (fcode = (long)hsize; fcode < 65536L; fcode *= 2L )
223         hshift++;
224 
225     hshift = 8 - hshift; /* set hash code range bound */
226 
227     hsize_reg = hsize;
228     cl_hash( (count_int) hsize_reg); /* clear hash table */
229 
230     output(ClearCode);
231 
232     while (len) {
233         c = pc2nc[*data++];
234         len--;
235         in_count++;
236 
237         fcode = (long)(((long) c << maxbits) + ent);
238         i = (((int) c << hshift) ^ ent);    /* xor hashing */
239 
240         if ( HashTabOf (i) == fcode ) {
241             ent = CodeTabOf (i);
242             continue;
243         } else if ( (long)HashTabOf (i) < 0) {
244             /* empty slot */
245             goto nomatch;
246         }
247 
248         disp = hsize_reg - i;   /* secondary hash (after G. Knott) */
249 
250         if ( i == 0 )
251             disp = 1;
252 
253 probe:
254         if ((i -= disp) < 0)
255             i += hsize_reg;
256 
257         if (HashTabOf (i) == fcode) {
258             ent = CodeTabOf (i);
259             continue;
260         }
261 
262         if ((long)HashTabOf (i) >= 0)
263             goto probe;
264 
265 nomatch:
266         output(ent);
267         out_count++;
268         ent = c;
269 
270         if (free_ent < maxmaxcode) {
271 	    CodeTabOf (i) = (unsigned short)free_ent++; /* code -> hashtable */
272             HashTabOf (i) = fcode;
273         } else {
274             cl_block();
275         }
276     }
277 
278     /* Put out the final code */
279     output(ent);
280     out_count++;
281     output(EOFCode);
282 }
283 
284 
285 /*****************************************************************
286  * TAG( output )
287  *
288  * Output the given code.
289  * Inputs:
290  *      code:   A n_bits-bit integer.  If == -1, then EOF.  This assumes
291  *              that n_bits =< (long)wordsize - 1.
292  * Outputs:
293  *      Outputs code to the file.
294  * Assumptions:
295  *      Chars are 8 bits long.
296  * Algorithm:
297  *      Maintain a BITS character long buffer (so that 8 codes will
298  * fit in it exactly).  Use the VAX insv instruction to insert each
299  * code in turn.  When the buffer fills up empty it and start over.
300  */
301 
302 static
303 unsigned long masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F,
304                                   0x001F, 0x003F, 0x007F, 0x00FF,
305                                   0x01FF, 0x03FF, 0x07FF, 0x0FFF,
306                                   0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
307 
308 static void
output(int code)309 output(int code)
310 {
311     cur_accum &= masks[cur_bits];
312 
313     if (cur_bits > 0)
314         cur_accum |= (unsigned long)((long)code << cur_bits);
315     else
316         cur_accum = (unsigned long)code;
317 
318     cur_bits += n_bits;
319 
320     while( cur_bits >= 8 ) {
321         char_out( (int)((unsigned int) cur_accum & 0xff) );
322         cur_accum >>= 8;
323         cur_bits -= 8;
324     }
325 
326     /*
327      * If the next entry is going to be too big for the code size, then
328      * increase it, if possible.
329      */
330     if (free_ent > maxcode || clear_flg) {
331         if (clear_flg) {
332             maxcode = MAXCODE (n_bits = g_init_bits);
333             clear_flg = 0;
334         } else {
335             n_bits++;
336 
337             if ( n_bits == maxbits )
338                 maxcode = maxmaxcode;
339             else
340                 maxcode = MAXCODE(n_bits);
341         }
342     }
343 
344     if (code == EOFCode) {
345         /* At EOF, write the rest of the buffer */
346         while( cur_bits > 0 ) {
347             char_out( (int)((unsigned int)cur_accum & 0xff) );
348             cur_accum >>= 8;
349             cur_bits -= 8;
350         }
351 
352         flush_char();
353         fflush( g_outfile );
354 
355 #ifdef FOO
356         if(ferror( g_outfile))
357             FatalError("unable to write GIF file");
358 #endif
359     }
360 }
361 
362 /********************************/
363 static void
cl_block(void)364 cl_block(void)                  /* table clear for block compress */
365 {
366     /* Clear out the hash table */
367     cl_hash((count_int) hsize);
368     free_ent = ClearCode + 2;
369     clear_flg = 1;
370     output(ClearCode);
371 }
372 
373 /********************************/
374 static void
cl_hash(count_int hashsize)375 cl_hash(count_int hashsize)     /* reset code table */
376 {
377     count_int *htab_p = htab+hashsize;
378     long i, m1 = -1;
379 
380     i = hashsize - 16;
381 
382     do {    /* might use Sys V memset(3) here */
383         *(htab_p-16) = m1;
384         *(htab_p-15) = m1;
385         *(htab_p-14) = m1;
386         *(htab_p-13) = m1;
387         *(htab_p-12) = m1;
388         *(htab_p-11) = m1;
389         *(htab_p-10) = m1;
390         *(htab_p-9) = m1;
391         *(htab_p-8) = m1;
392         *(htab_p-7) = m1;
393         *(htab_p-6) = m1;
394         *(htab_p-5) = m1;
395         *(htab_p-4) = m1;
396         *(htab_p-3) = m1;
397         *(htab_p-2) = m1;
398         *(htab_p-1) = m1;
399         htab_p -= 16;
400     } while ((i -= 16) >= 0);
401 
402     for ( i += 16; i > 0; i-- )
403         *--htab_p = m1;
404 }
405 
406 /******************************************************************************
407  *
408  * GIF Specific routines
409  *
410  ******************************************************************************/
411 
412 /*
413  * Number of characters so far in this 'packet'
414  */
415 static int a_count;
416 
417 /*
418  * Set up the 'byte output' routine
419  */
420 static void
char_init(void)421 char_init(void)
422 {
423     a_count = 0;
424 }
425 
426 /*
427  * Define the storage for the packet accumulator
428  */
429 static char accum[ 256 ];
430 
431 /*
432  * Add a character to the end of the current packet, and if it is 254
433  * characters, flush the packet to disk.
434  */
435 static void
char_out(int c)436 char_out(int c)
437 {
438     accum[ a_count++ ] = (char)c;
439 
440     if (a_count >= 254)
441         flush_char();
442 }
443 
444 /*
445  * Flush the packet to disk, and reset the accumulator
446  */
447 static void
flush_char(void)448 flush_char(void)
449 {
450     if (a_count > 0) {
451         fputc( a_count, g_outfile );
452         fwrite( accum, (size_t)1, (size_t)a_count, g_outfile);
453         a_count = 0;
454     }
455 }
456