2
* Copyright (C) 1991, 1992, Thomas G. Lane.
3
* This file is part of the Independent JPEG Group's software.
4
* For conditions of distribution and use, see the accompanying README file.
6
* This file contains routines to read input images in GIF format.
8
* These routines may need modification for non-Unix environments or
9
* specialized applications. As they stand, they assume input from
10
* an ordinary stdio stream. They further assume that reading begins
11
* at the start of the file; input_init may need work if the
12
* user interface has already read some data (e.g., to determine that
13
* the file is indeed GIF format).
15
* These routines are invoked via the methods get_input_row
16
* and input_init/term.
20
* This code is loosely based on giftoppm from the PBMPLUS distribution
21
* of Feb. 1991. That file contains the following copyright notice:
22
* +-------------------------------------------------------------------+
23
* | Copyright 1990, David Koblas. |
24
* | Permission to use, copy, modify, and distribute this software |
25
* | and its documentation for any purpose and without fee is hereby |
26
* | granted, provided that the above copyright notice appear in all |
27
* | copies and that both that copyright notice and this permission |
28
* | notice appear in supporting documentation. This software is |
29
* | provided "as is" without express or implied warranty. |
30
* +-------------------------------------------------------------------+
32
* We are also required to state that
33
* "The Graphics Interchange Format(c) is the Copyright property of
34
* CompuServe Incorporated. GIF(sm) is a Service Mark property of
35
* CompuServe Incorporated."
51
static int fehler=FALSE; /* wird bei fatalen fehlern auf TRUE gesetzt */
53
struct compress_info {
63
typedef struct compress_info* compress_info_ptr;
70
#define MAXCOLORMAPSIZE 256 /* max # of colors in a GIF colormap */
71
#define NUMCOLORS 3 /* # of colors */
72
#define CM_RED 0 /* color component numbers */
77
#define MAX_LZW_BITS 12 /* maximum LZW code size */
78
#define LZW_TABLE_SIZE (1<<MAX_LZW_BITS) /* # of possible LZW symbols */
80
/* Macros for extracting header data --- note we assume chars may be signed */
82
#define LM_to_uint(a,b) ((((b)&0xFF) << 8) | ((a)&0xFF))
84
#define BitSet(byte, bit) ((byte) & (bit))
85
#define INTERLACE 0x40 /* mask for bit signifying interlaced image */
86
#define COLORMAPFLAG 0x80 /* mask for bit signifying colormap presence */
88
/* Static vars for GetCode and LZWReadByte */
90
static char code_buf[256+4]; /* current input data block */
91
static int last_byte; /* # of bytes in code_buf */
92
static int last_bit; /* # of bits in code_buf */
93
static int cur_bit; /* next bit index to read */
94
static boolean out_of_blocks; /* TRUE if hit terminator data block */
96
static int input_code_size; /* codesize given in GIF file */
97
static int clear_code,end_code; /* values for Clear and End codes */
99
static int code_size; /* current actual code size */
100
static int limit_code; /* 2^code_size */
101
static int max_code; /* first unused code value */
102
static boolean first_time; /* flags first call to LZWReadByte */
104
/* LZW decompression tables:
105
* symbol_head[K] = prefix symbol of any LZW symbol K (0..LZW_TABLE_SIZE-1)
106
* symbol_tail[K] = suffix byte of any LZW symbol K (0..LZW_TABLE_SIZE-1)
107
* Note that entries 0..end_code of the above tables are not used,
108
* since those symbols represent raw bytes or special codes.
110
* The stack represents the not-yet-used expansion of the last LZW symbol.
111
* In the worst case, a symbol could expand to as many bytes as there are
112
* LZW symbols, so we allocate LZW_TABLE_SIZE bytes for the stack.
113
* (This is conservative since that number includes the raw-byte symbols.)
115
* The tables are allocated from FAR heap space since they would use up
116
* rather a lot of the near data space in a PC.
119
static unsigned short *symbol_head; /* => table of prefix symbols */
120
static unsigned char *symbol_tail; /* => table of suffix bytes */
121
static unsigned char *symbol_stack; /* stack for symbol expansions */
122
static unsigned char *sp; /* stack pointer */
124
/* Static state for interlaced image processing */
126
static boolean is_interlaced; /* TRUE if have interlaced image */
129
ReadByte (compress_info_ptr cinfo)
130
/* Read next byte from GIF file */
132
register FILE * infile = cinfo->input_file;
135
if ((c = getc(infile)) == EOF)
136
perror("Premature EOF in GIF file");
142
GetDataBlock (compress_info_ptr cinfo, char *buf)
143
/* Read a GIF data block, which has a leading count byte */
144
/* A zero-length block marks the end of a data block sequence */
148
count = ReadByte(cinfo);
150
if (! fread(buf, count,1,cinfo->input_file)) {
151
perror("Premature EOF in GIF file");
160
SkipDataBlocks (compress_info_ptr cinfo)
161
/* Skip a series of data blocks, until a block terminator is found */
165
while (GetDataBlock(cinfo, buf) > 0)
172
/* (Re)initialize LZW state; shared code for startup and Clear processing */
174
code_size = input_code_size+1;
175
limit_code = clear_code << 1; /* 2^code_size */
176
max_code = clear_code + 2; /* first unused code value */
177
sp = symbol_stack; /* init stack to empty */
183
/* Initialize for a series of LZWReadByte (and hence GetCode) calls */
185
/* GetCode initialization */
186
last_byte = 2; /* make safe to "recopy last two bytes" */
187
last_bit = 0; /* nothing in the buffer */
188
cur_bit = 0; /* force buffer load on first call */
189
out_of_blocks = FALSE;
191
/* LZWReadByte initialization */
192
clear_code = 1 << input_code_size; /* compute special code values */
193
end_code = clear_code + 1; /* note that these do not change */
200
GetCode (compress_info_ptr cinfo)
201
/* Fetch the next code_size bits from the GIF data */
202
/* We assume code_size is less than 16 */
205
int offs, ret, count;
207
if ( (cur_bit+code_size) > last_bit) {
208
/* Time to reload the buffer */
210
perror("Ran out of GIF bits");
211
return end_code; /* fake something useful */
213
/* preserve last two bytes of what we have -- assume code_size <= 16 */
214
code_buf[0] = code_buf[last_byte-2];
215
code_buf[1] = code_buf[last_byte-1];
216
/* Load more bytes; set flag if we reach the terminator block */
217
if ((count = GetDataBlock(cinfo, &code_buf[2])) == 0) {
218
out_of_blocks = TRUE;
219
perror("Ran out of GIF bits\n");
220
return end_code; /* fake something useful */
223
cur_bit = (cur_bit - last_bit) + 16;
224
last_byte = 2 + count;
225
last_bit = last_byte * 8;
228
/* Form up next 24 bits in accum */
229
offs = cur_bit >> 3; /* byte containing cur_bit */
230
#ifdef CHAR_IS_UNSIGNED
231
accum = code_buf[offs+2];
233
accum |= code_buf[offs+1];
235
accum |= code_buf[offs];
237
accum = code_buf[offs+2] & 0xFF;
239
accum |= code_buf[offs+1] & 0xFF;
241
accum |= code_buf[offs] & 0xFF;
244
/* Right-align cur_bit in accum, then mask off desired number of bits */
245
accum >>= (cur_bit & 7);
246
ret = ((int) accum) & ((1 << code_size) - 1);
248
cur_bit += code_size;
254
LZWReadByte (compress_info_ptr cinfo)
255
/* Read an LZW-compressed byte */
257
static int oldcode; /* previous LZW symbol */
258
static int firstcode; /* first byte of oldcode's expansion */
259
register int code; /* current working code */
260
int incode; /* saves actual input code */
262
/* First time, just eat the expected Clear code(s) and return next code, */
263
/* which is expected to be a raw byte. */
266
code = clear_code; /* enables sharing code with Clear case */
269
/* If any codes are stacked from a previously read symbol, return them */
270
if (sp > symbol_stack)
271
return (int) *(--sp);
273
/* Time to read a new symbol */
274
code = GetCode(cinfo);
278
if (code == clear_code) {
279
/* Reinit static state, swallow any extra Clear codes, and */
280
/* return next code, which is expected to be a raw byte. */
283
code = GetCode(cinfo);
284
} while (code == clear_code);
285
if (code > clear_code) { /* make sure it is a raw byte */
286
perror("Corrupt data in GIF file");
287
code = 0; /* use something valid */
289
firstcode = oldcode = code; /* make firstcode, oldcode valid! */
293
if (code == end_code) {
294
/* Skip the rest of the image, unless GetCode already read terminator */
295
if (! out_of_blocks) {
296
SkipDataBlocks(cinfo);
297
out_of_blocks = TRUE;
299
/* Complain that there's not enough data */
300
perror("Premature end of GIF image");
301
/* Pad data with 0's */
302
return 0; /* fake something usable */
305
/* Got normal raw byte or LZW symbol */
306
incode = code; /* save for a moment */
308
if (code >= max_code) { /* special case for not-yet-defined symbol */
309
/* code == max_code is OK; anything bigger is bad data */
310
if (code > max_code) {
311
perror("Corrupt data in GIF file");
312
incode = 0; /* prevent creation of loops in symbol table */
314
*sp++ = (unsigned char) firstcode; /* it will be defined as oldcode/firstcode */
318
/* If it's a symbol, expand it into the stack */
319
while (code >= clear_code) {
320
*sp++ = symbol_tail[code]; /* tail of symbol: a simple byte value */
321
code = symbol_head[code]; /* head of symbol: another LZW symbol */
323
/* At this point code just represents a raw byte */
324
firstcode = code; /* save for possible future use */
326
/* If there's room in table, */
327
if ((code = max_code) < LZW_TABLE_SIZE) {
328
/* Define a new symbol = prev sym + head of this sym's expansion */
329
symbol_head[code] = oldcode;
330
symbol_tail[code] = (unsigned char) firstcode;
332
/* Is it time to increase code_size? */
333
if ((max_code >= limit_code) && (code_size < MAX_LZW_BITS)) {
335
limit_code <<= 1; /* keep equal to 2^code_size */
339
oldcode = incode; /* save last input symbol for future use */
340
return firstcode; /* return first byte of symbol's expansion */
345
ReadColorMap (compress_info_ptr cinfo, int cmaplen)
346
/* Read a GIF colormap */
350
for (i = 0; i < cmaplen; i++) {
354
if(cinfo->load_as_block) {
355
// blockpal[i].R = R;
356
// blockpal[i].G = G;
357
// blockpal[i].B = B;
358
// blockpal[i].bestfit = best_color_match(R,G,B);
360
// blockpal[i].bestfit = i;
362
// dr_setRGB8(i,R, G, B);
369
DoExtension (compress_info_ptr cinfo)
370
/* Process an extension block */
371
/* Currently we ignore 'em all */
375
/* Read extension label byte */
376
extlabel = ReadByte(cinfo);
377
perror("Ignoring GIF extension block of type %d\n",extlabel);
378
/* Skip the data block(s) associated with the extension */
379
SkipDataBlocks(cinfo);
384
* Read the file header; return image size and component count.
388
input_init (compress_info_ptr cinfo)
390
char hdrbuf[10]; /* workspace for reading control blocks */
391
unsigned short width, height; /* image dimensions */
392
int colormaplen, aspectRatio;
395
/* Read and verify GIF Header */
396
if (! fread(hdrbuf, 6, 1,cinfo->input_file)) {
397
perror("Undefinable File\n");
400
if (hdrbuf[0] != 'G' || hdrbuf[1] != 'I' || hdrbuf[2] != 'F') {
401
perror("Not a GIF file\n");
404
/* Check for expected version numbers.
405
* If unknown version, give warning and try to process anyway;
406
* this is per recommendation in GIF89a standard.
408
if ((hdrbuf[3] != '8' || hdrbuf[4] != '7' || hdrbuf[5] != 'a') &&
409
(hdrbuf[3] != '8' || hdrbuf[4] != '9' || hdrbuf[5] != 'a'))
410
perror("Warning: unexpected GIF version number '%c%c%c'\n",
411
hdrbuf[3], hdrbuf[4], hdrbuf[5]);
413
/* Read and decipher Logical Screen Descriptor */
414
if (! fread(hdrbuf, 7, 1, cinfo->input_file))
415
perror("Premature EOF in GIF file\n");
416
width = LM_to_uint(hdrbuf[0],hdrbuf[1]);
417
height = LM_to_uint(hdrbuf[2],hdrbuf[3]);
418
colormaplen = 2 << (hdrbuf[4] & 0x07);
419
/* we ignore the color resolution, sort flag, and background color index */
420
aspectRatio = hdrbuf[6] & 0xFF;
421
if (aspectRatio != 0 && aspectRatio != 49)
422
perror("Warning: nonsquare pixels in input\n");
425
/* Read global colormap if header indicates it is present */
426
if (BitSet(hdrbuf[4], COLORMAPFLAG))
427
ReadColorMap(cinfo, colormaplen); /* sets colormap also */
429
/* Scan until we reach start of desired image.
430
* We don't currently support skipping images, but could add it easily.
435
if (c == ';') { /* GIF terminator?? */
436
perror("Too few images in GIF file\n");
440
if (c == '!') { /* Extension */
445
if (c != ',') { /* Not an image separator? */
446
perror("Bogus input char 0x%02x, ignoring\n", c);
450
/* Read and decipher Local Image Descriptor */
451
if (! fread(hdrbuf, 9, 1, cinfo->input_file)) {
452
perror("Premature EOF in GIF file\n");
455
/* we ignore top/left position info, also sort flag */
456
width = LM_to_uint(hdrbuf[4],hdrbuf[5]);
457
height = LM_to_uint(hdrbuf[6],hdrbuf[7]);
458
is_interlaced = BitSet(hdrbuf[8], INTERLACE);
460
/* Read local colormap if header indicates it is present */
461
/* Note: if we wanted to support skipping images, */
462
/* we'd need to skip rather than read colormap for ignored images */
463
if (BitSet(hdrbuf[8], COLORMAPFLAG)) {
464
colormaplen = 2 << (hdrbuf[8] & 0x07);
465
ReadColorMap(cinfo, colormaplen);
468
input_code_size = ReadByte(cinfo); /* get minimum-code-size byte */
469
if (input_code_size < 2 || input_code_size >= MAX_LZW_BITS) {
470
perror("Bogus codesize %d\n", input_code_size);
473
/* Reached desired image, so break out of loop */
474
/* If we wanted to skip this image, */
475
/* we'd call SkipDataBlocks and then continue the loop */
479
/* Prepare to read selected image: first initialize LZW decompressor */
480
symbol_head = (unsigned short *) (malloc(LZW_TABLE_SIZE * SIZEOF(unsigned short)));
481
symbol_tail = (unsigned char *) (malloc(LZW_TABLE_SIZE * SIZEOF(unsigned char)));
482
symbol_stack = (unsigned char *) (malloc(LZW_TABLE_SIZE * SIZEOF(unsigned char)));
486
* If image is interlaced, we read it into a full-size sample array,
487
* decompressing as we go; then get_input_row selects rows from the
488
* sample array in the proper order.
491
/* We request the big array now, but can't access it until the pipeline
492
* controller causes all the big arrays to be allocated. Hence, the
493
* actual work of reading the image is postponed until the first call
497
interlaced_image = (*cinfo->emethods->request_big_sarray)
498
((long) width, (long) height, 1L);
499
cinfo->methods->get_input_row = load_interlaced_image;
500
cinfo->total_passes++; */ /* count file reading as separate pass */
503
/* Return info about the image. */
504
/* cinfo->input_components = NUMCOLORS;
505
cinfo->in_color_space = CS_RGB; */
506
cinfo->image_width = width;
507
cinfo->image_height = height;
508
cinfo->data_precision = 8; /* always, even if 12-bit JSAMPLEs */
510
/* TRACEMS3(cinfo->emethods, 1, "%ux%ux%d GIF image",
511
(unsigned int) width, (unsigned int) height, colormaplen);
519
* Read one row of pixels.
520
* This version is used for noninterlaced GIF images:
521
* we read directly from the GIF file.
525
get_input_row(unsigned char *block, compress_info_ptr cinfo, int y)
530
const int w=cinfo->image_width;
531
const int line = y * w;
533
for(x = cinfo->image_width; x > 0; x--) {
534
c = LZWReadByte(cinfo);
536
block[line + w - x] = c;
541
* Finish up at the end of the file.
545
input_term (compress_info_ptr cinfo)
554
read_gif_as_block(unsigned char* block, FILE *file)
556
struct compress_info cinfo;
559
cinfo.input_file = file;
560
cinfo.load_as_block = TRUE;
564
int pass,start_y=0,step_y=0;
566
for(pass=0; pass<4; pass++) {
581
for(y=start_y; y<cinfo.image_height; y+=step_y) {
582
get_input_row(block, &cinfo, y);
587
for(y=0;y<cinfo.image_height;y++) {
588
get_input_row(block, &cinfo, y);
596
int load_block(unsigned char *block, char *fname)
600
file = fopen(fname,"rb");
602
read_gif_as_block(block, file);
604
printf("Error: Can't open '%s' for reading.\n", fname);