summaryrefslogtreecommitdiff
path: root/libjava/classpath/gnu/javax/imageio/gif/GIFFile.java
blob: 941397a0e7b719bf95036692c82dc8ef919b6d71 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
/* GIFFile.java -- GIF decoder
   Copyright (C) 2006  Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */

package gnu.javax.imageio.gif;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

/**
 * GIFFile - reads a GIF file.
 *
 * This class only does the bare minimum work, and returns the data in raw
 * formats (described below). The class is J2ME compatible, and hopefully
 * we can keep it that way without any significant overhead.
 *
 * @author Sven de Marothy.
 */
public class GIFFile
{
  // "NETSCAPE2.0" - identifier
  private final static byte[] nsBlock = new byte[]
  {0x4e, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45, 0x32, 0x2e, 0x30 };

  /**
   * Block identifiers
   */
  private final static int EXTENSION = 0x21;
  private final static int LOCAL = 0x2C;
  private final static int TERMINATOR = 0x3B;

  /**
   * Extension block types
   */
  private final static int EXTENSION_COMMENT = 254;
  private final static int EXTENSION_GCONTROL = 249;
  private final static int EXTENSION_APPLICATION = 255;

  /**
   * Undraw commands for animation.
   */
  private final static int UNDRAW_OVERWRITE = 1;
  private final static int UNDRAW_RESTORE_BACKGROUND = 2;
  private final static int UNDRAW_RESTORE_PREVIOUS = 3;

  /**
   * Image position and dimensions (images may be partial)
   */
  private int x, y, width, height;

  /**
   * Global dimensions
   */
  private int globalWidth, globalHeight;

  /**
   * Background color index.
   */
  private byte bgIndex;

  /**
   * Number of colors
   */
  private int nColors;

  /**
   * Global palette, if any
   */
  private byte[] globalPalette;

  /**
   * Any
   */
  private boolean hasGlobalColorMap;

  /**
   * Local palette, if any (used if available)
   */
  private byte[] localPalette;

  /**
   * Interlaced GIF or not?
   */
  private boolean interlaced;

  /**
   * Has transparency?
   */
  private boolean hasTransparency;

  /**
   * Undraw mode (animations)
   */
  private int undraw;

  /**
   * Transparent index;
   */
  private int transparentIndex;

  /**
   * The uncompressed raster
   */
  private byte[] raster;

  /**
   * The compressed data (freed after uncompressing)
   */
  private byte[] compressedData;

  /**
   * Frame delay in 100ths of a second ( centiseconds, metrically )
   */
  private int duration;

  /**
   * Indices used during decompression
   */
  private int dataBlockIndex;

  /**
   * The file comment , if a comment block exists.
   */
  private String comment;

  /**
   * Fields used by getBits()
   */
  private int remainingBits = 0;
  private int currentBits = 0;

  /**
   * Netscape animation extension
   */
  private boolean isLooped = false;

  /** Number of loops, 0 = infinite */
  private int loops;

  /**
   * Additional frames if it's an animated GIF.
   */
  private Vector animationFrames;

  /**
   * Loads the file from an input stream, which is not closed.
   * @throws IOException if an I/O error occured.
   * @throws GIFException if some file parsing error occured
   */
  public GIFFile(InputStream in) throws IOException, GIFException
  {
    // Validate the signature
    if( !readSignature( in ) )
      throw new GIFException("Invalid GIF signature.");

    {
      byte[] data = new byte[7];
      if (in.read(data) != 7)
        throw new IOException("Couldn't read global descriptor.");

      globalWidth = ((data[1] & 0xFF) << 8) | (data[0] & 0xFF);
      globalHeight = ((data[3] & 0xFF) << 8) | (data[2] & 0xFF);
      byte flags = data[4];
      bgIndex = data[5];
      nColors = (1 << (( flags & 0x07) + 1));
      hasGlobalColorMap = ((flags & 0x80) != 0);
    }

    if( hasGlobalColorMap )
      {
        globalPalette = new byte[ nColors * 3 ];
        if( in.read( globalPalette ) != nColors * 3 )
          throw new IOException("Couldn't read color map.");
      }

    int c = in.read();
    while( c == EXTENSION )
      {
        readExtension( in );
        c = in.read();
      }

    if( c != LOCAL )
      throw new GIFException("Extension blocks not followed by a local descriptor ("+c+")");

    loadImage( in );
    c = in.read();

    if( c == TERMINATOR ) // Not an animated GIF.
      return;

    // Load animation frames. Just quit if an error occurs instead
    // of throwing an exception.
    animationFrames = new Vector();
    try
      {
        while( c != TERMINATOR )
          {
            animationFrames.add( new GIFFile( this, in, c ) );
            c = in.read();
          }
      }
    catch(IOException ioe)
      {
      }
    catch(GIFException gife)
      {
      }
  }

  /**
   * Constructor for additional animation frames.
   */
  private GIFFile(GIFFile parent, InputStream in, int c)
    throws IOException, GIFException
  {
    // Copy global properties.
    globalWidth = parent.globalWidth;
    globalHeight = parent.globalHeight;
    nColors = parent.nColors;
    globalPalette = parent.globalPalette;
    hasGlobalColorMap = parent.hasGlobalColorMap;
    interlaced = parent.interlaced;
    comment = parent.comment;
    isLooped = parent.isLooped;
    loops = parent.loops;

    while( c == EXTENSION )
    {
      readExtension( in );
      c = in.read();
    }

    if( c != LOCAL )
      throw new GIFException("Extension blocks not followed by a local descriptor ("+c+")");

    loadImage( in );
  }

  /**
   * Reads a GIF file signature from an inputstream and checks it.
   *
   * @param in - the stream (reads 6 bytes, does not close or reset).
   * @return true if the signature is a valid GIF signature.
   * @throws IOException if the signature could not be read.
   */
  public static boolean readSignature( InputStream in ) throws IOException
  {
    byte[] data = new byte[6];
    if (in.read(data) != 6)
      throw new IOException("Couldn't read signature.");

    if( data[0] != 0x47 || data[1] != 0x49 || data[2] != 0x46 ||
        data[3] != 0x38 ) // GIF8
      return false;

    if( (data[4] != 0x39 && data[4] != 0x37) || // 7 | 9
        (data[5] != 0x61 && data[5] != 0x62) ) // 'a' or 'b'
      return false;
    return true;
  }


  /**
   * Loads the image local descriptor and then loads/decodes the image raster,
   * and then performs any necessary postprocessing like deinterlacing.
   */
  private void loadImage(InputStream in)
    throws IOException, GIFException
  {
    readLocal( in );

    try
      {
        decodeRaster( in );
      }
    catch(ArrayIndexOutOfBoundsException aioobe)
      {
        throw new GIFException("Error decompressing image.");
      }

    if( interlaced )  // Clean up
      deinterlace();
    packPixels();
  }

  /**
   * Pack the pixels if it's a 2, 4 or 16 color image.
   * While GIF may support any number of colors from 2-256, we won't bother
   * trying to pack pixels not resulting in even byte boundaries.
   * (AWT doesn't support that anyway, and most apps do the same.)
   */
  private void packPixels()
  {
    if( nColors != 2 && nColors != 4 && nColors != 16 )
      return;

    int nbits = 1;
    int ppbyte = 8;
    if( nColors == 4 )
      {
        nbits = 2;
        ppbyte = 4;
      }
    else if( nColors == 16 )
      {
        nbits = 4;
        ppbyte = 2;
      }

    int rem = (width & (ppbyte - 1));
    int w = ( rem == 0 ) ? (width / ppbyte) :
      ((width + ppbyte - rem) / ppbyte);
    byte[] nr = new byte[ w * height ];
    for(int j = 0; j < height; j++)
      {
        for(int i = 0; i < width - ppbyte; i += ppbyte)
          for(int k = 0; k < ppbyte; k++)
            nr[ j * w + (i / ppbyte) ] |= (byte)((raster[ width * j + i + k ]
                                                  << (8 - nbits * (1 + k))));
        for(int i = 0; i < rem; i++)
          nr[ j * w + w - 1 ] |= (byte)((raster[ width * j + width - rem + i ]
                                         << (nbits * (rem - i))));
      }
    raster = nr;
  }

  /**
   * Returns the (global) width
   */
  public int getWidth()
  {
    return width;
  }

  /**
   * Returns the image height
   */
  public int getHeight()
  {
    return height;
  }

  /**
   * Returns the # of colors.
   */
  public int getNColors()
  {
    return nColors;
  }

  /**
   * Returns whether the GIF has transparency.
   */
  public boolean hasTransparency()
  {
    return hasTransparency;
  }

  /**
   * Returns the index of the transparent color.
   */
  public int getTransparentIndex()
  {
    return transparentIndex;
  }

  /**
   * Retuns the GIF file comment, or null if none exists.
   */
  public String getComment()
  {
    return comment;
  }

  /**
   * Get duration of the frame for animations.
   */
  public int getDuration()
  {
    return duration;
  }

  /**
   * Deinterlaces the image.
   */
  private void deinterlace()
  {
    byte[] nr = new byte[ width * height ];
    int n = 0;
    for(int i = 0; i < ((height + 7) >> 3); i++)
      {
        System.arraycopy( raster, n, nr, width * i * 8, width );
        n += width;
      }
    for(int i = 0; i < ((height + 3) >> 3); i++)
      {
        System.arraycopy( raster, n, nr, width * ( 8 * i + 4 ), width );
        n += width;
      }
    for(int i = 0; i < (height >> 2); i++)
      {
        System.arraycopy( raster, n, nr, width * (4 * i + 2), width );
        n += width;
      }
    for(int i = 0; i < (height >> 1); i++)
      {
        System.arraycopy( raster, n, nr, width * (2 * i + 1), width );
        n += width;
      }
    raster = nr;
  }

  /**
   * Reads the local descriptor
   */
  private void readLocal(InputStream in) throws IOException
  {
    byte[] data = new byte[9];
    if (in.read(data) != 9)
      throw new IOException("Couldn't read local descriptor.");
    x = ((data[1] & 0xFF) << 8) | (data[0] & 0xFF);
    y = ((data[3] & 0xFF) << 8) | (data[2] & 0xFF);
    width = ((data[5] & 0xFF) << 8) | (data[4] & 0xFF);
    height = ((data[7] & 0xFF) << 8) | (data[6] & 0xFF);
    byte flags = data[8];
    interlaced = (( flags & 0x40 ) != 0);
    if( (flags & 0x80) != 0 )
      { // has a local color map
        int nLocalColors = (1 << (( flags & 0x07) + 1));
        if( !hasGlobalColorMap )
          nColors = nLocalColors;
        localPalette = new byte[ nLocalColors * 3 ];
        if( in.read( localPalette ) != nLocalColors * 3 )
          throw new IOException("Couldn't read color map.");
      }
  }

  /**
   * Returns the image's palette in raw format
   * (r0,g0,b0,r1,g1,b2..r(Ncolors-1),g(Ncolors-1),b(Ncolors-1))
   */
  public byte[] getRawPalette()
  {
    return hasGlobalColorMap ? globalPalette : localPalette;
  }

  /**
   * Returns the image file for animated gifs.
   */
  public GIFFile getImage( int index )
  {
    if( index == 0 )
      return this;
    if( animationFrames == null )
      throw new ArrayIndexOutOfBoundsException("Only one image in file");
    return (GIFFile)animationFrames.elementAt( index - 1 );
  }

  /**
   * Return the image's raw image data.
   * If the color depth is 1,2 or 4 bits per pixel the pixels are packed
   * and the scanlines padded up to the nearest byte if needed.
   */
  public byte[] getRawImage()
  {
    return raster;
  }

  /**
   * Return the number of images in the GIF file
   */
  public int nImages()
  {
    if( animationFrames != null )
      return 1 + animationFrames.size();
    return 1;
  }

  /**
   * Handles extension blocks.
   */
  private void readExtension(InputStream in) throws IOException, GIFException
  {
    int functionCode = in.read();
    byte[] data = readData(in);
    switch( functionCode )
      {
      case EXTENSION_COMMENT: // comment block
        comment = new String(data, "8859_1");
        break;

      case EXTENSION_GCONTROL: // Graphics control extension
        undraw = (data[0] & 0x1C) >> 2;
        // allegedly there can be bad values of this.
        if( undraw < 1 && undraw > 3 ) undraw = 1;
        hasTransparency = ((data[0] & 0x01) == 1);
        transparentIndex = (data[3] & 0xFF);
        duration = ((data[2] & 0xFF) << 8) | (data[1] & 0xFF);
        break;

        // Application extension. We only parse the Netscape animation
        // extension here. Which is the only one most use anyway.
      case EXTENSION_APPLICATION:
        boolean isNS = true;
        for(int i = 0; i < nsBlock.length; i++ )
          if( nsBlock[i] != data[i] )
            isNS = false;
        if( isNS )
          {
            isLooped = true;
            loops = ((data[12] & 0xFF) << 8) | (data[13] & 0xFF);
          }
        break;

      default:
        break;
      }
  }

  /**
   * Reads a series of data blocks and merges them into a single one.
   */
  private byte[] readData(InputStream in) throws IOException
  {
    Vector v = new Vector();
    int totalBytes = 0;

    int n = in.read();
    do
      {
        totalBytes += n;
        byte[] block = new byte[ n ];
        in.read(block);
        v.add(block);
        n = in.read();
      }
    while( n > 0 );

    n = 0;
    byte[] bigBuffer = new byte[ totalBytes ];
    for( int i = 0; i < v.size(); i++ )
      {
        byte[] block = (byte[])v.elementAt(i);
        System.arraycopy(block, 0, bigBuffer, n, block.length);
        n += block.length;
      }
    return bigBuffer;
  }

  /**
   * Loads a compressed image block and decompresses it.
   */
  private void decodeRaster(InputStream in) throws IOException
  {
    int initialCodeSize = in.read();
    compressedData = readData( in );
    dataBlockIndex = 0;

    int rasterIndex = 0; // Index into the raster
    int clearCode = (1 << initialCodeSize); // 256 usually
    int endCode = clearCode + 1; // The stop code.

    raster = new byte[ width * height ];

    int codeSize = initialCodeSize + 1;
    int code = getBits( codeSize ); // = clear
    int nextCode = endCode + 1;

    /*
     * Initialize LZW dictionary
     *
     * First index - code #
     * Second index:
     * 0 = color index
     * 1 = parent (-1 - no parent)
     * 2 = first value
     * 3 - depth
     * The latter two aren't strictly necessary but make things faster, since
     * copying the values forward is faster than going back and looking.
     */
    short[][] dictionary = new short[ 4096 ][ 4 ];

    for(short i = 0; i < nColors; i ++ )
      {
        dictionary[i][0] = i;  // color index
        dictionary[i][1] = -1; // parent
        dictionary[i][2] = i;  // first
        dictionary[i][3] = 1;  // depth
      }

    code = getBits( codeSize ); // get second code
    raster[ rasterIndex++ ] = (byte)dictionary[code][0];
    int old = code;
    code = getBits( codeSize ); // start at the third code
    int c;

    do
      {
        if( code == clearCode )
          {
            codeSize = initialCodeSize + 1;
            nextCode = endCode + 1;
            // get and output second code
            code = getBits( codeSize );
            raster[ rasterIndex++ ] = (byte)dictionary[code][0];
            old = code;
          }
        else
          {
            dictionary[nextCode][1] = (short)old; // parent = old
            dictionary[nextCode][2] = dictionary[old][2]; // first pixel
            dictionary[nextCode][3] = (short)(dictionary[old][3] + 1); // depth

            // appended pixel  = first pixel of c
            if( code < nextCode )
              {
                dictionary[nextCode][0] = dictionary[code][2];
                old = code;
              }
            else // first of old
              {
                dictionary[nextCode][0] = dictionary[old][2];
                old = nextCode;
              }

            c = old;
            // output the code c
            int depth = dictionary[c][3];
            for( int i = depth - 1; i >= 0; i-- )
              {
                raster[ rasterIndex + i ] = (byte)dictionary[c][0];
                c = dictionary[c][1]; // go to parent.
              }
            rasterIndex += depth;
            nextCode ++;

            if( codeSize < 12 && nextCode >= (1 << codeSize) )
              codeSize++;
          }
        code = getBits( codeSize );
      }
    while( code != endCode && dataBlockIndex < compressedData.length );

    compressedData = null; // throw away compressed data.
  }

  /**
   * Returns nbits number of bits (in the LSBs) from compressedData
   */
  private int getBits( int nbits )
  {
    while( nbits > remainingBits )
      {
        int c = (compressedData[ dataBlockIndex++ ] & 0xFF) << remainingBits;
        currentBits |= c;
        remainingBits += 8;
      }
    int rval = (currentBits & ((1 << nbits) - 1));
    currentBits = (currentBits >> nbits);
    remainingBits -= nbits;
    return rval;
  }

  /**
   * Generic exception used by GIFFile to report decoding errors.
   */
  public static class GIFException extends Exception
  {
    public GIFException(String message)
    {
      super(message);
    }
  }
}