1 /*
   2  * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.imageio.plugins.png;
  27 
  28 import java.awt.Point;
  29 import java.awt.Rectangle;
  30 import java.awt.color.ColorSpace;
  31 import java.awt.image.BufferedImage;
  32 import java.awt.image.DataBuffer;
  33 import java.awt.image.DataBufferByte;
  34 import java.awt.image.DataBufferUShort;
  35 import java.awt.image.Raster;
  36 import java.awt.image.WritableRaster;
  37 import java.io.BufferedInputStream;
  38 import java.io.ByteArrayInputStream;
  39 import java.io.DataInputStream;
  40 import java.io.EOFException;
  41 import java.io.InputStream;
  42 import java.io.IOException;
  43 import java.io.SequenceInputStream;
  44 import java.util.ArrayList;
  45 import java.util.Arrays;
  46 import java.util.Enumeration;
  47 import java.util.Iterator;
  48 import java.util.zip.Inflater;
  49 import java.util.zip.InflaterInputStream;
  50 import javax.imageio.IIOException;
  51 import javax.imageio.ImageReader;
  52 import javax.imageio.ImageReadParam;
  53 import javax.imageio.ImageTypeSpecifier;
  54 import javax.imageio.metadata.IIOMetadata;
  55 import javax.imageio.spi.ImageReaderSpi;
  56 import javax.imageio.stream.ImageInputStream;
  57 import com.sun.imageio.plugins.common.InputStreamAdapter;
  58 import com.sun.imageio.plugins.common.ReaderUtil;
  59 import com.sun.imageio.plugins.common.SubImageInputStream;
  60 import java.io.ByteArrayOutputStream;
  61 import sun.awt.image.ByteInterleavedRaster;
  62 
  63 class PNGImageDataEnumeration implements Enumeration<InputStream> {
  64 
  65     boolean firstTime = true;
  66     ImageInputStream stream;
  67     int length;
  68 
  69     public PNGImageDataEnumeration(ImageInputStream stream)
  70         throws IOException {
  71         this.stream = stream;
  72         this.length = stream.readInt();
  73         int type = stream.readInt(); // skip chunk type
  74     }
  75 
  76     public InputStream nextElement() {
  77         try {
  78             firstTime = false;
  79             ImageInputStream iis = new SubImageInputStream(stream, length);
  80             return new InputStreamAdapter(iis);
  81         } catch (IOException e) {
  82             return null;
  83         }
  84     }
  85 
  86     public boolean hasMoreElements() {
  87         if (firstTime) {
  88             return true;
  89         }
  90 
  91         try {
  92             int crc = stream.readInt();
  93             this.length = stream.readInt();
  94             int type = stream.readInt();
  95             if (type == PNGImageReader.IDAT_TYPE) {
  96                 return true;
  97             } else {
  98                 return false;
  99             }
 100         } catch (IOException e) {
 101             return false;
 102         }
 103     }
 104 }
 105 
 106 public class PNGImageReader extends ImageReader {
 107 
 108     /*
 109      * Note: The following chunk type constants are autogenerated.  Each
 110      * one is derived from the ASCII values of its 4-character name.  For
 111      * example, IHDR_TYPE is calculated as follows:
 112      *            ('I' << 24) | ('H' << 16) | ('D' << 8) | 'R'
 113      */
 114 
 115     // Critical chunks
 116     static final int IHDR_TYPE = 0x49484452;
 117     static final int PLTE_TYPE = 0x504c5445;
 118     static final int IDAT_TYPE = 0x49444154;
 119     static final int IEND_TYPE = 0x49454e44;
 120 
 121     // Ancillary chunks
 122     static final int bKGD_TYPE = 0x624b4744;
 123     static final int cHRM_TYPE = 0x6348524d;
 124     static final int gAMA_TYPE = 0x67414d41;
 125     static final int hIST_TYPE = 0x68495354;
 126     static final int iCCP_TYPE = 0x69434350;
 127     static final int iTXt_TYPE = 0x69545874;
 128     static final int pHYs_TYPE = 0x70485973;
 129     static final int sBIT_TYPE = 0x73424954;
 130     static final int sPLT_TYPE = 0x73504c54;
 131     static final int sRGB_TYPE = 0x73524742;
 132     static final int tEXt_TYPE = 0x74455874;
 133     static final int tIME_TYPE = 0x74494d45;
 134     static final int tRNS_TYPE = 0x74524e53;
 135     static final int zTXt_TYPE = 0x7a545874;
 136 
 137     static final int PNG_COLOR_GRAY = 0;
 138     static final int PNG_COLOR_RGB = 2;
 139     static final int PNG_COLOR_PALETTE = 3;
 140     static final int PNG_COLOR_GRAY_ALPHA = 4;
 141     static final int PNG_COLOR_RGB_ALPHA = 6;
 142 
 143     // The number of bands by PNG color type
 144     static final int[] inputBandsForColorType = {
 145          1, // gray
 146         -1, // unused
 147          3, // rgb
 148          1, // palette
 149          2, // gray + alpha
 150         -1, // unused
 151          4  // rgb + alpha
 152     };
 153 
 154     static final int PNG_FILTER_NONE = 0;
 155     static final int PNG_FILTER_SUB = 1;
 156     static final int PNG_FILTER_UP = 2;
 157     static final int PNG_FILTER_AVERAGE = 3;
 158     static final int PNG_FILTER_PAETH = 4;
 159 
 160     static final int[] adam7XOffset = { 0, 4, 0, 2, 0, 1, 0 };
 161     static final int[] adam7YOffset = { 0, 0, 4, 0, 2, 0, 1 };
 162     static final int[] adam7XSubsampling = { 8, 8, 4, 4, 2, 2, 1, 1 };
 163     static final int[] adam7YSubsampling = { 8, 8, 8, 4, 4, 2, 2, 1 };
 164 
 165     private static final boolean debug = true;
 166 
 167     ImageInputStream stream = null;
 168 
 169     boolean gotHeader = false;
 170     boolean gotMetadata = false;
 171 
 172     ImageReadParam lastParam = null;
 173 
 174     long imageStartPosition = -1L;
 175 
 176     Rectangle sourceRegion = null;
 177     int sourceXSubsampling = -1;
 178     int sourceYSubsampling = -1;
 179     int sourceMinProgressivePass = 0;
 180     int sourceMaxProgressivePass = 6;
 181     int[] sourceBands = null;
 182     int[] destinationBands = null;
 183     Point destinationOffset = new Point(0, 0);
 184 
 185     PNGMetadata metadata = new PNGMetadata();
 186 
 187     DataInputStream pixelStream = null;
 188 
 189     BufferedImage theImage = null;
 190 
 191     // The number of source pixels processed
 192     int pixelsDone = 0;
 193 
 194     // The total number of pixels in the source image
 195     int totalPixels;
 196 
 197     public PNGImageReader(ImageReaderSpi originatingProvider) {
 198         super(originatingProvider);
 199     }
 200 
 201     public void setInput(Object input,
 202                          boolean seekForwardOnly,
 203                          boolean ignoreMetadata) {
 204         super.setInput(input, seekForwardOnly, ignoreMetadata);
 205         this.stream = (ImageInputStream)input; // Always works
 206 
 207         // Clear all values based on the previous stream contents
 208         resetStreamSettings();
 209     }
 210 
 211     private String readNullTerminatedString(String charset, int maxLen) throws IOException {
 212         ByteArrayOutputStream baos = new ByteArrayOutputStream();
 213         int b;
 214         int count = 0;
 215         while ((maxLen > count++) && ((b = stream.read()) != 0)) {
 216             if (b == -1) throw new EOFException();
 217             baos.write(b);
 218         }
 219         return new String(baos.toByteArray(), charset);
 220     }
 221 
 222     private void readHeader() throws IIOException {
 223         if (gotHeader) {
 224             return;
 225         }
 226         if (stream == null) {
 227             throw new IllegalStateException("Input source not set!");
 228         }
 229 
 230         try {
 231             byte[] signature = new byte[8];
 232             stream.readFully(signature);
 233 
 234             if (signature[0] != (byte)137 ||
 235                 signature[1] != (byte)80 ||
 236                 signature[2] != (byte)78 ||
 237                 signature[3] != (byte)71 ||
 238                 signature[4] != (byte)13 ||
 239                 signature[5] != (byte)10 ||
 240                 signature[6] != (byte)26 ||
 241                 signature[7] != (byte)10) {
 242                 throw new IIOException("Bad PNG signature!");
 243             }
 244 
 245             int IHDR_length = stream.readInt();
 246             if (IHDR_length != 13) {
 247                 throw new IIOException("Bad length for IHDR chunk!");
 248             }
 249             int IHDR_type = stream.readInt();
 250             if (IHDR_type != IHDR_TYPE) {
 251                 throw new IIOException("Bad type for IHDR chunk!");
 252             }
 253 
 254             this.metadata = new PNGMetadata();
 255 
 256             int width = stream.readInt();
 257             int height = stream.readInt();
 258 
 259             // Re-use signature array to bulk-read these unsigned byte values
 260             stream.readFully(signature, 0, 5);
 261             int bitDepth          = signature[0] & 0xff;
 262             int colorType         = signature[1] & 0xff;
 263             int compressionMethod = signature[2] & 0xff;
 264             int filterMethod      = signature[3] & 0xff;
 265             int interlaceMethod   = signature[4] & 0xff;
 266 
 267             // Skip IHDR CRC
 268             stream.skipBytes(4);
 269 
 270             stream.flushBefore(stream.getStreamPosition());
 271 
 272             if (width <= 0) {
 273                 throw new IIOException("Image width <= 0!");
 274             }
 275             if (height <= 0) {
 276                 throw new IIOException("Image height <= 0!");
 277             }
 278             if (bitDepth != 1 && bitDepth != 2 && bitDepth != 4 &&
 279                 bitDepth != 8 && bitDepth != 16) {
 280                 throw new IIOException("Bit depth must be 1, 2, 4, 8, or 16!");
 281             }
 282             if (colorType != 0 && colorType != 2 && colorType != 3 &&
 283                 colorType != 4 && colorType != 6) {
 284                 throw new IIOException("Color type must be 0, 2, 3, 4, or 6!");
 285             }
 286             if (colorType == PNG_COLOR_PALETTE && bitDepth == 16) {
 287                 throw new IIOException("Bad color type/bit depth combination!");
 288             }
 289             if ((colorType == PNG_COLOR_RGB ||
 290                  colorType == PNG_COLOR_RGB_ALPHA ||
 291                  colorType == PNG_COLOR_GRAY_ALPHA) &&
 292                 (bitDepth != 8 && bitDepth != 16)) {
 293                 throw new IIOException("Bad color type/bit depth combination!");
 294             }
 295             if (compressionMethod != 0) {
 296                 throw new IIOException("Unknown compression method (not 0)!");
 297             }
 298             if (filterMethod != 0) {
 299                 throw new IIOException("Unknown filter method (not 0)!");
 300             }
 301             if (interlaceMethod != 0 && interlaceMethod != 1) {
 302                 throw new IIOException("Unknown interlace method (not 0 or 1)!");
 303             }
 304 
 305             metadata.IHDR_present = true;
 306             metadata.IHDR_width = width;
 307             metadata.IHDR_height = height;
 308             metadata.IHDR_bitDepth = bitDepth;
 309             metadata.IHDR_colorType = colorType;
 310             metadata.IHDR_compressionMethod = compressionMethod;
 311             metadata.IHDR_filterMethod = filterMethod;
 312             metadata.IHDR_interlaceMethod = interlaceMethod;
 313             gotHeader = true;
 314         } catch (IOException e) {
 315             throw new IIOException("I/O error reading PNG header!", e);
 316         }
 317     }
 318 
 319     private void parse_PLTE_chunk(int chunkLength) throws IOException {
 320         if (metadata.PLTE_present) {
 321             processWarningOccurred(
 322 "A PNG image may not contain more than one PLTE chunk.\n" +
 323 "The chunk wil be ignored.");
 324             return;
 325         } else if (metadata.IHDR_colorType == PNG_COLOR_GRAY ||
 326                    metadata.IHDR_colorType == PNG_COLOR_GRAY_ALPHA) {
 327             processWarningOccurred(
 328 "A PNG gray or gray alpha image cannot have a PLTE chunk.\n" +
 329 "The chunk wil be ignored.");
 330             return;
 331         }
 332 
 333         byte[] palette = new byte[chunkLength];
 334         stream.readFully(palette);
 335 
 336         int numEntries = chunkLength/3;
 337         if (metadata.IHDR_colorType == PNG_COLOR_PALETTE) {
 338             int maxEntries = 1 << metadata.IHDR_bitDepth;
 339             if (numEntries > maxEntries) {
 340                 processWarningOccurred(
 341 "PLTE chunk contains too many entries for bit depth, ignoring extras.");
 342                 numEntries = maxEntries;
 343             }
 344             numEntries = Math.min(numEntries, maxEntries);
 345         }
 346 
 347         // Round array sizes up to 2^2^n
 348         int paletteEntries;
 349         if (numEntries > 16) {
 350             paletteEntries = 256;
 351         } else if (numEntries > 4) {
 352             paletteEntries = 16;
 353         } else if (numEntries > 2) {
 354             paletteEntries = 4;
 355         } else {
 356             paletteEntries = 2;
 357         }
 358 
 359         metadata.PLTE_present = true;
 360         metadata.PLTE_red = new byte[paletteEntries];
 361         metadata.PLTE_green = new byte[paletteEntries];
 362         metadata.PLTE_blue = new byte[paletteEntries];
 363 
 364         int index = 0;
 365         for (int i = 0; i < numEntries; i++) {
 366             metadata.PLTE_red[i] = palette[index++];
 367             metadata.PLTE_green[i] = palette[index++];
 368             metadata.PLTE_blue[i] = palette[index++];
 369         }
 370     }
 371 
 372     private void parse_bKGD_chunk() throws IOException {
 373         if (metadata.IHDR_colorType == PNG_COLOR_PALETTE) {
 374             metadata.bKGD_colorType = PNG_COLOR_PALETTE;
 375             metadata.bKGD_index = stream.readUnsignedByte();
 376         } else if (metadata.IHDR_colorType == PNG_COLOR_GRAY ||
 377                    metadata.IHDR_colorType == PNG_COLOR_GRAY_ALPHA) {
 378             metadata.bKGD_colorType = PNG_COLOR_GRAY;
 379             metadata.bKGD_gray = stream.readUnsignedShort();
 380         } else { // RGB or RGB_ALPHA
 381             metadata.bKGD_colorType = PNG_COLOR_RGB;
 382             metadata.bKGD_red = stream.readUnsignedShort();
 383             metadata.bKGD_green = stream.readUnsignedShort();
 384             metadata.bKGD_blue = stream.readUnsignedShort();
 385         }
 386 
 387         metadata.bKGD_present = true;
 388     }
 389 
 390     private void parse_cHRM_chunk() throws IOException {
 391         metadata.cHRM_whitePointX = stream.readInt();
 392         metadata.cHRM_whitePointY = stream.readInt();
 393         metadata.cHRM_redX = stream.readInt();
 394         metadata.cHRM_redY = stream.readInt();
 395         metadata.cHRM_greenX = stream.readInt();
 396         metadata.cHRM_greenY = stream.readInt();
 397         metadata.cHRM_blueX = stream.readInt();
 398         metadata.cHRM_blueY = stream.readInt();
 399 
 400         metadata.cHRM_present = true;
 401     }
 402 
 403     private void parse_gAMA_chunk() throws IOException {
 404         int gamma = stream.readInt();
 405         metadata.gAMA_gamma = gamma;
 406 
 407         metadata.gAMA_present = true;
 408     }
 409 
 410     private void parse_hIST_chunk(int chunkLength) throws IOException,
 411         IIOException
 412     {
 413         if (!metadata.PLTE_present) {
 414             throw new IIOException("hIST chunk without prior PLTE chunk!");
 415         }
 416 
 417         /* According to PNG specification length of
 418          * hIST chunk is specified in bytes and
 419          * hIST chunk consists of 2 byte elements
 420          * (so we expect length is even).
 421          */
 422         metadata.hIST_histogram = new char[chunkLength/2];
 423         stream.readFully(metadata.hIST_histogram,
 424                          0, metadata.hIST_histogram.length);
 425 
 426         metadata.hIST_present = true;
 427     }
 428 
 429     private void parse_iCCP_chunk(int chunkLength) throws IOException {
 430         String keyword = readNullTerminatedString("ISO-8859-1", 80);
 431         metadata.iCCP_profileName = keyword;
 432 
 433         metadata.iCCP_compressionMethod = stream.readUnsignedByte();
 434 
 435         byte[] compressedProfile =
 436           new byte[chunkLength - keyword.length() - 2];
 437         stream.readFully(compressedProfile);
 438         metadata.iCCP_compressedProfile = compressedProfile;
 439 
 440         metadata.iCCP_present = true;
 441     }
 442 
 443     private void parse_iTXt_chunk(int chunkLength) throws IOException {
 444         long chunkStart = stream.getStreamPosition();
 445 
 446         String keyword = readNullTerminatedString("ISO-8859-1", 80);
 447         metadata.iTXt_keyword.add(keyword);
 448 
 449         int compressionFlag = stream.readUnsignedByte();
 450         metadata.iTXt_compressionFlag.add(Boolean.valueOf(compressionFlag == 1));
 451 
 452         int compressionMethod = stream.readUnsignedByte();
 453         metadata.iTXt_compressionMethod.add(Integer.valueOf(compressionMethod));
 454 
 455         String languageTag = readNullTerminatedString("UTF8", 80);
 456         metadata.iTXt_languageTag.add(languageTag);
 457 
 458         long pos = stream.getStreamPosition();
 459         int maxLen = (int)(chunkStart + chunkLength - pos);
 460         String translatedKeyword =
 461             readNullTerminatedString("UTF8", maxLen);
 462         metadata.iTXt_translatedKeyword.add(translatedKeyword);
 463 
 464         String text;
 465         pos = stream.getStreamPosition();
 466         byte[] b = new byte[(int)(chunkStart + chunkLength - pos)];
 467         stream.readFully(b);
 468 
 469         if (compressionFlag == 1) { // Decompress the text
 470             text = new String(inflate(b), "UTF8");
 471         } else {
 472             text = new String(b, "UTF8");
 473         }
 474         metadata.iTXt_text.add(text);
 475 
 476         // Check if the text chunk contains image creation time
 477         if (keyword.equals(PNGMetadata.tEXt_creationTimeKey)) {
 478             // Update Standard/Document/ImageCreationTime from text chunk
 479             int index = metadata.iTXt_text.size() - 1;
 480             metadata.decodeImageCreationTimeFromTextChunk(
 481                     metadata.iTXt_text.listIterator(index));
 482         }
 483     }
 484 
 485     private void parse_pHYs_chunk() throws IOException {
 486         metadata.pHYs_pixelsPerUnitXAxis = stream.readInt();
 487         metadata.pHYs_pixelsPerUnitYAxis = stream.readInt();
 488         metadata.pHYs_unitSpecifier = stream.readUnsignedByte();
 489 
 490         metadata.pHYs_present = true;
 491     }
 492 
 493     private void parse_sBIT_chunk() throws IOException {
 494         int colorType = metadata.IHDR_colorType;
 495         if (colorType == PNG_COLOR_GRAY ||
 496             colorType == PNG_COLOR_GRAY_ALPHA) {
 497             metadata.sBIT_grayBits = stream.readUnsignedByte();
 498         } else if (colorType == PNG_COLOR_RGB ||
 499                    colorType == PNG_COLOR_PALETTE ||
 500                    colorType == PNG_COLOR_RGB_ALPHA) {
 501             metadata.sBIT_redBits = stream.readUnsignedByte();
 502             metadata.sBIT_greenBits = stream.readUnsignedByte();
 503             metadata.sBIT_blueBits = stream.readUnsignedByte();
 504         }
 505 
 506         if (colorType == PNG_COLOR_GRAY_ALPHA ||
 507             colorType == PNG_COLOR_RGB_ALPHA) {
 508             metadata.sBIT_alphaBits = stream.readUnsignedByte();
 509         }
 510 
 511         metadata.sBIT_colorType = colorType;
 512         metadata.sBIT_present = true;
 513     }
 514 
 515     private void parse_sPLT_chunk(int chunkLength)
 516         throws IOException, IIOException {
 517         metadata.sPLT_paletteName = readNullTerminatedString("ISO-8859-1", 80);
 518         chunkLength -= metadata.sPLT_paletteName.length() + 1;
 519 
 520         int sampleDepth = stream.readUnsignedByte();
 521         metadata.sPLT_sampleDepth = sampleDepth;
 522 
 523         int numEntries = chunkLength/(4*(sampleDepth/8) + 2);
 524         metadata.sPLT_red = new int[numEntries];
 525         metadata.sPLT_green = new int[numEntries];
 526         metadata.sPLT_blue = new int[numEntries];
 527         metadata.sPLT_alpha = new int[numEntries];
 528         metadata.sPLT_frequency = new int[numEntries];
 529 
 530         if (sampleDepth == 8) {
 531             for (int i = 0; i < numEntries; i++) {
 532                 metadata.sPLT_red[i] = stream.readUnsignedByte();
 533                 metadata.sPLT_green[i] = stream.readUnsignedByte();
 534                 metadata.sPLT_blue[i] = stream.readUnsignedByte();
 535                 metadata.sPLT_alpha[i] = stream.readUnsignedByte();
 536                 metadata.sPLT_frequency[i] = stream.readUnsignedShort();
 537             }
 538         } else if (sampleDepth == 16) {
 539             for (int i = 0; i < numEntries; i++) {
 540                 metadata.sPLT_red[i] = stream.readUnsignedShort();
 541                 metadata.sPLT_green[i] = stream.readUnsignedShort();
 542                 metadata.sPLT_blue[i] = stream.readUnsignedShort();
 543                 metadata.sPLT_alpha[i] = stream.readUnsignedShort();
 544                 metadata.sPLT_frequency[i] = stream.readUnsignedShort();
 545             }
 546         } else {
 547             throw new IIOException("sPLT sample depth not 8 or 16!");
 548         }
 549 
 550         metadata.sPLT_present = true;
 551     }
 552 
 553     private void parse_sRGB_chunk() throws IOException {
 554         metadata.sRGB_renderingIntent = stream.readUnsignedByte();
 555 
 556         metadata.sRGB_present = true;
 557     }
 558 
 559     private void parse_tEXt_chunk(int chunkLength) throws IOException {
 560         String keyword = readNullTerminatedString("ISO-8859-1", 80);
 561         metadata.tEXt_keyword.add(keyword);
 562 
 563         byte[] b = new byte[chunkLength - keyword.length() - 1];
 564         stream.readFully(b);
 565         metadata.tEXt_text.add(new String(b, "ISO-8859-1"));
 566 
 567         // Check if the text chunk contains image creation time
 568         if (keyword.equals(PNGMetadata.tEXt_creationTimeKey)) {
 569             // Update Standard/Document/ImageCreationTime from text chunk
 570             int index = metadata.tEXt_text.size() - 1;
 571             metadata.decodeImageCreationTimeFromTextChunk(
 572                     metadata.tEXt_text.listIterator(index));
 573         }
 574     }
 575 
 576     private void parse_tIME_chunk() throws IOException {
 577         metadata.tIME_year = stream.readUnsignedShort();
 578         metadata.tIME_month = stream.readUnsignedByte();
 579         metadata.tIME_day = stream.readUnsignedByte();
 580         metadata.tIME_hour = stream.readUnsignedByte();
 581         metadata.tIME_minute = stream.readUnsignedByte();
 582         metadata.tIME_second = stream.readUnsignedByte();
 583 
 584         metadata.tIME_present = true;
 585     }
 586 
 587     private void parse_tRNS_chunk(int chunkLength) throws IOException {
 588         int colorType = metadata.IHDR_colorType;
 589         if (colorType == PNG_COLOR_PALETTE) {
 590             if (!metadata.PLTE_present) {
 591                 processWarningOccurred(
 592 "tRNS chunk without prior PLTE chunk, ignoring it.");
 593                 return;
 594             }
 595 
 596             // Alpha table may have fewer entries than RGB palette
 597             int maxEntries = metadata.PLTE_red.length;
 598             int numEntries = chunkLength;
 599             if (numEntries > maxEntries) {
 600                 processWarningOccurred(
 601 "tRNS chunk has more entries than prior PLTE chunk, ignoring extras.");
 602                 numEntries = maxEntries;
 603             }
 604             metadata.tRNS_alpha = new byte[numEntries];
 605             metadata.tRNS_colorType = PNG_COLOR_PALETTE;
 606             stream.read(metadata.tRNS_alpha, 0, numEntries);
 607             stream.skipBytes(chunkLength - numEntries);
 608         } else if (colorType == PNG_COLOR_GRAY) {
 609             if (chunkLength != 2) {
 610                 processWarningOccurred(
 611 "tRNS chunk for gray image must have length 2, ignoring chunk.");
 612                 stream.skipBytes(chunkLength);
 613                 return;
 614             }
 615             metadata.tRNS_gray = stream.readUnsignedShort();
 616             metadata.tRNS_colorType = PNG_COLOR_GRAY;
 617         } else if (colorType == PNG_COLOR_RGB) {
 618             if (chunkLength != 6) {
 619                 processWarningOccurred(
 620 "tRNS chunk for RGB image must have length 6, ignoring chunk.");
 621                 stream.skipBytes(chunkLength);
 622                 return;
 623             }
 624             metadata.tRNS_red = stream.readUnsignedShort();
 625             metadata.tRNS_green = stream.readUnsignedShort();
 626             metadata.tRNS_blue = stream.readUnsignedShort();
 627             metadata.tRNS_colorType = PNG_COLOR_RGB;
 628         } else {
 629             processWarningOccurred(
 630 "Gray+Alpha and RGBS images may not have a tRNS chunk, ignoring it.");
 631             return;
 632         }
 633 
 634         metadata.tRNS_present = true;
 635     }
 636 
 637     private static byte[] inflate(byte[] b) throws IOException {
 638         InputStream bais = new ByteArrayInputStream(b);
 639         InputStream iis = new InflaterInputStream(bais);
 640         ByteArrayOutputStream baos = new ByteArrayOutputStream();
 641 
 642         int c;
 643         try {
 644             while ((c = iis.read()) != -1) {
 645                 baos.write(c);
 646             }
 647         } finally {
 648             iis.close();
 649         }
 650         return baos.toByteArray();
 651     }
 652 
 653     private void parse_zTXt_chunk(int chunkLength) throws IOException {
 654         String keyword = readNullTerminatedString("ISO-8859-1", 80);
 655         metadata.zTXt_keyword.add(keyword);
 656 
 657         int method = stream.readUnsignedByte();
 658         metadata.zTXt_compressionMethod.add(method);
 659 
 660         byte[] b = new byte[chunkLength - keyword.length() - 2];
 661         stream.readFully(b);
 662         metadata.zTXt_text.add(new String(inflate(b), "ISO-8859-1"));
 663 
 664         // Check if the text chunk contains image creation time
 665         if (keyword.equals(PNGMetadata.tEXt_creationTimeKey)) {
 666             // Update Standard/Document/ImageCreationTime from text chunk
 667             int index = metadata.zTXt_text.size() - 1;
 668             metadata.decodeImageCreationTimeFromTextChunk(
 669                     metadata.zTXt_text.listIterator(index));
 670         }
 671     }
 672 
 673     private void readMetadata() throws IIOException {
 674         if (gotMetadata) {
 675             return;
 676         }
 677 
 678         readHeader();
 679 
 680         /*
 681          * Optimization: We can skip the remaining metadata if the
 682          * ignoreMetadata flag is set, and only if this is not a palette
 683          * image (in that case, we need to read the metadata to get the
 684          * tRNS chunk, which is needed for the getImageTypes() method).
 685          */
 686         int colorType = metadata.IHDR_colorType;
 687         if (ignoreMetadata && colorType != PNG_COLOR_PALETTE) {
 688             try {
 689                 while (true) {
 690                     int chunkLength = stream.readInt();
 691 
 692                     // verify the chunk length first
 693                     if (chunkLength < 0 || chunkLength + 4 < 0) {
 694                         throw new IIOException("Invalid chunk length " + chunkLength);
 695                     }
 696 
 697                     int chunkType = stream.readInt();
 698 
 699                     if (chunkType == IDAT_TYPE) {
 700                         // We've reached the image data
 701                         stream.skipBytes(-8);
 702                         imageStartPosition = stream.getStreamPosition();
 703                         break;
 704                     } else {
 705                         // Skip the chunk plus the 4 CRC bytes that follow
 706                         stream.skipBytes(chunkLength + 4);
 707                     }
 708                 }
 709             } catch (IOException e) {
 710                 throw new IIOException("Error skipping PNG metadata", e);
 711             }
 712 
 713             gotMetadata = true;
 714             return;
 715         }
 716 
 717         try {
 718             loop: while (true) {
 719                 int chunkLength = stream.readInt();
 720                 int chunkType = stream.readInt();
 721                 int chunkCRC;
 722 
 723                 // verify the chunk length
 724                 if (chunkLength < 0) {
 725                     throw new IIOException("Invalid chunk length " + chunkLength);
 726                 };
 727 
 728                 try {
 729                     stream.mark();
 730                     stream.seek(stream.getStreamPosition() + chunkLength);
 731                     chunkCRC = stream.readInt();
 732                     stream.reset();
 733                 } catch (IOException e) {
 734                     throw new IIOException("Invalid chunk length " + chunkLength);
 735                 }
 736 
 737                 switch (chunkType) {
 738                 case IDAT_TYPE:
 739                     // If chunk type is 'IDAT', we've reached the image data.
 740                     if (imageStartPosition == -1L) {
 741                         /*
 742                          * The PNG specification mandates that if colorType is
 743                          * PNG_COLOR_PALETTE then the PLTE chunk should appear
 744                          * before the first IDAT chunk.
 745                          */
 746                         if (colorType == PNG_COLOR_PALETTE &&
 747                             !(metadata.PLTE_present))
 748                         {
 749                             throw new IIOException("Required PLTE chunk"
 750                                     + " missing");
 751                         }
 752                         /*
 753                          * PNGs may contain multiple IDAT chunks containing
 754                          * a portion of image data. We store the position of
 755                          * the first IDAT chunk and continue with iteration
 756                          * of other chunks that follow image data.
 757                          */
 758                         imageStartPosition = stream.getStreamPosition() - 8;
 759                     }
 760                     // Move to the CRC byte location.
 761                     stream.skipBytes(chunkLength);
 762                     break;
 763                 case IEND_TYPE:
 764                     /*
 765                      * If the chunk type is 'IEND', we've reached end of image.
 766                      * Seek to the first IDAT chunk for subsequent decoding.
 767                      */
 768                     stream.seek(imageStartPosition);
 769 
 770                     /*
 771                      * flushBefore discards the portion of the stream before
 772                      * the indicated position. Hence this should be used after
 773                      * we complete iteration over available chunks including
 774                      * those that appear after the IDAT.
 775                      */
 776                     stream.flushBefore(stream.getStreamPosition());
 777                     break loop;
 778                 case PLTE_TYPE:
 779                     parse_PLTE_chunk(chunkLength);
 780                     break;
 781                 case bKGD_TYPE:
 782                     parse_bKGD_chunk();
 783                     break;
 784                 case cHRM_TYPE:
 785                     parse_cHRM_chunk();
 786                     break;
 787                 case gAMA_TYPE:
 788                     parse_gAMA_chunk();
 789                     break;
 790                 case hIST_TYPE:
 791                     parse_hIST_chunk(chunkLength);
 792                     break;
 793                 case iCCP_TYPE:
 794                     parse_iCCP_chunk(chunkLength);
 795                     break;
 796                 case iTXt_TYPE:
 797                     if (ignoreMetadata) {
 798                         stream.skipBytes(chunkLength);
 799                     } else {
 800                         parse_iTXt_chunk(chunkLength);
 801                     }
 802                     break;
 803                 case pHYs_TYPE:
 804                     parse_pHYs_chunk();
 805                     break;
 806                 case sBIT_TYPE:
 807                     parse_sBIT_chunk();
 808                     break;
 809                 case sPLT_TYPE:
 810                     parse_sPLT_chunk(chunkLength);
 811                     break;
 812                 case sRGB_TYPE:
 813                     parse_sRGB_chunk();
 814                     break;
 815                 case tEXt_TYPE:
 816                     parse_tEXt_chunk(chunkLength);
 817                     break;
 818                 case tIME_TYPE:
 819                     parse_tIME_chunk();
 820                     break;
 821                 case tRNS_TYPE:
 822                     parse_tRNS_chunk(chunkLength);
 823                     break;
 824                 case zTXt_TYPE:
 825                     if (ignoreMetadata) {
 826                         stream.skipBytes(chunkLength);
 827                     } else {
 828                         parse_zTXt_chunk(chunkLength);
 829                     }
 830                     break;
 831                 default:
 832                     // Read an unknown chunk
 833                     byte[] b = new byte[chunkLength];
 834                     stream.readFully(b);
 835 
 836                     StringBuilder chunkName = new StringBuilder(4);
 837                     chunkName.append((char)(chunkType >>> 24));
 838                     chunkName.append((char)((chunkType >> 16) & 0xff));
 839                     chunkName.append((char)((chunkType >> 8) & 0xff));
 840                     chunkName.append((char)(chunkType & 0xff));
 841 
 842                     int ancillaryBit = chunkType >>> 28;
 843                     if (ancillaryBit == 0) {
 844                         processWarningOccurred(
 845 "Encountered unknown chunk with critical bit set!");
 846                     }
 847 
 848                     metadata.unknownChunkType.add(chunkName.toString());
 849                     metadata.unknownChunkData.add(b);
 850                     break;
 851                 }
 852 
 853                 // double check whether all chunk data were consumed
 854                 if (chunkCRC != stream.readInt()) {
 855                     throw new IIOException("Failed to read a chunk of type " +
 856                             chunkType);
 857                 }
 858             }
 859         } catch (IOException e) {
 860             throw new IIOException("Error reading PNG metadata", e);
 861         }
 862 
 863         gotMetadata = true;
 864     }
 865 
 866     // Data filtering methods
 867 
 868     private static void decodeSubFilter(byte[] curr, int coff, int count,
 869                                         int bpp) {
 870         for (int i = bpp; i < count; i++) {
 871             int val;
 872 
 873             val = curr[i + coff] & 0xff;
 874             val += curr[i + coff - bpp] & 0xff;
 875 
 876             curr[i + coff] = (byte)val;
 877         }
 878     }
 879 
 880     private static void decodeUpFilter(byte[] curr, int coff,
 881                                        byte[] prev, int poff,
 882                                        int count) {
 883         for (int i = 0; i < count; i++) {
 884             int raw = curr[i + coff] & 0xff;
 885             int prior = prev[i + poff] & 0xff;
 886 
 887             curr[i + coff] = (byte)(raw + prior);
 888         }
 889     }
 890 
 891     private static void decodeAverageFilter(byte[] curr, int coff,
 892                                             byte[] prev, int poff,
 893                                             int count, int bpp) {
 894         int raw, priorPixel, priorRow;
 895 
 896         for (int i = 0; i < bpp; i++) {
 897             raw = curr[i + coff] & 0xff;
 898             priorRow = prev[i + poff] & 0xff;
 899 
 900             curr[i + coff] = (byte)(raw + priorRow/2);
 901         }
 902 
 903         for (int i = bpp; i < count; i++) {
 904             raw = curr[i + coff] & 0xff;
 905             priorPixel = curr[i + coff - bpp] & 0xff;
 906             priorRow = prev[i + poff] & 0xff;
 907 
 908             curr[i + coff] = (byte)(raw + (priorPixel + priorRow)/2);
 909         }
 910     }
 911 
 912     private static int paethPredictor(int a, int b, int c) {
 913         int p = a + b - c;
 914         int pa = Math.abs(p - a);
 915         int pb = Math.abs(p - b);
 916         int pc = Math.abs(p - c);
 917 
 918         if ((pa <= pb) && (pa <= pc)) {
 919             return a;
 920         } else if (pb <= pc) {
 921             return b;
 922         } else {
 923             return c;
 924         }
 925     }
 926 
 927     private static void decodePaethFilter(byte[] curr, int coff,
 928                                           byte[] prev, int poff,
 929                                           int count, int bpp) {
 930         int raw, priorPixel, priorRow, priorRowPixel;
 931 
 932         for (int i = 0; i < bpp; i++) {
 933             raw = curr[i + coff] & 0xff;
 934             priorRow = prev[i + poff] & 0xff;
 935 
 936             curr[i + coff] = (byte)(raw + priorRow);
 937         }
 938 
 939         for (int i = bpp; i < count; i++) {
 940             raw = curr[i + coff] & 0xff;
 941             priorPixel = curr[i + coff - bpp] & 0xff;
 942             priorRow = prev[i + poff] & 0xff;
 943             priorRowPixel = prev[i + poff - bpp] & 0xff;
 944 
 945             curr[i + coff] = (byte)(raw + paethPredictor(priorPixel,
 946                                                          priorRow,
 947                                                          priorRowPixel));
 948         }
 949     }
 950 
 951     private static final int[][] bandOffsets = {
 952         null,
 953         { 0 }, // G
 954         { 0, 1 }, // GA in GA order
 955         { 0, 1, 2 }, // RGB in RGB order
 956         { 0, 1, 2, 3 } // RGBA in RGBA order
 957     };
 958 
 959     private WritableRaster createRaster(int width, int height, int bands,
 960                                         int scanlineStride,
 961                                         int bitDepth) {
 962 
 963         DataBuffer dataBuffer;
 964         WritableRaster ras = null;
 965         Point origin = new Point(0, 0);
 966         if ((bitDepth < 8) && (bands == 1)) {
 967             dataBuffer = new DataBufferByte(height*scanlineStride);
 968             ras = Raster.createPackedRaster(dataBuffer,
 969                                             width, height,
 970                                             bitDepth,
 971                                             origin);
 972         } else if (bitDepth <= 8) {
 973             dataBuffer = new DataBufferByte(height*scanlineStride);
 974             ras = Raster.createInterleavedRaster(dataBuffer,
 975                                                  width, height,
 976                                                  scanlineStride,
 977                                                  bands,
 978                                                  bandOffsets[bands],
 979                                                  origin);
 980         } else {
 981             dataBuffer = new DataBufferUShort(height*scanlineStride);
 982             ras = Raster.createInterleavedRaster(dataBuffer,
 983                                                  width, height,
 984                                                  scanlineStride,
 985                                                  bands,
 986                                                  bandOffsets[bands],
 987                                                  origin);
 988         }
 989 
 990         return ras;
 991     }
 992 
 993     private void skipPass(int passWidth, int passHeight)
 994         throws IOException, IIOException  {
 995         if ((passWidth == 0) || (passHeight == 0)) {
 996             return;
 997         }
 998 
 999         int inputBands = inputBandsForColorType[metadata.IHDR_colorType];
1000         int bytesPerRow = (inputBands*passWidth*metadata.IHDR_bitDepth + 7)/8;
1001 
1002         // Read the image row-by-row
1003         for (int srcY = 0; srcY < passHeight; srcY++) {
1004             // Skip filter byte and the remaining row bytes
1005             pixelStream.skipBytes(1 + bytesPerRow);
1006         }
1007     }
1008 
1009     private void updateImageProgress(int newPixels) {
1010         pixelsDone += newPixels;
1011         processImageProgress(100.0F*pixelsDone/totalPixels);
1012     }
1013 
1014     private void decodePass(int passNum,
1015                             int xStart, int yStart,
1016                             int xStep, int yStep,
1017                             int passWidth, int passHeight) throws IOException {
1018 
1019         if ((passWidth == 0) || (passHeight == 0)) {
1020             return;
1021         }
1022 
1023         WritableRaster imRas = theImage.getWritableTile(0, 0);
1024         int dstMinX = imRas.getMinX();
1025         int dstMaxX = dstMinX + imRas.getWidth() - 1;
1026         int dstMinY = imRas.getMinY();
1027         int dstMaxY = dstMinY + imRas.getHeight() - 1;
1028 
1029         // Determine which pixels will be updated in this pass
1030         int[] vals =
1031           ReaderUtil.computeUpdatedPixels(sourceRegion,
1032                                           destinationOffset,
1033                                           dstMinX, dstMinY,
1034                                           dstMaxX, dstMaxY,
1035                                           sourceXSubsampling,
1036                                           sourceYSubsampling,
1037                                           xStart, yStart,
1038                                           passWidth, passHeight,
1039                                           xStep, yStep);
1040         int updateMinX = vals[0];
1041         int updateMinY = vals[1];
1042         int updateWidth = vals[2];
1043         int updateXStep = vals[4];
1044         int updateYStep = vals[5];
1045 
1046         int bitDepth = metadata.IHDR_bitDepth;
1047         int inputBands = inputBandsForColorType[metadata.IHDR_colorType];
1048         int bytesPerPixel = (bitDepth == 16) ? 2 : 1;
1049         bytesPerPixel *= inputBands;
1050 
1051         int bitsPerRow = Math.multiplyExact((inputBands * bitDepth), passWidth);
1052         int bytesPerRow = (bitsPerRow + 7) / 8;
1053         int eltsPerRow = (bitDepth == 16) ? bytesPerRow/2 : bytesPerRow;
1054 
1055         // If no pixels need updating, just skip the input data
1056         if (updateWidth == 0) {
1057             for (int srcY = 0; srcY < passHeight; srcY++) {
1058                 // Update count of pixels read
1059                 updateImageProgress(passWidth);
1060                 /*
1061                  * If read has been aborted, just return
1062                  * processReadAborted will be called later
1063                  */
1064                 if (abortRequested()) {
1065                     return;
1066                 }
1067                 // Skip filter byte and the remaining row bytes
1068                 pixelStream.skipBytes(1 + bytesPerRow);
1069             }
1070             return;
1071         }
1072 
1073         // Backwards map from destination pixels
1074         // (dstX = updateMinX + k*updateXStep)
1075         // to source pixels (sourceX), and then
1076         // to offset and skip in passRow (srcX and srcXStep)
1077         int sourceX =
1078             (updateMinX - destinationOffset.x)*sourceXSubsampling +
1079             sourceRegion.x;
1080         int srcX = (sourceX - xStart)/xStep;
1081 
1082         // Compute the step factor in the source
1083         int srcXStep = updateXStep*sourceXSubsampling/xStep;
1084 
1085         byte[] byteData = null;
1086         short[] shortData = null;
1087         byte[] curr = new byte[bytesPerRow];
1088         byte[] prior = new byte[bytesPerRow];
1089 
1090         // Create a 1-row tall Raster to hold the data
1091         WritableRaster passRow = createRaster(passWidth, 1, inputBands,
1092                                               eltsPerRow,
1093                                               bitDepth);
1094 
1095         // Create an array suitable for holding one pixel
1096         int[] ps = passRow.getPixel(0, 0, (int[])null);
1097 
1098         DataBuffer dataBuffer = passRow.getDataBuffer();
1099         int type = dataBuffer.getDataType();
1100         if (type == DataBuffer.TYPE_BYTE) {
1101             byteData = ((DataBufferByte)dataBuffer).getData();
1102         } else {
1103             shortData = ((DataBufferUShort)dataBuffer).getData();
1104         }
1105 
1106         processPassStarted(theImage,
1107                            passNum,
1108                            sourceMinProgressivePass,
1109                            sourceMaxProgressivePass,
1110                            updateMinX, updateMinY,
1111                            updateXStep, updateYStep,
1112                            destinationBands);
1113 
1114         // Handle source and destination bands
1115         if (sourceBands != null) {
1116             passRow = passRow.createWritableChild(0, 0,
1117                                                   passRow.getWidth(), 1,
1118                                                   0, 0,
1119                                                   sourceBands);
1120         }
1121         if (destinationBands != null) {
1122             imRas = imRas.createWritableChild(0, 0,
1123                                               imRas.getWidth(),
1124                                               imRas.getHeight(),
1125                                               0, 0,
1126                                               destinationBands);
1127         }
1128 
1129         // Determine if all of the relevant output bands have the
1130         // same bit depth as the source data
1131         boolean adjustBitDepths = false;
1132         int[] outputSampleSize = imRas.getSampleModel().getSampleSize();
1133         int numBands = outputSampleSize.length;
1134         for (int b = 0; b < numBands; b++) {
1135             if (outputSampleSize[b] != bitDepth) {
1136                 adjustBitDepths = true;
1137                 break;
1138             }
1139         }
1140 
1141         // If the bit depths differ, create a lookup table per band to perform
1142         // the conversion
1143         int[][] scale = null;
1144         if (adjustBitDepths) {
1145             int maxInSample = (1 << bitDepth) - 1;
1146             int halfMaxInSample = maxInSample/2;
1147             scale = new int[numBands][];
1148             for (int b = 0; b < numBands; b++) {
1149                 int maxOutSample = (1 << outputSampleSize[b]) - 1;
1150                 scale[b] = new int[maxInSample + 1];
1151                 for (int s = 0; s <= maxInSample; s++) {
1152                     scale[b][s] =
1153                         (s*maxOutSample + halfMaxInSample)/maxInSample;
1154                 }
1155             }
1156         }
1157 
1158         // Limit passRow to relevant area for the case where we
1159         // will can setRect to copy a contiguous span
1160         boolean useSetRect = srcXStep == 1 &&
1161             updateXStep == 1 &&
1162             !adjustBitDepths &&
1163             (imRas instanceof ByteInterleavedRaster);
1164 
1165         if (useSetRect) {
1166             passRow = passRow.createWritableChild(srcX, 0,
1167                                                   updateWidth, 1,
1168                                                   0, 0,
1169                                                   null);
1170         }
1171 
1172         // Decode the (sub)image row-by-row
1173         for (int srcY = 0; srcY < passHeight; srcY++) {
1174             // Update count of pixels read
1175             updateImageProgress(passWidth);
1176             /*
1177              * If read has been aborted, just return
1178              * processReadAborted will be called later
1179              */
1180             if (abortRequested()) {
1181                 return;
1182             }
1183             // Read the filter type byte and a row of data
1184             int filter = pixelStream.read();
1185             try {
1186                 // Swap curr and prior
1187                 byte[] tmp = prior;
1188                 prior = curr;
1189                 curr = tmp;
1190 
1191                 pixelStream.readFully(curr, 0, bytesPerRow);
1192             } catch (java.util.zip.ZipException ze) {
1193                 // TODO - throw a more meaningful exception
1194                 throw ze;
1195             }
1196 
1197             switch (filter) {
1198             case PNG_FILTER_NONE:
1199                 break;
1200             case PNG_FILTER_SUB:
1201                 decodeSubFilter(curr, 0, bytesPerRow, bytesPerPixel);
1202                 break;
1203             case PNG_FILTER_UP:
1204                 decodeUpFilter(curr, 0, prior, 0, bytesPerRow);
1205                 break;
1206             case PNG_FILTER_AVERAGE:
1207                 decodeAverageFilter(curr, 0, prior, 0, bytesPerRow,
1208                                     bytesPerPixel);
1209                 break;
1210             case PNG_FILTER_PAETH:
1211                 decodePaethFilter(curr, 0, prior, 0, bytesPerRow,
1212                                   bytesPerPixel);
1213                 break;
1214             default:
1215                 throw new IIOException("Unknown row filter type (= " +
1216                                        filter + ")!");
1217             }
1218 
1219             // Copy data into passRow byte by byte
1220             if (bitDepth < 16) {
1221                 System.arraycopy(curr, 0, byteData, 0, bytesPerRow);
1222             } else {
1223                 int idx = 0;
1224                 for (int j = 0; j < eltsPerRow; j++) {
1225                     shortData[j] =
1226                         (short)((curr[idx] << 8) | (curr[idx + 1] & 0xff));
1227                     idx += 2;
1228                 }
1229             }
1230 
1231             // True Y position in source
1232             int sourceY = srcY*yStep + yStart;
1233             if ((sourceY >= sourceRegion.y) &&
1234                 (sourceY < sourceRegion.y + sourceRegion.height) &&
1235                 (((sourceY - sourceRegion.y) %
1236                   sourceYSubsampling) == 0)) {
1237 
1238                 int dstY = destinationOffset.y +
1239                     (sourceY - sourceRegion.y)/sourceYSubsampling;
1240                 if (dstY < dstMinY) {
1241                     continue;
1242                 }
1243                 if (dstY > dstMaxY) {
1244                     break;
1245                 }
1246 
1247                 if (useSetRect) {
1248                     imRas.setRect(updateMinX, dstY, passRow);
1249                 } else {
1250                     int newSrcX = srcX;
1251 
1252                     for (int dstX = updateMinX;
1253                          dstX < updateMinX + updateWidth;
1254                          dstX += updateXStep) {
1255 
1256                         passRow.getPixel(newSrcX, 0, ps);
1257                         if (adjustBitDepths) {
1258                             for (int b = 0; b < numBands; b++) {
1259                                 ps[b] = scale[b][ps[b]];
1260                             }
1261                         }
1262                         imRas.setPixel(dstX, dstY, ps);
1263                         newSrcX += srcXStep;
1264                     }
1265                 }
1266 
1267                 processImageUpdate(theImage,
1268                                    updateMinX, dstY,
1269                                    updateWidth, 1,
1270                                    updateXStep, updateYStep,
1271                                    destinationBands);
1272             }
1273         }
1274 
1275         processPassComplete(theImage);
1276     }
1277 
1278     private void decodeImage()
1279         throws IOException, IIOException  {
1280         int width = metadata.IHDR_width;
1281         int height = metadata.IHDR_height;
1282 
1283         this.pixelsDone = 0;
1284         this.totalPixels = width*height;
1285 
1286         if (metadata.IHDR_interlaceMethod == 0) {
1287             decodePass(0, 0, 0, 1, 1, width, height);
1288         } else {
1289             for (int i = 0; i <= sourceMaxProgressivePass; i++) {
1290                 int XOffset = adam7XOffset[i];
1291                 int YOffset = adam7YOffset[i];
1292                 int XSubsampling = adam7XSubsampling[i];
1293                 int YSubsampling = adam7YSubsampling[i];
1294                 int xbump = adam7XSubsampling[i + 1] - 1;
1295                 int ybump = adam7YSubsampling[i + 1] - 1;
1296 
1297                 if (i >= sourceMinProgressivePass) {
1298                     decodePass(i,
1299                                XOffset,
1300                                YOffset,
1301                                XSubsampling,
1302                                YSubsampling,
1303                                (width + xbump)/XSubsampling,
1304                                (height + ybump)/YSubsampling);
1305                 } else {
1306                     skipPass((width + xbump)/XSubsampling,
1307                              (height + ybump)/YSubsampling);
1308                 }
1309 
1310                 /*
1311                  * If read has been aborted, just return
1312                  * processReadAborted will be called later
1313                  */
1314                 if (abortRequested()) {
1315                     return;
1316                 }
1317             }
1318         }
1319     }
1320 
1321     private void readImage(ImageReadParam param) throws IIOException {
1322         readMetadata();
1323 
1324         int width = metadata.IHDR_width;
1325         int height = metadata.IHDR_height;
1326 
1327         // Init default values
1328         sourceXSubsampling = 1;
1329         sourceYSubsampling = 1;
1330         sourceMinProgressivePass = 0;
1331         sourceMaxProgressivePass = 6;
1332         sourceBands = null;
1333         destinationBands = null;
1334         destinationOffset = new Point(0, 0);
1335 
1336         // If an ImageReadParam is available, get values from it
1337         if (param != null) {
1338             sourceXSubsampling = param.getSourceXSubsampling();
1339             sourceYSubsampling = param.getSourceYSubsampling();
1340 
1341             sourceMinProgressivePass =
1342                 Math.max(param.getSourceMinProgressivePass(), 0);
1343             sourceMaxProgressivePass =
1344                 Math.min(param.getSourceMaxProgressivePass(), 6);
1345 
1346             sourceBands = param.getSourceBands();
1347             destinationBands = param.getDestinationBands();
1348             destinationOffset = param.getDestinationOffset();
1349         }
1350         Inflater inf = null;
1351         try {
1352             stream.seek(imageStartPosition);
1353 
1354             Enumeration<InputStream> e = new PNGImageDataEnumeration(stream);
1355             InputStream is = new SequenceInputStream(e);
1356 
1357            /* InflaterInputStream uses an Inflater instance which consumes
1358             * native (non-GC visible) resources. This is normally implicitly
1359             * freed when the stream is closed. However since the
1360             * InflaterInputStream wraps a client-supplied input stream,
1361             * we cannot close it.
1362             * But the app may depend on GC finalization to close the stream.
1363             * Therefore to ensure timely freeing of native resources we
1364             * explicitly create the Inflater instance and free its resources
1365             * when we are done with the InflaterInputStream by calling
1366             * inf.end();
1367             */
1368             inf = new Inflater();
1369             is = new InflaterInputStream(is, inf);
1370             is = new BufferedInputStream(is);
1371             this.pixelStream = new DataInputStream(is);
1372 
1373             /*
1374              * PNG spec declares that valid range for width
1375              * and height is [1, 2^31-1], so here we may fail to allocate
1376              * a buffer for destination image due to memory limitation.
1377              *
1378              * If the read operation triggers OutOfMemoryError, the same
1379              * will be wrapped in an IIOException at PNGImageReader.read
1380              * method.
1381              *
1382              * The recovery strategy for this case should be defined at
1383              * the level of application, so we will not try to estimate
1384              * the required amount of the memory and/or handle OOM in
1385              * any way.
1386              */
1387             theImage = getDestination(param,
1388                                       getImageTypes(0),
1389                                       width,
1390                                       height);
1391 
1392             Rectangle destRegion = new Rectangle(0, 0, 0, 0);
1393             sourceRegion = new Rectangle(0, 0, 0, 0);
1394             computeRegions(param, width, height,
1395                            theImage,
1396                            sourceRegion, destRegion);
1397             destinationOffset.setLocation(destRegion.getLocation());
1398 
1399             // At this point the header has been read and we know
1400             // how many bands are in the image, so perform checking
1401             // of the read param.
1402             int colorType = metadata.IHDR_colorType;
1403             checkReadParamBandSettings(param,
1404                                        inputBandsForColorType[colorType],
1405                                       theImage.getSampleModel().getNumBands());
1406 
1407             clearAbortRequest();
1408             processImageStarted(0);
1409             if (abortRequested()) {
1410                 processReadAborted();
1411             } else {
1412                 decodeImage();
1413                 if (abortRequested()) {
1414                     processReadAborted();
1415                 } else {
1416                     processImageComplete();
1417                 }
1418             }
1419 
1420         } catch (IOException e) {
1421             throw new IIOException("Error reading PNG image data", e);
1422         } finally {
1423             if (inf != null) {
1424                 inf.end();
1425             }
1426         }
1427     }
1428 
1429     public int getNumImages(boolean allowSearch) throws IIOException {
1430         if (stream == null) {
1431             throw new IllegalStateException("No input source set!");
1432         }
1433         if (seekForwardOnly && allowSearch) {
1434             throw new IllegalStateException
1435                 ("seekForwardOnly and allowSearch can't both be true!");
1436         }
1437         return 1;
1438     }
1439 
1440     public int getWidth(int imageIndex) throws IIOException {
1441         if (imageIndex != 0) {
1442             throw new IndexOutOfBoundsException("imageIndex != 0!");
1443         }
1444 
1445         readHeader();
1446 
1447         return metadata.IHDR_width;
1448     }
1449 
1450     public int getHeight(int imageIndex) throws IIOException {
1451         if (imageIndex != 0) {
1452             throw new IndexOutOfBoundsException("imageIndex != 0!");
1453         }
1454 
1455         readHeader();
1456 
1457         return metadata.IHDR_height;
1458     }
1459 
1460     public Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex)
1461       throws IIOException
1462     {
1463         if (imageIndex != 0) {
1464             throw new IndexOutOfBoundsException("imageIndex != 0!");
1465         }
1466 
1467         readHeader();
1468 
1469         ArrayList<ImageTypeSpecifier> l =
1470             new ArrayList<ImageTypeSpecifier>(1);
1471 
1472         ColorSpace rgb;
1473         ColorSpace gray;
1474         int[] bandOffsets;
1475 
1476         int bitDepth = metadata.IHDR_bitDepth;
1477         int colorType = metadata.IHDR_colorType;
1478 
1479         int dataType;
1480         if (bitDepth <= 8) {
1481             dataType = DataBuffer.TYPE_BYTE;
1482         } else {
1483             dataType = DataBuffer.TYPE_USHORT;
1484         }
1485 
1486         switch (colorType) {
1487         case PNG_COLOR_GRAY:
1488             // Packed grayscale
1489             l.add(ImageTypeSpecifier.createGrayscale(bitDepth,
1490                                                      dataType,
1491                                                      false));
1492             break;
1493 
1494         case PNG_COLOR_RGB:
1495             if (bitDepth == 8) {
1496                 // some standard types of buffered images
1497                 // which can be used as destination
1498                 l.add(ImageTypeSpecifier.createFromBufferedImageType(
1499                           BufferedImage.TYPE_3BYTE_BGR));
1500 
1501                 l.add(ImageTypeSpecifier.createFromBufferedImageType(
1502                           BufferedImage.TYPE_INT_RGB));
1503 
1504                 l.add(ImageTypeSpecifier.createFromBufferedImageType(
1505                           BufferedImage.TYPE_INT_BGR));
1506 
1507             }
1508             // Component R, G, B
1509             rgb = ColorSpace.getInstance(ColorSpace.CS_sRGB);
1510             bandOffsets = new int[3];
1511             bandOffsets[0] = 0;
1512             bandOffsets[1] = 1;
1513             bandOffsets[2] = 2;
1514             l.add(ImageTypeSpecifier.createInterleaved(rgb,
1515                                                        bandOffsets,
1516                                                        dataType,
1517                                                        false,
1518                                                        false));
1519             break;
1520 
1521         case PNG_COLOR_PALETTE:
1522             readMetadata(); // Need tRNS chunk
1523 
1524             /*
1525              * The PLTE chunk spec says:
1526              *
1527              * The number of palette entries must not exceed the range that
1528              * can be represented in the image bit depth (for example, 2^4 = 16
1529              * for a bit depth of 4). It is permissible to have fewer entries
1530              * than the bit depth would allow. In that case, any out-of-range
1531              * pixel value found in the image data is an error.
1532              *
1533              * http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.PLTE
1534              *
1535              * Consequently, the case when the palette length is smaller than
1536              * 2^bitDepth is legal in the view of PNG spec.
1537              *
1538              * However the spec of createIndexed() method demands the exact
1539              * equality of the palette lengh and number of possible palette
1540              * entries (2^bitDepth).
1541              *
1542              * {@link javax.imageio.ImageTypeSpecifier.html#createIndexed}
1543              *
1544              * In order to avoid this contradiction we need to extend the
1545              * palette arrays to the limit defined by the bitDepth.
1546              */
1547 
1548             int plength = 1 << bitDepth;
1549 
1550             byte[] red = metadata.PLTE_red;
1551             byte[] green = metadata.PLTE_green;
1552             byte[] blue = metadata.PLTE_blue;
1553 
1554             if (metadata.PLTE_red.length < plength) {
1555                 red = Arrays.copyOf(metadata.PLTE_red, plength);
1556                 Arrays.fill(red, metadata.PLTE_red.length, plength,
1557                             metadata.PLTE_red[metadata.PLTE_red.length - 1]);
1558 
1559                 green = Arrays.copyOf(metadata.PLTE_green, plength);
1560                 Arrays.fill(green, metadata.PLTE_green.length, plength,
1561                             metadata.PLTE_green[metadata.PLTE_green.length - 1]);
1562 
1563                 blue = Arrays.copyOf(metadata.PLTE_blue, plength);
1564                 Arrays.fill(blue, metadata.PLTE_blue.length, plength,
1565                             metadata.PLTE_blue[metadata.PLTE_blue.length - 1]);
1566 
1567             }
1568 
1569             // Alpha from tRNS chunk may have fewer entries than
1570             // the RGB LUTs from the PLTE chunk; if so, pad with
1571             // 255.
1572             byte[] alpha = null;
1573             if (metadata.tRNS_present && (metadata.tRNS_alpha != null)) {
1574                 if (metadata.tRNS_alpha.length == red.length) {
1575                     alpha = metadata.tRNS_alpha;
1576                 } else {
1577                     alpha = Arrays.copyOf(metadata.tRNS_alpha, red.length);
1578                     Arrays.fill(alpha,
1579                                 metadata.tRNS_alpha.length,
1580                                 red.length, (byte)255);
1581                 }
1582             }
1583 
1584             l.add(ImageTypeSpecifier.createIndexed(red, green,
1585                                                    blue, alpha,
1586                                                    bitDepth,
1587                                                    DataBuffer.TYPE_BYTE));
1588             break;
1589 
1590         case PNG_COLOR_GRAY_ALPHA:
1591             // Component G, A
1592             gray = ColorSpace.getInstance(ColorSpace.CS_GRAY);
1593             bandOffsets = new int[2];
1594             bandOffsets[0] = 0;
1595             bandOffsets[1] = 1;
1596             l.add(ImageTypeSpecifier.createInterleaved(gray,
1597                                                        bandOffsets,
1598                                                        dataType,
1599                                                        true,
1600                                                        false));
1601             break;
1602 
1603         case PNG_COLOR_RGB_ALPHA:
1604             if (bitDepth == 8) {
1605                 // some standard types of buffered images
1606                 // wich can be used as destination
1607                 l.add(ImageTypeSpecifier.createFromBufferedImageType(
1608                           BufferedImage.TYPE_4BYTE_ABGR));
1609 
1610                 l.add(ImageTypeSpecifier.createFromBufferedImageType(
1611                           BufferedImage.TYPE_INT_ARGB));
1612             }
1613 
1614             // Component R, G, B, A (non-premultiplied)
1615             rgb = ColorSpace.getInstance(ColorSpace.CS_sRGB);
1616             bandOffsets = new int[4];
1617             bandOffsets[0] = 0;
1618             bandOffsets[1] = 1;
1619             bandOffsets[2] = 2;
1620             bandOffsets[3] = 3;
1621 
1622             l.add(ImageTypeSpecifier.createInterleaved(rgb,
1623                                                        bandOffsets,
1624                                                        dataType,
1625                                                        true,
1626                                                        false));
1627             break;
1628 
1629         default:
1630             break;
1631         }
1632 
1633         return l.iterator();
1634     }
1635 
1636     /*
1637      * Super class implementation uses first element
1638      * of image types list as raw image type.
1639      *
1640      * Also, super implementation uses first element of this list
1641      * as default destination type image read param does not specify
1642      * anything other.
1643      *
1644      * However, in case of RGB and RGBA color types, raw image type
1645      * produces buffered image of custom type. It causes some
1646      * performance degradation of subsequent rendering operations.
1647      *
1648      * To resolve this contradiction we put standard image types
1649      * at the first positions of image types list (to produce standard
1650      * images by default) and put raw image type (which is custom)
1651      * at the last position of this list.
1652      *
1653      * After this changes we should override getRawImageType()
1654      * to return last element of image types list.
1655      */
1656     public ImageTypeSpecifier getRawImageType(int imageIndex)
1657       throws IOException {
1658 
1659         Iterator<ImageTypeSpecifier> types = getImageTypes(imageIndex);
1660         ImageTypeSpecifier raw = null;
1661         do {
1662             raw = types.next();
1663         } while (types.hasNext());
1664         return raw;
1665     }
1666 
1667     public ImageReadParam getDefaultReadParam() {
1668         return new ImageReadParam();
1669     }
1670 
1671     public IIOMetadata getStreamMetadata()
1672         throws IIOException {
1673         return null;
1674     }
1675 
1676     public IIOMetadata getImageMetadata(int imageIndex) throws IIOException {
1677         if (imageIndex != 0) {
1678             throw new IndexOutOfBoundsException("imageIndex != 0!");
1679         }
1680         readMetadata();
1681         return metadata;
1682     }
1683 
1684     public BufferedImage read(int imageIndex, ImageReadParam param)
1685         throws IIOException {
1686         if (imageIndex != 0) {
1687             throw new IndexOutOfBoundsException("imageIndex != 0!");
1688         }
1689 
1690         try {
1691             readImage(param);
1692         } catch (IOException |
1693                  IllegalStateException |
1694                  IllegalArgumentException e)
1695         {
1696             throw e;
1697         } catch (Throwable e) {
1698             throw new IIOException("Caught exception during read: ", e);
1699         }
1700         return theImage;
1701     }
1702 
1703     public void reset() {
1704         super.reset();
1705         resetStreamSettings();
1706     }
1707 
1708     private void resetStreamSettings() {
1709         gotHeader = false;
1710         gotMetadata = false;
1711         metadata = null;
1712         pixelStream = null;
1713         imageStartPosition = -1L;
1714     }
1715 }
--- EOF ---