2003/09/19 08:33:47
[org.ibex.core.git] / src / org / xwt / translators / GIF.java
1 /*
2  * This file was adapted from D J Hagberg's GifDecoder.java
3  *
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.
7  * 
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
16  * they apply.
17  * 
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.
23  * 
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
29  * MODIFICATIONS.
30  * 
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.
42  *
43  */
44 package org.xwt.translators;
45
46 import org.xwt.*;
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;
52
53 /** Converts an InputStream carrying a GIF image into an ARGB int[] */
54 public class GIF extends ImageDecoder {
55
56     // Public Methods /////////////////////////////////////////////////////////
57
58     public int[] getData() { return data; }
59     public int getWidth() { return width; }
60     public int getHeight() { return height; }
61
62     /** Processes an image from InputStream is; returns null if there is an error
63         @param name A string describing the image; used for error reporting.
64      */
65     public static GIF decode(InputStream is, String name) {
66         try {
67             return new GIF(is, name);
68         } catch (Exception e) {
69             if (Log.on) Log.log(GIF.class, e);
70             return null;
71         }
72     }
73
74     private GIF(InputStream is, String name) throws IOException {
75         if (is instanceof BufferedInputStream) _in = (BufferedInputStream)is;
76         else _in = new BufferedInputStream(is);
77         decodeAsBufferedImage(0);
78     }
79
80     // Private Methods /////////////////////////////////////////////////////////
81
82     private int[] data = null;
83
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 {
86
87         // If the user requested a page already decoded, we cannot go back.
88         if (page <= index ) return;
89
90         // If we just started reading this stream, initialize the global info.
91         if (index < 0 ) {
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.");
96         }
97         
98         // Loop through the blocks in the image.
99         int block_identifier;
100         while (true) {
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)");
106                 continue;
107             }
108
109             // not a valid start character -- ignore it.
110             if (block_identifier != ',') continue;
111
112             if (!readLocalImageDescriptor()) throw new IOException("Unexpected EOF(3)");
113             data = new int[width * height];
114             readImage();
115
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).
120             index++;
121             if (index < page) continue;
122             
123             // If we did decode the requested index, we can return.
124             break;
125         }
126         
127         // Return the image thus-far decoded
128         return;
129     }
130
131     /** Actually read the image data */
132     private void readImage() 
133         throws IOException, IOException {
134         int len = width;
135         int rows = height;
136         int initialCodeSize;
137         int v;
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];
142         int top_idx;
143         int codeSize, clearCode, inCode, endCode, oldCode, maxCode, code, firstCode;
144         
145         // Initialize the decoder
146         if (!readIntoBuf(1)) throw new IOException("Unexpected EOF decoding image");
147         initialCodeSize = _buf[0];
148
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;
153
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
160          */
161         clearCode   = 1 << initialCodeSize;
162         endCode     = clearCode + 1;
163         codeSize    = initialCodeSize + 1;
164         maxCode     = clearCode + 2;
165         oldCode     = -1;
166         firstCode   = -1;
167         
168         for (i = 0; i < clearCode; i++) append[i] = i;
169         top_idx = 0; // top of stack.
170         
171         bitsInWindow = 0;
172         bytes = 0;
173         window = 0L;
174         done = false;
175         c = -1;
176         
177         /* Read until we finish the image */
178         ypos = 0;
179         for (i = 0; i < rows; i++) {
180             for (xpos = 0; xpos < len;) {
181                 
182                 if (top_idx == 0) {
183                     /* Bummer -- our stack is empty.  Now we have to work! */
184                     code = getCode(codeSize);
185                     if (code < 0) return;
186                     
187                     if (code > maxCode || code == endCode) return;
188                     if (code == clearCode) {
189                         codeSize    = initialCodeSize + 1;
190                         maxCode     = clearCode + 2;
191                         oldCode     = -1;
192                         continue;
193                     }
194                     
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.
201                     if (oldCode == -1) {
202                         stack[top_idx++] = append[code];
203                         oldCode = code;
204                         firstCode = code;
205                         continue;
206                     }
207                     
208                     inCode = code;
209
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;
216                         code = oldCode;
217                     }
218                     
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];
223                         code = prefix[code];
224                     }
225                     firstCode = append[code];
226                     
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;
230                     
231                     // Push the head of the string onto the stack
232                     stack[top_idx++] = firstCode;
233                     
234                     // Add a new string to the string table
235                     prefix[maxCode] = oldCode;
236                     append[maxCode] = firstCode;
237                     maxCode++;
238                     
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++;
244                     oldCode = inCode;
245                 }
246                 
247                 // Pop the next color index off the stack
248                 v = stack[--top_idx];
249                 if (v < 0) return;
250                 
251                 // Finally, we can set a pixel!  Joy!
252                 data[xpos + ypos * width] = cmap[v];
253                 xpos++;
254             }
255             
256             // If interlacing, the next ypos is not just +1
257             if (interlaced) {
258                 ypos += _interlaceStep[pass];
259                 while (ypos >= rows) {
260                     pass++;
261                     if (pass > 3) return;
262                     ypos = _interlaceStart[pass];
263                 }
264             } else ypos++;
265         }
266         return;
267     }
268
269     /** Extract the next compression code from the file. */
270     private int getCode(int code_size) throws IOException {
271         int ret;
272         
273         while (bitsInWindow < code_size) {
274             // Not enough bits in our window to cover the request
275             if (done) return -1;
276             
277             if (bytes == 0) {
278                 // Not enough bytes in our buffer to add to the window
279                 bytes = getDataBlock();
280                 c = 0;
281                 if (bytes <= 0) {
282                     done = true;
283                     break;
284                 }
285             }
286             // Tack another byte onto the window, see if that's enough
287             window += (_buf[c]) << bitsInWindow;
288             ++c;
289             bitsInWindow += 8;
290             bytes--;
291         }
292         
293         
294         // The next code will always be the last code_size bits of the window
295         ret = ((int)window) & ((1 << code_size) - 1);
296         
297         // Shift data in the window to put the next code at the end
298         window >>= code_size;
299         bitsInWindow -= code_size;
300         return ret;
301     }
302     
303     /** Read the global image descriptor and optional global color map. Sets global_* variables. */
304     private boolean readGlobalImageDescriptor() throws IOException {
305         int packed;
306         int aspect; // we ignore this.
307         int ofs;
308         
309         if (!readIntoBuf(7) ) return false;
310         global_width     = _buf[0] | (_buf[1] << 8);
311         global_height    = _buf[2] | (_buf[3] << 8);
312         packed       = _buf[4];
313         global_bgcolor   = _buf[5];
314         aspect       = _buf[6];
315         global_cmapsize  = 2 << (packed & 0x07);
316         global_hascmap   = (packed & GLOBALCOLORMAP) == GLOBALCOLORMAP;
317         global_color_map = null;
318         
319         // Read the color map, if we have one.
320         if (global_hascmap) {
321             if (!readColorMap(global_cmapsize,true)) {
322                 return false;
323             }
324         }
325         
326         return true;
327     }
328     
329     /** Read a local image descriptor and optional local color map. */
330     private boolean readLocalImageDescriptor() throws IOException {
331         int packed;
332         
333         if (!readIntoBuf(9) ) return false;
334         
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);
339         packed        = _buf[8];
340         hascmap    = (packed & LOCALCOLORMAP) == LOCALCOLORMAP;
341         cmapsize   = 2 << (packed & 0x07);
342         interlaced = (packed & INTERLACE) == INTERLACE;
343         color_map  = null;
344         
345         // Read the local color table, if there is one.
346         return !(hascmap && !readColorMap(cmapsize,false));
347     }
348
349     /** Read a color map (global or local). */
350     private boolean readColorMap(int nColors, boolean isGlobal)
351         throws IOException {
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;
356         }
357         if (isGlobal) global_color_map = map;
358         else color_map = map;
359         return true;
360     }
361
362     /** Read the contents of a GIF89a Graphical Extension Block. */
363     private boolean readExtensionBlock() throws IOException {
364         if (!readIntoBuf(1) ) return false;
365         int label = _buf[0];
366         int count = -1;
367         switch (label) {
368         case 0x01:      // Plain Text Extension
369         case 0xff:      // Application Extension
370         case 0xfe:      // Comment Extension
371             break;
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];
377             else trans_idx = -1;
378         }
379         do { count = getDataBlock(); } while (count > 0);
380         return true;
381     }
382
383     /** Read a block of data from the GIF file. */
384     private int getDataBlock() throws IOException {
385         if (!readIntoBuf(1) ) return -1;
386         int count = _buf[0];
387         if (count != 0) if (!readIntoBuf(count) ) return -1;
388         return count;
389     }
390     
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;
394         return true;
395     }
396
397     // Private Data //////////////////////////////////////////////////////////
398
399     // State management stuff
400     private int index = -1;
401     private BufferedInputStream _in = null;
402     private int[] _buf = new int[BUFSIZE];
403
404     // Transparency settings
405     private int trans_idx = -1;
406
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;
414
415     // Local image descriptor contents
416     private int left = 0;
417     private int top = 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;
424
425     // Variables used in getCode(...) to track sliding bit-window.
426     private int     bytes = 0;
427     private boolean done;
428     private int     c;
429     private long    window;
430     private int     bitsInWindow = 0;
431
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 };
441 }
442
443
444