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