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.translators;
47 import org.ibex.util.*;
48 import java.io.BufferedInputStream;
49 import java.io.InputStream;
50 import java.io.IOException;
51 import java.io.PrintWriter;
53 /** Converts an InputStream carrying a GIF image into an ARGB int[] */
56 // Public Methods /////////////////////////////////////////////////////////
60 private static Queue instances = new Queue(10);
62 public static void load(InputStream is, Picture p) {
63 GIF g = (GIF)instances.remove(false);
64 if (g == null) g = new GIF();
67 } catch (Exception e) {
68 if (Log.on) Log.info(GIF.class, e);
71 // FIXME: must reset fields
72 // if (instances.size() < 10) instances.append(g);
75 private void _load(InputStream is, Picture p) throws IOException {
77 if (is instanceof BufferedInputStream) _in = (BufferedInputStream)is;
78 else _in = new BufferedInputStream(is);
79 decodeAsBufferedImage(0);
86 /** Decode a particular frame from the GIF file. Frames must be decoded in order, starting with 0. */
87 private void decodeAsBufferedImage(int page) throws IOException, IOException {
89 // If the user requested a page already decoded, we cannot go back.
90 if (page <= index ) return;
92 // If we just started reading this stream, initialize the global info.
94 if (!readIntoBuf(6) || _buf[0] != 'G' || _buf[1] != 'I' || _buf[2] != 'F' ||
95 _buf[3] != '8' || !(_buf[4] == '7' || _buf[4] == '9') || _buf[5] != 'a')
96 throw new IOException("Not a GIF8Xa file.");
97 if (!readGlobalImageDescriptor()) throw new IOException("Unable to read GIF header.");
100 // Loop through the blocks in the image.
101 int block_identifier;
103 if(!readIntoBuf(1)) throw new IOException("Unexpected EOF(1)");
104 block_identifier = _buf[0];
105 if (block_identifier == ';') throw new IOException("No image data");
106 if (block_identifier == '!') {
107 if (!readExtensionBlock()) throw new IOException("Unexpected EOF(2)");
111 // not a valid start character -- ignore it.
112 if (block_identifier != ',') continue;
114 if (!readLocalImageDescriptor()) throw new IOException("Unexpected EOF(3)");
115 p.data = new int[p.width * p.height];
118 // If we did not decode the requested index, need to go on
119 // to the next one (future implementations should consider
120 // caching already-decoded images here to allow for random
121 // access to animated GIF pages).
123 if (index < page) continue;
125 // If we did decode the requested index, we can return.
129 // Return the image thus-far decoded
133 /** Actually read the image data */
134 private void readImage()
135 throws IOException, IOException {
140 int xpos = 0, ypos = 0, pass = 0, i;
141 int prefix[] = new int[(1 << MAX_LWZ_BITS)];
142 int append[] = new int[(1 << MAX_LWZ_BITS)];
143 int stack[] = new int[(1 << MAX_LWZ_BITS)*2];
145 int codeSize, clearCode, inCode, endCode, oldCode, maxCode, code, firstCode;
147 // Initialize the decoder
148 if (!readIntoBuf(1)) throw new IOException("Unexpected EOF decoding image");
149 initialCodeSize = _buf[0];
151 // Look at the right color map, setting up transparency if called for.
152 int[] cmap = global_color_map;
153 if (hascmap) cmap = color_map;
154 if (trans_idx >= 0) cmap[trans_idx] = 0x00000000;
156 /* Initialize the decoder */
157 /* Set values for "special" numbers:
158 * clear code reset the decoder
159 * end code stop decoding
160 * code size size of the next code to retrieve
161 * max code next available table position
163 clearCode = 1 << initialCodeSize;
164 endCode = clearCode + 1;
165 codeSize = initialCodeSize + 1;
166 maxCode = clearCode + 2;
170 for (i = 0; i < clearCode; i++) append[i] = i;
171 top_idx = 0; // top of stack.
179 /* Read until we finish the image */
181 for (i = 0; i < rows; i++) {
182 for (xpos = 0; xpos < len;) {
185 /* Bummer -- our stack is empty. Now we have to work! */
186 code = getCode(codeSize);
187 if (code < 0) return;
189 if (code > maxCode || code == endCode) return;
190 if (code == clearCode) {
191 codeSize = initialCodeSize + 1;
192 maxCode = clearCode + 2;
197 // Last pass reset the decoder, so the first code we
198 // see must be a singleton. Seed the stack with it,
199 // and set up the old/first code pointers for
200 // insertion into the string table. We can't just
201 // roll this into the clearCode test above, because
202 // at that point we have not yet read the next code.
204 stack[top_idx++] = append[code];
212 // maxCode is always one bigger than our
213 // highest assigned code. If the code we see
214 // is equal to maxCode, then we are about to
215 // add a new string to the table. ???
216 if (code == maxCode) {
217 stack[top_idx++] = firstCode;
221 // Populate the stack by tracing the string in the
222 // string table from its tail to its head
223 while (code > clearCode) {
224 stack[top_idx++] = append[code];
227 firstCode = append[code];
229 // If there's no more room in our string table, quit.
230 // Otherwise, add a new string to the table
231 if (maxCode >= (1 << MAX_LWZ_BITS)) return;
233 // Push the head of the string onto the stack
234 stack[top_idx++] = firstCode;
236 // Add a new string to the string table
237 prefix[maxCode] = oldCode;
238 append[maxCode] = firstCode;
241 // maxCode tells us the maximum code value we can accept.
242 // If we see that we need more bits to represent it than
243 // we are requesting from the unpacker, we need to increase
244 // the number we ask for.
245 if ((maxCode >= (1 << codeSize)) && (maxCode < (1<<MAX_LWZ_BITS))) codeSize++;
249 // Pop the next color index off the stack
250 v = stack[--top_idx];
253 // Finally, we can set a pixel! Joy!
254 p.data[xpos + ypos * p.width] = cmap[v];
258 // If interlacing, the next ypos is not just +1
260 ypos += _interlaceStep[pass];
261 while (ypos >= rows) {
263 if (pass > 3) return;
264 ypos = _interlaceStart[pass];
271 /** Extract the next compression code from the file. */
272 private int getCode(int code_size) throws IOException {
275 while (bitsInWindow < code_size) {
276 // Not enough bits in our window to cover the request
280 // Not enough bytes in our buffer to add to the window
281 bytes = getDataBlock();
288 // Tack another byte onto the window, see if that's enough
289 window += (_buf[c]) << bitsInWindow;
296 // The next code will always be the last code_size bits of the window
297 ret = ((int)window) & ((1 << code_size) - 1);
299 // Shift data in the window to put the next code at the end
300 window >>= code_size;
301 bitsInWindow -= code_size;
305 /** Read the global image descriptor and optional global color map. Sets global_* variables. */
306 private boolean readGlobalImageDescriptor() throws IOException {
308 int aspect; // we ignore this.
311 if (!readIntoBuf(7) ) return false;
312 global_width = _buf[0] | (_buf[1] << 8);
313 global_height = _buf[2] | (_buf[3] << 8);
315 global_bgcolor = _buf[5];
317 global_cmapsize = 2 << (packed & 0x07);
318 global_hascmap = (packed & GLOBALCOLORMAP) == GLOBALCOLORMAP;
319 global_color_map = null;
321 // Read the color map, if we have one.
322 if (global_hascmap) {
323 if (!readColorMap(global_cmapsize,true)) {
331 /** Read a local image descriptor and optional local color map. */
332 private boolean readLocalImageDescriptor() throws IOException {
335 if (!readIntoBuf(9) ) return false;
337 left = _buf[0] | (_buf[1] << 8);
338 top = _buf[2] | (_buf[3] << 8);
339 p.width = _buf[4] | (_buf[5] << 8);
340 p.height = _buf[6] | (_buf[7] << 8);
342 hascmap = (packed & LOCALCOLORMAP) == LOCALCOLORMAP;
343 cmapsize = 2 << (packed & 0x07);
344 interlaced = (packed & INTERLACE) == INTERLACE;
347 // Read the local color table, if there is one.
348 return !(hascmap && !readColorMap(cmapsize,false));
351 /** Read a color map (global or local). */
352 private boolean readColorMap(int nColors, boolean isGlobal)
354 int[] map = new int[nColors];
355 for( int i=0; i < nColors; ++i) {
356 if (!readIntoBuf(3) ) return false;
357 map[i] = (_buf[0] << 16) | (_buf[1] << 8) | _buf[2] | 0xFF000000;
359 if (isGlobal) global_color_map = map;
360 else color_map = map;
364 /** Read the contents of a GIF89a Graphical Extension Block. */
365 private boolean readExtensionBlock() throws IOException {
366 if (!readIntoBuf(1) ) return false;
370 case 0x01: // Plain Text Extension
371 case 0xff: // Application Extension
372 case 0xfe: // Comment Extension
374 case 0xf9: // Graphic Control Extension
375 count = getDataBlock();
376 if (count < 0) return true;
377 // Check for transparency setting.
378 if ((_buf[0] & HASTRANSPARENCY) != 0) trans_idx = _buf[3];
381 do { count = getDataBlock(); } while (count > 0);
385 /** Read a block of data from the GIF file. */
386 private int getDataBlock() throws IOException {
387 if (!readIntoBuf(1) ) return -1;
389 if (count != 0) if (!readIntoBuf(count) ) return -1;
393 /** Read the indicated number of bytes into _buf, our instance-wide buffer. */
394 private boolean readIntoBuf(int count) throws IOException {
395 for(int i = 0; i < count; i++) if ((_buf[i] = _in.read()) == -1) return false;
399 // Private Data //////////////////////////////////////////////////////////
403 // State management stuff
404 private int index = -1;
405 private BufferedInputStream _in = null;
406 private int[] _buf = new int[BUFSIZE];
408 // Transparency settings
409 private int trans_idx = -1;
411 // Global image descriptor contents
412 private int global_width = 0;
413 private int global_height = 0;
414 private int global_bgcolor = 0;
415 private int global_cmapsize = 0;
416 private boolean global_hascmap = false;
417 private int[] global_color_map = null;
419 // Local image descriptor contents
420 private int left = 0;
422 private int cmapsize = 0;
423 private boolean hascmap = false;
424 private boolean interlaced = false;
425 private int[] color_map = null;
427 // Variables used in getCode(...) to track sliding bit-window.
428 private int bytes = 0;
429 private boolean done;
432 private int bitsInWindow = 0;
434 // Class-wide constants.
435 private static final int INTERLACE = 0x40;
436 private static final int GLOBALCOLORMAP = 0x80;
437 private static final int LOCALCOLORMAP = 0x80;
438 private static final int HASTRANSPARENCY = 0x01;
439 private static final int MAX_LWZ_BITS = 12;
440 private static final int BUFSIZE = 280;
441 private static final int[] _interlaceStep = { 8, 8, 4, 2 };
442 private static final int[] _interlaceStart = { 0, 4, 2, 1 };