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.xwt.translators;
47 import org.xwt.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 public int[] getData() { return data; }
61 public int getWidth() { return width; }
62 public int getHeight() { return height; }
64 /** Processes an image from InputStream is; returns null if there is an error
65 @param name A string describing the image; used for error reporting.
67 public Picture fromInputStream(InputStream is, String name) {
69 if (is instanceof BufferedInputStream) _in = (BufferedInputStream)is;
70 else _in = new BufferedInputStream(is);
71 decodeAsBufferedImage(0);
72 return Platform.createPicture(data, width, height);
73 } catch (Exception e) {
74 if (Log.on) Log.log(GIF.class, e);
80 // Private Methods /////////////////////////////////////////////////////////
82 private int[] data = null;
84 /** Decode a particular frame from the GIF file. Frames must be decoded in order, starting with 0. */
85 private void decodeAsBufferedImage(int page) throws IOException, IOException {
87 // If the user requested a page already decoded, we cannot go back.
88 if (page <= index ) return;
90 // If we just started reading this stream, initialize the global info.
92 if (!readIntoBuf(6) || _buf[0] != 'G' || _buf[1] != 'I' || _buf[2] != 'F' ||
93 _buf[3] != '8' || !(_buf[4] == '7' || _buf[4] == '9') || _buf[5] != 'a')
94 throw new IOException("Not a GIF8Xa file.");
95 if (!readGlobalImageDescriptor()) throw new IOException("Unable to read GIF header.");
98 // Loop through the blocks in the image.
101 if(!readIntoBuf(1)) throw new IOException("Unexpected EOF(1)");
102 block_identifier = _buf[0];
103 if (block_identifier == ';') throw new IOException("No image data");
104 if (block_identifier == '!') {
105 if (!readExtensionBlock()) throw new IOException("Unexpected EOF(2)");
109 // not a valid start character -- ignore it.
110 if (block_identifier != ',') continue;
112 if (!readLocalImageDescriptor()) throw new IOException("Unexpected EOF(3)");
113 data = new int[width * height];
116 // If we did not decode the requested index, need to go on
117 // to the next one (future implementations should consider
118 // caching already-decoded images here to allow for random
119 // access to animated GIF pages).
121 if (index < page) continue;
123 // If we did decode the requested index, we can return.
127 // Return the image thus-far decoded
131 /** Actually read the image data */
132 private void readImage()
133 throws IOException, IOException {
138 int xpos = 0, ypos = 0, pass = 0, i;
139 int prefix[] = new int[(1 << MAX_LWZ_BITS)];
140 int append[] = new int[(1 << MAX_LWZ_BITS)];
141 int stack[] = new int[(1 << MAX_LWZ_BITS)*2];
143 int codeSize, clearCode, inCode, endCode, oldCode, maxCode, code, firstCode;
145 // Initialize the decoder
146 if (!readIntoBuf(1)) throw new IOException("Unexpected EOF decoding image");
147 initialCodeSize = _buf[0];
149 // Look at the right color map, setting up transparency if called for.
150 int[] cmap = global_color_map;
151 if (hascmap) cmap = color_map;
152 if (trans_idx >= 0) cmap[trans_idx] = 0x00000000;
154 /* Initialize the decoder */
155 /* Set values for "special" numbers:
156 * clear code reset the decoder
157 * end code stop decoding
158 * code size size of the next code to retrieve
159 * max code next available table position
161 clearCode = 1 << initialCodeSize;
162 endCode = clearCode + 1;
163 codeSize = initialCodeSize + 1;
164 maxCode = clearCode + 2;
168 for (i = 0; i < clearCode; i++) append[i] = i;
169 top_idx = 0; // top of stack.
177 /* Read until we finish the image */
179 for (i = 0; i < rows; i++) {
180 for (xpos = 0; xpos < len;) {
183 /* Bummer -- our stack is empty. Now we have to work! */
184 code = getCode(codeSize);
185 if (code < 0) return;
187 if (code > maxCode || code == endCode) return;
188 if (code == clearCode) {
189 codeSize = initialCodeSize + 1;
190 maxCode = clearCode + 2;
195 // Last pass reset the decoder, so the first code we
196 // see must be a singleton. Seed the stack with it,
197 // and set up the old/first code pointers for
198 // insertion into the string table. We can't just
199 // roll this into the clearCode test above, because
200 // at that point we have not yet read the next code.
202 stack[top_idx++] = append[code];
210 // maxCode is always one bigger than our
211 // highest assigned code. If the code we see
212 // is equal to maxCode, then we are about to
213 // add a new string to the table. ???
214 if (code == maxCode) {
215 stack[top_idx++] = firstCode;
219 // Populate the stack by tracing the string in the
220 // string table from its tail to its head
221 while (code > clearCode) {
222 stack[top_idx++] = append[code];
225 firstCode = append[code];
227 // If there's no more room in our string table, quit.
228 // Otherwise, add a new string to the table
229 if (maxCode >= (1 << MAX_LWZ_BITS)) return;
231 // Push the head of the string onto the stack
232 stack[top_idx++] = firstCode;
234 // Add a new string to the string table
235 prefix[maxCode] = oldCode;
236 append[maxCode] = firstCode;
239 // maxCode tells us the maximum code value we can accept.
240 // If we see that we need more bits to represent it than
241 // we are requesting from the unpacker, we need to increase
242 // the number we ask for.
243 if ((maxCode >= (1 << codeSize)) && (maxCode < (1<<MAX_LWZ_BITS))) codeSize++;
247 // Pop the next color index off the stack
248 v = stack[--top_idx];
251 // Finally, we can set a pixel! Joy!
252 data[xpos + ypos * width] = cmap[v];
256 // If interlacing, the next ypos is not just +1
258 ypos += _interlaceStep[pass];
259 while (ypos >= rows) {
261 if (pass > 3) return;
262 ypos = _interlaceStart[pass];
269 /** Extract the next compression code from the file. */
270 private int getCode(int code_size) throws IOException {
273 while (bitsInWindow < code_size) {
274 // Not enough bits in our window to cover the request
278 // Not enough bytes in our buffer to add to the window
279 bytes = getDataBlock();
286 // Tack another byte onto the window, see if that's enough
287 window += (_buf[c]) << bitsInWindow;
294 // The next code will always be the last code_size bits of the window
295 ret = ((int)window) & ((1 << code_size) - 1);
297 // Shift data in the window to put the next code at the end
298 window >>= code_size;
299 bitsInWindow -= code_size;
303 /** Read the global image descriptor and optional global color map. Sets global_* variables. */
304 private boolean readGlobalImageDescriptor() throws IOException {
306 int aspect; // we ignore this.
309 if (!readIntoBuf(7) ) return false;
310 global_width = _buf[0] | (_buf[1] << 8);
311 global_height = _buf[2] | (_buf[3] << 8);
313 global_bgcolor = _buf[5];
315 global_cmapsize = 2 << (packed & 0x07);
316 global_hascmap = (packed & GLOBALCOLORMAP) == GLOBALCOLORMAP;
317 global_color_map = null;
319 // Read the color map, if we have one.
320 if (global_hascmap) {
321 if (!readColorMap(global_cmapsize,true)) {
329 /** Read a local image descriptor and optional local color map. */
330 private boolean readLocalImageDescriptor() throws IOException {
333 if (!readIntoBuf(9) ) return false;
335 left = _buf[0] | (_buf[1] << 8);
336 top = _buf[2] | (_buf[3] << 8);
337 width = _buf[4] | (_buf[5] << 8);
338 height = _buf[6] | (_buf[7] << 8);
340 hascmap = (packed & LOCALCOLORMAP) == LOCALCOLORMAP;
341 cmapsize = 2 << (packed & 0x07);
342 interlaced = (packed & INTERLACE) == INTERLACE;
345 // Read the local color table, if there is one.
346 return !(hascmap && !readColorMap(cmapsize,false));
349 /** Read a color map (global or local). */
350 private boolean readColorMap(int nColors, boolean isGlobal)
352 int[] map = new int[nColors];
353 for( int i=0; i < nColors; ++i) {
354 if (!readIntoBuf(3) ) return false;
355 map[i] = (_buf[0] << 16) | (_buf[1] << 8) | _buf[2] | 0xFF000000;
357 if (isGlobal) global_color_map = map;
358 else color_map = map;
362 /** Read the contents of a GIF89a Graphical Extension Block. */
363 private boolean readExtensionBlock() throws IOException {
364 if (!readIntoBuf(1) ) return false;
368 case 0x01: // Plain Text Extension
369 case 0xff: // Application Extension
370 case 0xfe: // Comment Extension
372 case 0xf9: // Graphic Control Extension
373 count = getDataBlock();
374 if (count < 0) return true;
375 // Check for transparency setting.
376 if ((_buf[0] & HASTRANSPARENCY) != 0) trans_idx = _buf[3];
379 do { count = getDataBlock(); } while (count > 0);
383 /** Read a block of data from the GIF file. */
384 private int getDataBlock() throws IOException {
385 if (!readIntoBuf(1) ) return -1;
387 if (count != 0) if (!readIntoBuf(count) ) return -1;
391 /** Read the indicated number of bytes into _buf, our instance-wide buffer. */
392 private boolean readIntoBuf(int count) throws IOException {
393 for(int i = 0; i < count; i++) if ((_buf[i] = _in.read()) == -1) return false;
397 // Private Data //////////////////////////////////////////////////////////
399 // State management stuff
400 private int index = -1;
401 private BufferedInputStream _in = null;
402 private int[] _buf = new int[BUFSIZE];
404 // Transparency settings
405 private int trans_idx = -1;
407 // Global image descriptor contents
408 private int global_width = 0;
409 private int global_height = 0;
410 private int global_bgcolor = 0;
411 private int global_cmapsize = 0;
412 private boolean global_hascmap = false;
413 private int[] global_color_map = null;
415 // Local image descriptor contents
416 private int left = 0;
418 private int width = 0;
419 private int height = 0;
420 private int cmapsize = 0;
421 private boolean hascmap = false;
422 private boolean interlaced = false;
423 private int[] color_map = null;
425 // Variables used in getCode(...) to track sliding bit-window.
426 private int bytes = 0;
427 private boolean done;
430 private int bitsInWindow = 0;
432 // Class-wide constants.
433 private static final int INTERLACE = 0x40;
434 private static final int GLOBALCOLORMAP = 0x80;
435 private static final int LOCALCOLORMAP = 0x80;
436 private static final int HASTRANSPARENCY = 0x01;
437 private static final int MAX_LWZ_BITS = 12;
438 private static final int BUFSIZE = 280;
439 private static final int[] _interlaceStep = { 8, 8, 4, 2 };
440 private static final int[] _interlaceStart = { 0, 4, 2, 1 };