2 * This file was adapted from D J Hagberg's GifDecoder.java
4 * This software is copyrighted by D. J. Hagberg, Jr., and other parties.
5 * The following terms apply to all files associated with the software
6 * unless explicitly disclaimed in individual files.
8 * The authors hereby grant permission to use, copy, modify, distribute,
9 * and license this software and its documentation for any purpose, provided
10 * that existing copyright notices are retained in all copies and that this
11 * notice is included verbatim in any distributions. No written agreement,
12 * license, or royalty fee is required for any of the authorized uses.
13 * Modifications to this software may be copyrighted by their authors
14 * and need not follow the licensing terms described here, provided that
15 * the new terms are clearly indicated on the first page of each file where
18 * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
19 * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
20 * ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
21 * DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
22 * POSSIBILITY OF SUCH DAMAGE.
24 * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
25 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
26 * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
27 * IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
28 * NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
31 * GOVERNMENT USE: If you are acquiring this software on behalf of the
32 * U.S. government, the Government shall have only "Restricted Rights"
33 * in the software and related documentation as defined in the Federal
34 * Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
35 * are acquiring the software on behalf of the Department of Defense, the
36 * software shall be classified as "Commercial Computer Software" and the
37 * Government shall have only "Restricted Rights" as defined in Clause
38 * 252.227-7013 (c) (1) of DFARs. Notwithstanding the foregoing, the
39 * authors grant the U.S. Government and others acting in its behalf
40 * permission to use and distribute the software in accordance with the
41 * terms specified in this license.
44 package org.ibex.graphics;
46 import org.ibex.util.*;
47 import java.io.BufferedInputStream;
48 import java.io.InputStream;
49 import java.io.IOException;
50 import java.io.PrintWriter;
52 /** Converts an InputStream carrying a GIF image into an ARGB int[] */
55 // Public Methods /////////////////////////////////////////////////////////
59 private static Queue instances = new Queue(10);
61 public static void load(InputStream is, Picture p) {
62 GIF g = (GIF)instances.remove(false);
63 if (g == null) g = new GIF();
66 } catch (Exception e) {
67 if (Log.on) Log.info(GIF.class, e);
70 // FIXME: must reset fields
71 // if (instances.size() < 10) instances.append(g);
74 private void _load(InputStream is, Picture p) throws IOException {
76 if (is instanceof BufferedInputStream) _in = (BufferedInputStream)is;
77 else _in = new BufferedInputStream(is);
78 decodeAsBufferedImage(0);
85 /** Decode a particular frame from the GIF file. Frames must be decoded in order, starting with 0. */
86 private void decodeAsBufferedImage(int page) throws IOException, IOException {
88 // If the user requested a page already decoded, we cannot go back.
89 if (page <= index ) return;
91 // If we just started reading this stream, initialize the global info.
93 if (!readIntoBuf(6) || _buf[0] != 'G' || _buf[1] != 'I' || _buf[2] != 'F' ||
94 _buf[3] != '8' || !(_buf[4] == '7' || _buf[4] == '9') || _buf[5] != 'a')
95 throw new IOException("Not a GIF8Xa file.");
96 if (!readGlobalImageDescriptor()) throw new IOException("Unable to read GIF header.");
99 // Loop through the blocks in the image.
100 int block_identifier;
102 if(!readIntoBuf(1)) throw new IOException("Unexpected EOF(1)");
103 block_identifier = _buf[0];
104 if (block_identifier == ';') throw new IOException("No image data");
105 if (block_identifier == '!') {
106 if (!readExtensionBlock()) throw new IOException("Unexpected EOF(2)");
110 // not a valid start character -- ignore it.
111 if (block_identifier != ',') continue;
113 if (!readLocalImageDescriptor()) throw new IOException("Unexpected EOF(3)");
114 p.data = new int[p.width * p.height];
117 // If we did not decode the requested index, need to go on
118 // to the next one (future implementations should consider
119 // caching already-decoded images here to allow for random
120 // access to animated GIF pages).
122 if (index < page) continue;
124 // If we did decode the requested index, we can return.
128 // Return the image thus-far decoded
132 /** Actually read the image data */
133 private void readImage()
134 throws IOException, IOException {
139 int xpos = 0, ypos = 0, pass = 0, i;
140 int prefix[] = new int[(1 << MAX_LWZ_BITS)];
141 int append[] = new int[(1 << MAX_LWZ_BITS)];
142 int stack[] = new int[(1 << MAX_LWZ_BITS)*2];
144 int codeSize, clearCode, inCode, endCode, oldCode, maxCode, code, firstCode;
146 // Initialize the decoder
147 if (!readIntoBuf(1)) throw new IOException("Unexpected EOF decoding image");
148 initialCodeSize = _buf[0];
150 // Look at the right color map, setting up transparency if called for.
151 int[] cmap = global_color_map;
152 if (hascmap) cmap = color_map;
153 if (trans_idx >= 0) cmap[trans_idx] = 0x00000000;
155 /* Initialize the decoder */
156 /* Set values for "special" numbers:
157 * clear code reset the decoder
158 * end code stop decoding
159 * code size size of the next code to retrieve
160 * max code next available table position
162 clearCode = 1 << initialCodeSize;
163 endCode = clearCode + 1;
164 codeSize = initialCodeSize + 1;
165 maxCode = clearCode + 2;
169 for (i = 0; i < clearCode; i++) append[i] = i;
170 top_idx = 0; // top of stack.
178 /* Read until we finish the image */
180 for (i = 0; i < rows; i++) {
181 for (xpos = 0; xpos < len;) {
184 /* Bummer -- our stack is empty. Now we have to work! */
185 code = getCode(codeSize);
186 if (code < 0) return;
188 if (code > maxCode || code == endCode) return;
189 if (code == clearCode) {
190 codeSize = initialCodeSize + 1;
191 maxCode = clearCode + 2;
196 // Last pass reset the decoder, so the first code we
197 // see must be a singleton. Seed the stack with it,
198 // and set up the old/first code pointers for
199 // insertion into the string table. We can't just
200 // roll this into the clearCode test above, because
201 // at that point we have not yet read the next code.
203 stack[top_idx++] = append[code];
211 // maxCode is always one bigger than our
212 // highest assigned code. If the code we see
213 // is equal to maxCode, then we are about to
214 // add a new string to the table. ???
215 if (code == maxCode) {
216 stack[top_idx++] = firstCode;
220 // Populate the stack by tracing the string in the
221 // string table from its tail to its head
222 while (code > clearCode) {
223 stack[top_idx++] = append[code];
226 firstCode = append[code];
228 // If there's no more room in our string table, quit.
229 // Otherwise, add a new string to the table
230 if (maxCode >= (1 << MAX_LWZ_BITS)) return;
232 // Push the head of the string onto the stack
233 stack[top_idx++] = firstCode;
235 // Add a new string to the string table
236 prefix[maxCode] = oldCode;
237 append[maxCode] = firstCode;
240 // maxCode tells us the maximum code value we can accept.
241 // If we see that we need more bits to represent it than
242 // we are requesting from the unpacker, we need to increase
243 // the number we ask for.
244 if ((maxCode >= (1 << codeSize)) && (maxCode < (1<<MAX_LWZ_BITS))) codeSize++;
248 // Pop the next color index off the stack
249 v = stack[--top_idx];
252 // Finally, we can set a pixel! Joy!
253 p.data[xpos + ypos * p.width] = cmap[v];
257 // If interlacing, the next ypos is not just +1
259 ypos += _interlaceStep[pass];
260 while (ypos >= rows) {
262 if (pass > 3) return;
263 ypos = _interlaceStart[pass];
270 /** Extract the next compression code from the file. */
271 private int getCode(int code_size) throws IOException {
274 while (bitsInWindow < code_size) {
275 // Not enough bits in our window to cover the request
279 // Not enough bytes in our buffer to add to the window
280 bytes = getDataBlock();
287 // Tack another byte onto the window, see if that's enough
288 window += (_buf[c]) << bitsInWindow;
295 // The next code will always be the last code_size bits of the window
296 ret = ((int)window) & ((1 << code_size) - 1);
298 // Shift data in the window to put the next code at the end
299 window >>= code_size;
300 bitsInWindow -= code_size;
304 /** Read the global image descriptor and optional global color map. Sets global_* variables. */
305 private boolean readGlobalImageDescriptor() throws IOException {
307 int aspect; // we ignore this.
310 if (!readIntoBuf(7) ) return false;
311 global_width = _buf[0] | (_buf[1] << 8);
312 global_height = _buf[2] | (_buf[3] << 8);
314 global_bgcolor = _buf[5];
316 global_cmapsize = 2 << (packed & 0x07);
317 global_hascmap = (packed & GLOBALCOLORMAP) == GLOBALCOLORMAP;
318 global_color_map = null;
320 // Read the color map, if we have one.
321 if (global_hascmap) {
322 if (!readColorMap(global_cmapsize,true)) {
330 /** Read a local image descriptor and optional local color map. */
331 private boolean readLocalImageDescriptor() throws IOException {
334 if (!readIntoBuf(9) ) return false;
336 left = _buf[0] | (_buf[1] << 8);
337 top = _buf[2] | (_buf[3] << 8);
338 p.width = _buf[4] | (_buf[5] << 8);
339 p.height = _buf[6] | (_buf[7] << 8);
341 hascmap = (packed & LOCALCOLORMAP) == LOCALCOLORMAP;
342 cmapsize = 2 << (packed & 0x07);
343 interlaced = (packed & INTERLACE) == INTERLACE;
346 // Read the local color table, if there is one.
347 return !(hascmap && !readColorMap(cmapsize,false));
350 /** Read a color map (global or local). */
351 private boolean readColorMap(int nColors, boolean isGlobal)
353 int[] map = new int[nColors];
354 for( int i=0; i < nColors; ++i) {
355 if (!readIntoBuf(3) ) return false;
356 map[i] = (_buf[0] << 16) | (_buf[1] << 8) | _buf[2] | 0xFF000000;
358 if (isGlobal) global_color_map = map;
359 else color_map = map;
363 /** Read the contents of a GIF89a Graphical Extension Block. */
364 private boolean readExtensionBlock() throws IOException {
365 if (!readIntoBuf(1) ) return false;
369 case 0x01: // Plain Text Extension
370 case 0xff: // Application Extension
371 case 0xfe: // Comment Extension
373 case 0xf9: // Graphic Control Extension
374 count = getDataBlock();
375 if (count < 0) return true;
376 // Check for transparency setting.
377 if ((_buf[0] & HASTRANSPARENCY) != 0) trans_idx = _buf[3];
380 do { count = getDataBlock(); } while (count > 0);
384 /** Read a block of data from the GIF file. */
385 private int getDataBlock() throws IOException {
386 if (!readIntoBuf(1) ) return -1;
388 if (count != 0) if (!readIntoBuf(count) ) return -1;
392 /** Read the indicated number of bytes into _buf, our instance-wide buffer. */
393 private boolean readIntoBuf(int count) throws IOException {
394 for(int i = 0; i < count; i++) if ((_buf[i] = _in.read()) == -1) return false;
398 // Private Data //////////////////////////////////////////////////////////
402 // State management stuff
403 private int index = -1;
404 private BufferedInputStream _in = null;
405 private int[] _buf = new int[BUFSIZE];
407 // Transparency settings
408 private int trans_idx = -1;
410 // Global image descriptor contents
411 private int global_width = 0;
412 private int global_height = 0;
413 private int global_bgcolor = 0;
414 private int global_cmapsize = 0;
415 private boolean global_hascmap = false;
416 private int[] global_color_map = null;
418 // Local image descriptor contents
419 private int left = 0;
421 private int cmapsize = 0;
422 private boolean hascmap = false;
423 private boolean interlaced = false;
424 private int[] color_map = null;
426 // Variables used in getCode(...) to track sliding bit-window.
427 private int bytes = 0;
428 private boolean done;
431 private int bitsInWindow = 0;
433 // Class-wide constants.
434 private static final int INTERLACE = 0x40;
435 private static final int GLOBALCOLORMAP = 0x80;
436 private static final int LOCALCOLORMAP = 0x80;
437 private static final int HASTRANSPARENCY = 0x01;
438 private static final int MAX_LWZ_BITS = 12;
439 private static final int BUFSIZE = 280;
440 private static final int[] _interlaceStep = { 8, 8, 4, 2 };
441 private static final int[] _interlaceStart = { 0, 4, 2, 1 };