resolve darcs stupidity
[org.ibex.core.git] / src / org / ibex / graphics / 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.ibex.translators;
45
46 import org.ibex.*;
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;
52
53 /** Converts an InputStream carrying a GIF image into an ARGB int[] */
54 public class GIF {
55
56     // Public Methods /////////////////////////////////////////////////////////
57
58     private GIF() { }
59
60     private static Queue instances = new Queue(10);
61
62     public static void load(InputStream is, Picture p) {
63         GIF g = (GIF)instances.remove(false);
64         if (g == null) g = new GIF();
65         try {
66             g._load(is, p);
67         } catch (Exception e) {
68             if (Log.on) Log.info(GIF.class, e);
69             return;
70         }
71         // FIXME: must reset fields
72         // if (instances.size() < 10) instances.append(g);
73     }
74
75     private void _load(InputStream is, Picture p) throws IOException {
76         this.p = p;
77         if (is instanceof BufferedInputStream) _in = (BufferedInputStream)is;
78         else _in = new BufferedInputStream(is);
79         decodeAsBufferedImage(0);
80         p.isLoaded = true;
81         p = null;
82         _in = null;
83     }
84
85
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 {
88
89         // If the user requested a page already decoded, we cannot go back.
90         if (page <= index ) return;
91
92         // If we just started reading this stream, initialize the global info.
93         if (index < 0 ) {
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.");
98         }
99         
100         // Loop through the blocks in the image.
101         int block_identifier;
102         while (true) {
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)");
108                 continue;
109             }
110
111             // not a valid start character -- ignore it.
112             if (block_identifier != ',') continue;
113
114             if (!readLocalImageDescriptor()) throw new IOException("Unexpected EOF(3)");
115             p.data = new int[p.width * p.height];
116             readImage();
117
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).
122             index++;
123             if (index < page) continue;
124             
125             // If we did decode the requested index, we can return.
126             break;
127         }
128         
129         // Return the image thus-far decoded
130         return;
131     }
132
133     /** Actually read the image data */
134     private void readImage() 
135         throws IOException, IOException {
136         int len = p.width;
137         int rows = p.height;
138         int initialCodeSize;
139         int v;
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];
144         int top_idx;
145         int codeSize, clearCode, inCode, endCode, oldCode, maxCode, code, firstCode;
146         
147         // Initialize the decoder
148         if (!readIntoBuf(1)) throw new IOException("Unexpected EOF decoding image");
149         initialCodeSize = _buf[0];
150
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;
155
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
162          */
163         clearCode   = 1 << initialCodeSize;
164         endCode     = clearCode + 1;
165         codeSize    = initialCodeSize + 1;
166         maxCode     = clearCode + 2;
167         oldCode     = -1;
168         firstCode   = -1;
169         
170         for (i = 0; i < clearCode; i++) append[i] = i;
171         top_idx = 0; // top of stack.
172         
173         bitsInWindow = 0;
174         bytes = 0;
175         window = 0L;
176         done = false;
177         c = -1;
178         
179         /* Read until we finish the image */
180         ypos = 0;
181         for (i = 0; i < rows; i++) {
182             for (xpos = 0; xpos < len;) {
183                 
184                 if (top_idx == 0) {
185                     /* Bummer -- our stack is empty.  Now we have to work! */
186                     code = getCode(codeSize);
187                     if (code < 0) return;
188                     
189                     if (code > maxCode || code == endCode) return;
190                     if (code == clearCode) {
191                         codeSize    = initialCodeSize + 1;
192                         maxCode     = clearCode + 2;
193                         oldCode     = -1;
194                         continue;
195                     }
196                     
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.
203                     if (oldCode == -1) {
204                         stack[top_idx++] = append[code];
205                         oldCode = code;
206                         firstCode = code;
207                         continue;
208                     }
209                     
210                     inCode = code;
211
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;
218                         code = oldCode;
219                     }
220                     
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];
225                         code = prefix[code];
226                     }
227                     firstCode = append[code];
228                     
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;
232                     
233                     // Push the head of the string onto the stack
234                     stack[top_idx++] = firstCode;
235                     
236                     // Add a new string to the string table
237                     prefix[maxCode] = oldCode;
238                     append[maxCode] = firstCode;
239                     maxCode++;
240                     
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++;
246                     oldCode = inCode;
247                 }
248                 
249                 // Pop the next color index off the stack
250                 v = stack[--top_idx];
251                 if (v < 0) return;
252                 
253                 // Finally, we can set a pixel!  Joy!
254                 p.data[xpos + ypos * p.width] = cmap[v];
255                 xpos++;
256             }
257             
258             // If interlacing, the next ypos is not just +1
259             if (interlaced) {
260                 ypos += _interlaceStep[pass];
261                 while (ypos >= rows) {
262                     pass++;
263                     if (pass > 3) return;
264                     ypos = _interlaceStart[pass];
265                 }
266             } else ypos++;
267         }
268         return;
269     }
270
271     /** Extract the next compression code from the file. */
272     private int getCode(int code_size) throws IOException {
273         int ret;
274         
275         while (bitsInWindow < code_size) {
276             // Not enough bits in our window to cover the request
277             if (done) return -1;
278             
279             if (bytes == 0) {
280                 // Not enough bytes in our buffer to add to the window
281                 bytes = getDataBlock();
282                 c = 0;
283                 if (bytes <= 0) {
284                     done = true;
285                     break;
286                 }
287             }
288             // Tack another byte onto the window, see if that's enough
289             window += (_buf[c]) << bitsInWindow;
290             ++c;
291             bitsInWindow += 8;
292             bytes--;
293         }
294         
295         
296         // The next code will always be the last code_size bits of the window
297         ret = ((int)window) & ((1 << code_size) - 1);
298         
299         // Shift data in the window to put the next code at the end
300         window >>= code_size;
301         bitsInWindow -= code_size;
302         return ret;
303     }
304     
305     /** Read the global image descriptor and optional global color map. Sets global_* variables. */
306     private boolean readGlobalImageDescriptor() throws IOException {
307         int packed;
308         int aspect; // we ignore this.
309         int ofs;
310         
311         if (!readIntoBuf(7) ) return false;
312         global_width     = _buf[0] | (_buf[1] << 8);
313         global_height    = _buf[2] | (_buf[3] << 8);
314         packed       = _buf[4];
315         global_bgcolor   = _buf[5];
316         aspect       = _buf[6];
317         global_cmapsize  = 2 << (packed & 0x07);
318         global_hascmap   = (packed & GLOBALCOLORMAP) == GLOBALCOLORMAP;
319         global_color_map = null;
320         
321         // Read the color map, if we have one.
322         if (global_hascmap) {
323             if (!readColorMap(global_cmapsize,true)) {
324                 return false;
325             }
326         }
327         
328         return true;
329     }
330     
331     /** Read a local image descriptor and optional local color map. */
332     private boolean readLocalImageDescriptor() throws IOException {
333         int packed;
334         
335         if (!readIntoBuf(9) ) return false;
336         
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);
341         packed        = _buf[8];
342         hascmap    = (packed & LOCALCOLORMAP) == LOCALCOLORMAP;
343         cmapsize   = 2 << (packed & 0x07);
344         interlaced = (packed & INTERLACE) == INTERLACE;
345         color_map  = null;
346         
347         // Read the local color table, if there is one.
348         return !(hascmap && !readColorMap(cmapsize,false));
349     }
350
351     /** Read a color map (global or local). */
352     private boolean readColorMap(int nColors, boolean isGlobal)
353         throws IOException {
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;
358         }
359         if (isGlobal) global_color_map = map;
360         else color_map = map;
361         return true;
362     }
363
364     /** Read the contents of a GIF89a Graphical Extension Block. */
365     private boolean readExtensionBlock() throws IOException {
366         if (!readIntoBuf(1) ) return false;
367         int label = _buf[0];
368         int count = -1;
369         switch (label) {
370         case 0x01:      // Plain Text Extension
371         case 0xff:      // Application Extension
372         case 0xfe:      // Comment Extension
373             break;
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];
379             else trans_idx = -1;
380         }
381         do { count = getDataBlock(); } while (count > 0);
382         return true;
383     }
384
385     /** Read a block of data from the GIF file. */
386     private int getDataBlock() throws IOException {
387         if (!readIntoBuf(1) ) return -1;
388         int count = _buf[0];
389         if (count != 0) if (!readIntoBuf(count) ) return -1;
390         return count;
391     }
392     
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;
396         return true;
397     }
398
399     // Private Data //////////////////////////////////////////////////////////
400
401     private Picture p;
402
403     // State management stuff
404     private int index = -1;
405     private BufferedInputStream _in = null;
406     private int[] _buf = new int[BUFSIZE];
407
408     // Transparency settings
409     private int trans_idx = -1;
410
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;
418
419     // Local image descriptor contents
420     private int left = 0;
421     private int top = 0;
422     private int cmapsize = 0;
423     private boolean hascmap = false;
424     private boolean interlaced = false;
425     private int[] color_map = null;
426
427     // Variables used in getCode(...) to track sliding bit-window.
428     private int     bytes = 0;
429     private boolean done;
430     private int     c;
431     private long    window;
432     private int     bitsInWindow = 0;
433
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 };
443 }
444
445
446