1 /*
   2  * Copyright (c) 2000, 2014, 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.jpeg;
  27 
  28 import javax.imageio.IIOException;
  29 import javax.imageio.ImageReader;
  30 import javax.imageio.ImageReadParam;
  31 import javax.imageio.ImageTypeSpecifier;
  32 import javax.imageio.metadata.IIOMetadata;
  33 import javax.imageio.spi.ImageReaderSpi;
  34 import javax.imageio.stream.ImageInputStream;
  35 import javax.imageio.plugins.jpeg.JPEGImageReadParam;
  36 import javax.imageio.plugins.jpeg.JPEGQTable;
  37 import javax.imageio.plugins.jpeg.JPEGHuffmanTable;
  38 
  39 import java.awt.Point;
  40 import java.awt.Rectangle;
  41 import java.awt.color.ColorSpace;
  42 import java.awt.color.ICC_Profile;
  43 import java.awt.color.ICC_ColorSpace;
  44 import java.awt.color.CMMException;
  45 import java.awt.image.BufferedImage;
  46 import java.awt.image.Raster;
  47 import java.awt.image.WritableRaster;
  48 import java.awt.image.DataBuffer;
  49 import java.awt.image.DataBufferByte;
  50 import java.awt.image.ColorModel;
  51 import java.awt.image.IndexColorModel;
  52 import java.awt.image.ColorConvertOp;
  53 import java.io.IOException;
  54 import java.util.List;
  55 import java.util.Iterator;
  56 import java.util.ArrayList;
  57 import java.util.NoSuchElementException;
  58 
  59 import sun.java2d.Disposer;
  60 import sun.java2d.DisposerRecord;
  61 
  62 public class JPEGImageReader extends ImageReader {
  63 
  64     private boolean debug = false;
  65 
  66     /**
  67      * The following variable contains a pointer to the IJG library
  68      * structure for this reader.  It is assigned in the constructor
  69      * and then is passed in to every native call.  It is set to 0
  70      * by dispose to avoid disposing twice.
  71      */
  72     private long structPointer = 0;
  73 
  74     /** The input stream we read from */
  75     private ImageInputStream iis = null;
  76 
  77     /**
  78      * List of stream positions for images, reinitialized every time
  79      * a new input source is set.
  80      */
  81     private List<Long> imagePositions = null;
  82 
  83     /**
  84      * The number of images in the stream, or 0.
  85      */
  86     private int numImages = 0;
  87 
  88     static {
  89         java.security.AccessController.doPrivileged(
  90             new java.security.PrivilegedAction<Void>() {
  91                 public Void run() {
  92                     System.loadLibrary("javajpeg");
  93                     return null;
  94                 }
  95             });
  96         initReaderIDs(ImageInputStream.class,
  97                       JPEGQTable.class,
  98                       JPEGHuffmanTable.class);
  99     }
 100 
 101     // The following warnings are converted to strings when used
 102     // as keys to get localized resources from JPEGImageReaderResources
 103     // and its children.
 104 
 105     /**
 106      * Warning code to be passed to warningOccurred to indicate
 107      * that the EOI marker is missing from the end of the stream.
 108      * This usually signals that the stream is corrupted, but
 109      * everything up to the last MCU should be usable.
 110      */
 111     protected static final int WARNING_NO_EOI = 0;
 112 
 113     /**
 114      * Warning code to be passed to warningOccurred to indicate
 115      * that a JFIF segment was encountered inside a JFXX JPEG
 116      * thumbnail and is being ignored.
 117      */
 118     protected static final int WARNING_NO_JFIF_IN_THUMB = 1;
 119 
 120     /**
 121      * Warning code to be passed to warningOccurred to indicate
 122      * that embedded ICC profile is invalid and will be ignored.
 123      */
 124     protected static final int WARNING_IGNORE_INVALID_ICC = 2;
 125 
 126     private static final int MAX_WARNING = WARNING_IGNORE_INVALID_ICC;
 127 
 128     /**
 129      * Image index of image for which header information
 130      * is available.
 131      */
 132     private int currentImage = -1;
 133 
 134     // The following is copied out from C after reading the header.
 135     // Unlike metadata, which may never be retrieved, we need this
 136     // if we are to read an image at all.
 137 
 138     /** Set by setImageData native code callback */
 139     private int width;
 140     /** Set by setImageData native code callback */
 141     private int height;
 142     /**
 143      * Set by setImageData native code callback.  A modified
 144      * IJG+NIFTY colorspace code.
 145      */
 146     private int colorSpaceCode;
 147     /**
 148      * Set by setImageData native code callback.  A modified
 149      * IJG+NIFTY colorspace code.
 150      */
 151     private int outColorSpaceCode;
 152     /** Set by setImageData native code callback */
 153     private int numComponents;
 154     /** Set by setImageData native code callback */
 155     private ColorSpace iccCS = null;
 156 
 157 
 158     /** If we need to post-convert in Java, convert with this op */
 159     private ColorConvertOp convert = null;
 160 
 161     /** The image we are going to fill */
 162     private BufferedImage image = null;
 163 
 164     /** An intermediate Raster to hold decoded data */
 165     private WritableRaster raster = null;
 166 
 167     /** A view of our target Raster that we can setRect to */
 168     private WritableRaster target = null;
 169 
 170     /** The databuffer for the above Raster */
 171     private DataBufferByte buffer = null;
 172 
 173     /** The region in the destination where we will write pixels */
 174     private Rectangle destROI = null;
 175 
 176     /** The list of destination bands, if any */
 177     private int [] destinationBands = null;
 178 
 179     /** Stream metadata, cached, even when the stream is changed. */
 180     private JPEGMetadata streamMetadata = null;
 181 
 182     /** Image metadata, valid for the imageMetadataIndex only. */
 183     private JPEGMetadata imageMetadata = null;
 184     private int imageMetadataIndex = -1;
 185 
 186     /**
 187      * Set to true every time we seek in the stream; used to
 188      * invalidate the native buffer contents in C.
 189      */
 190     private boolean haveSeeked = false;
 191 
 192     /**
 193      * Tables that have been read from a tables-only image at the
 194      * beginning of a stream.
 195      */
 196     private JPEGQTable [] abbrevQTables = null;
 197     private JPEGHuffmanTable[] abbrevDCHuffmanTables = null;
 198     private JPEGHuffmanTable[] abbrevACHuffmanTables = null;
 199 
 200     private int minProgressivePass = 0;
 201     private int maxProgressivePass = Integer.MAX_VALUE;
 202 
 203     /**
 204      * Variables used by progress monitoring.
 205      */
 206     private static final int UNKNOWN = -1;  // Number of passes
 207     private static final int MIN_ESTIMATED_PASSES = 10; // IJG default
 208     private int knownPassCount = UNKNOWN;
 209     private int pass = 0;
 210     private float percentToDate = 0.0F;
 211     private float previousPassPercentage = 0.0F;
 212     private int progInterval = 0;
 213 
 214     /**
 215      * Set to true once stream has been checked for stream metadata
 216      */
 217     private boolean tablesOnlyChecked = false;
 218 
 219     /** The referent to be registered with the Disposer. */
 220     private Object disposerReferent = new Object();
 221 
 222     /** The DisposerRecord that handles the actual disposal of this reader. */
 223     private DisposerRecord disposerRecord;
 224 
 225     /** Sets up static C structures. */
 226     private static native void initReaderIDs(Class<?> iisClass,
 227                                              Class<?> qTableClass,
 228                                              Class<?> huffClass);
 229 
 230     public JPEGImageReader(ImageReaderSpi originator) {
 231         super(originator);
 232         structPointer = initJPEGImageReader();
 233         disposerRecord = new JPEGReaderDisposerRecord(structPointer);
 234         Disposer.addRecord(disposerReferent, disposerRecord);
 235     }
 236 
 237     /** Sets up per-reader C structure and returns a pointer to it. */
 238     private native long initJPEGImageReader();
 239 
 240     /**
 241      * Called by the native code or other classes to signal a warning.
 242      * The code is used to lookup a localized message to be used when
 243      * sending warnings to listeners.
 244      */
 245     protected void warningOccurred(int code) {
 246         cbLock.lock();
 247         try {
 248             if ((code < 0) || (code > MAX_WARNING)){
 249                 throw new InternalError("Invalid warning index");
 250             }
 251             processWarningOccurred
 252                 ("com.sun.imageio.plugins.jpeg.JPEGImageReaderResources",
 253                  Integer.toString(code));
 254         } finally {
 255             cbLock.unlock();
 256         }
 257     }
 258 
 259     /**
 260      * The library has it's own error facility that emits warning messages.
 261      * This routine is called by the native code when it has already
 262      * formatted a string for output.
 263      * XXX  For truly complete localization of all warning messages,
 264      * the sun_jpeg_output_message routine in the native code should
 265      * send only the codes and parameters to a method here in Java,
 266      * which will then format and send the warnings, using localized
 267      * strings.  This method will have to deal with all the parameters
 268      * and formats (%u with possibly large numbers, %02d, %02x, etc.)
 269      * that actually occur in the JPEG library.  For now, this prevents
 270      * library warnings from being printed to stderr.
 271      */
 272     protected void warningWithMessage(String msg) {
 273         cbLock.lock();
 274         try {
 275             processWarningOccurred(msg);
 276         } finally {
 277             cbLock.unlock();
 278         }
 279     }
 280 
 281     public void setInput(Object input,
 282                          boolean seekForwardOnly,
 283                          boolean ignoreMetadata)
 284     {
 285         setThreadLock();
 286         try {
 287             cbLock.check();
 288 
 289             super.setInput(input, seekForwardOnly, ignoreMetadata);
 290             this.ignoreMetadata = ignoreMetadata;
 291             resetInternalState();
 292             iis = (ImageInputStream) input; // Always works
 293             setSource(structPointer);
 294         } finally {
 295             clearThreadLock();
 296         }
 297     }
 298 
 299     /**
 300      * This method is called from native code in order to fill
 301      * native input buffer.
 302      *
 303      * We block any attempt to change the reading state during this
 304      * method, in order to prevent a corruption of the native decoder
 305      * state.
 306      *
 307      * @return number of bytes read from the stream.
 308      */
 309     private int readInputData(byte[] buf, int off, int len) throws IOException {
 310         cbLock.lock();
 311         try {
 312             return iis.read(buf, off, len);
 313         } finally {
 314             cbLock.unlock();
 315         }
 316     }
 317 
 318     /**
 319      * This method is called from the native code in order to
 320      * skip requested number of bytes in the input stream.
 321      *
 322      * @param n
 323      * @return
 324      * @throws IOException
 325      */
 326     private long skipInputBytes(long n) throws IOException {
 327         cbLock.lock();
 328         try {
 329             return iis.skipBytes(n);
 330         } finally {
 331             cbLock.unlock();
 332         }
 333     }
 334 
 335     private native void setSource(long structPointer);
 336 
 337     private void checkTablesOnly() throws IOException {
 338         if (debug) {
 339             System.out.println("Checking for tables-only image");
 340         }
 341         long savePos = iis.getStreamPosition();
 342         if (debug) {
 343             System.out.println("saved pos is " + savePos);
 344             System.out.println("length is " + iis.length());
 345         }
 346         // Read the first header
 347         boolean tablesOnly = readNativeHeader(true);
 348         if (tablesOnly) {
 349             if (debug) {
 350                 System.out.println("tables-only image found");
 351                 long pos = iis.getStreamPosition();
 352                 System.out.println("pos after return from native is " + pos);
 353             }
 354             // This reads the tables-only image twice, once from C
 355             // and once from Java, but only if ignoreMetadata is false
 356             if (ignoreMetadata == false) {
 357                 iis.seek(savePos);
 358                 haveSeeked = true;
 359                 streamMetadata = new JPEGMetadata(true, false,
 360                                                   iis, this);
 361                 long pos = iis.getStreamPosition();
 362                 if (debug) {
 363                     System.out.println
 364                         ("pos after constructing stream metadata is " + pos);
 365                 }
 366             }
 367             // Now we are at the first image if there are any, so add it
 368             // to the list
 369             if (hasNextImage()) {
 370                 imagePositions.add(iis.getStreamPosition());
 371             }
 372         } else { // Not tables only, so add original pos to the list
 373             imagePositions.add(savePos);
 374             // And set current image since we've read it now
 375             currentImage = 0;
 376         }
 377         if (seekForwardOnly) {
 378             Long pos = imagePositions.get(imagePositions.size()-1);
 379             iis.flushBefore(pos.longValue());
 380         }
 381         tablesOnlyChecked = true;
 382     }
 383 
 384     public int getNumImages(boolean allowSearch) throws IOException {
 385         setThreadLock();
 386         try { // locked thread
 387             cbLock.check();
 388 
 389             return getNumImagesOnThread(allowSearch);
 390         } finally {
 391             clearThreadLock();
 392         }
 393     }
 394 
 395     @SuppressWarnings("fallthrough")
 396     private int getNumImagesOnThread(boolean allowSearch)
 397       throws IOException {
 398         if (numImages != 0) {
 399             return numImages;
 400         }
 401         if (iis == null) {
 402             throw new IllegalStateException("Input not set");
 403         }
 404         if (allowSearch == true) {
 405             if (seekForwardOnly) {
 406                 throw new IllegalStateException(
 407                     "seekForwardOnly and allowSearch can't both be true!");
 408             }
 409             // Otherwise we have to read the entire stream
 410 
 411             if (!tablesOnlyChecked) {
 412                 checkTablesOnly();
 413             }
 414 
 415             iis.mark();
 416 
 417             gotoImage(0);
 418 
 419             JPEGBuffer buffer = new JPEGBuffer(iis);
 420             buffer.loadBuf(0);
 421 
 422             boolean done = false;
 423             while (!done) {
 424                 done = buffer.scanForFF(this);
 425                 switch (buffer.buf[buffer.bufPtr] & 0xff) {
 426                 case JPEG.SOI:
 427                     numImages++;
 428                     // FALL THROUGH to decrement buffer vars
 429                     // This first set doesn't have a length
 430                 case 0: // not a marker, just a data 0xff
 431                 case JPEG.RST0:
 432                 case JPEG.RST1:
 433                 case JPEG.RST2:
 434                 case JPEG.RST3:
 435                 case JPEG.RST4:
 436                 case JPEG.RST5:
 437                 case JPEG.RST6:
 438                 case JPEG.RST7:
 439                 case JPEG.EOI:
 440                     buffer.bufAvail--;
 441                     buffer.bufPtr++;
 442                     break;
 443                     // All the others have a length
 444                 default:
 445                     buffer.bufAvail--;
 446                     buffer.bufPtr++;
 447                     buffer.loadBuf(2);
 448                     int length = ((buffer.buf[buffer.bufPtr++] & 0xff) << 8) |
 449                         (buffer.buf[buffer.bufPtr++] & 0xff);
 450                     buffer.bufAvail -= 2;
 451                     length -= 2; // length includes itself
 452                     buffer.skipData(length);
 453                 }
 454             }
 455 
 456 
 457             iis.reset();
 458 
 459             return numImages;
 460         }
 461 
 462         return -1;  // Search is necessary for JPEG
 463     }
 464 
 465     /**
 466      * Sets the input stream to the start of the requested image.
 467      * <pre>
 468      * @exception IllegalStateException if the input source has not been
 469      * set.
 470      * @exception IndexOutOfBoundsException if the supplied index is
 471      * out of bounds.
 472      * </pre>
 473      */
 474     private void gotoImage(int imageIndex) throws IOException {
 475         if (iis == null) {
 476             throw new IllegalStateException("Input not set");
 477         }
 478         if (imageIndex < minIndex) {
 479             throw new IndexOutOfBoundsException();
 480         }
 481         if (!tablesOnlyChecked) {
 482             checkTablesOnly();
 483         }
 484         if (imageIndex < imagePositions.size()) {
 485             iis.seek(imagePositions.get(imageIndex).longValue());
 486         } else {
 487             // read to start of image, saving positions
 488             // First seek to the last position we already have, and skip the
 489             // entire image
 490             Long pos = imagePositions.get(imagePositions.size()-1);
 491             iis.seek(pos.longValue());
 492             skipImage();
 493             // Now add all intervening positions, skipping images
 494             for (int index = imagePositions.size();
 495                  index <= imageIndex;
 496                  index++) {
 497                 // Is there an image?
 498                 if (!hasNextImage()) {
 499                     throw new IndexOutOfBoundsException();
 500                 }
 501                 pos = iis.getStreamPosition();
 502                 imagePositions.add(pos);
 503                 if (seekForwardOnly) {
 504                     iis.flushBefore(pos.longValue());
 505                 }
 506                 if (index < imageIndex) {
 507                     skipImage();
 508                 }  // Otherwise we are where we want to be
 509             }
 510         }
 511 
 512         if (seekForwardOnly) {
 513             minIndex = imageIndex;
 514         }
 515 
 516         haveSeeked = true;  // No way is native buffer still valid
 517     }
 518 
 519     /**
 520      * Skip over a complete image in the stream, leaving the stream
 521      * positioned such that the next byte to be read is the first
 522      * byte of the next image. For JPEG, this means that we read
 523      * until we encounter an EOI marker or until the end of the stream.
 524      * We can find data same as EOI marker in some headers
 525      * or comments, so we have to skip bytes related to these headers.
 526      * If the stream ends before an EOI marker is encountered,
 527      * an IndexOutOfBoundsException is thrown.
 528      */
 529     private void skipImage() throws IOException {
 530         if (debug) {
 531             System.out.println("skipImage called");
 532         }
 533         // verify if image starts with an SOI marker
 534         int initialFF = iis.read();
 535         if (initialFF == 0xff) {
 536             int soiMarker = iis.read();
 537             if (soiMarker != JPEG.SOI) {
 538                 throw new IOException("skipImage : Invalid image doesn't "
 539                         + "start with SOI marker");
 540             }
 541         } else {
 542             throw new IOException("skipImage : Invalid image doesn't start "
 543                     + "with 0xff");
 544         }
 545         boolean foundFF = false;
 546         String IOOBE = "skipImage : Reached EOF before we got EOI marker";
 547         int markerLength = 2;
 548         for (int byteval = iis.read();
 549              byteval != -1;
 550              byteval = iis.read()) {
 551 
 552             if (foundFF == true) {
 553                 switch (byteval) {
 554                     case JPEG.EOI:
 555                         if (debug) {
 556                             System.out.println("skipImage : Found EOI at " +
 557                                     (iis.getStreamPosition() - markerLength));
 558                         }
 559                         return;
 560                     case JPEG.SOI:
 561                         throw new IOException("skipImage : Found extra SOI"
 562                                 + " marker before getting to EOI");
 563                     case 0:
 564                     // markers which doesn't contain length data
 565                     case JPEG.RST0:
 566                     case JPEG.RST1:
 567                     case JPEG.RST2:
 568                     case JPEG.RST3:
 569                     case JPEG.RST4:
 570                     case JPEG.RST5:
 571                     case JPEG.RST6:
 572                     case JPEG.RST7:
 573                     case JPEG.TEM:
 574                         break;
 575                     // markers which contains length data
 576                     case JPEG.SOF0:
 577                     case JPEG.SOF1:
 578                     case JPEG.SOF2:
 579                     case JPEG.SOF3:
 580                     case JPEG.DHT:
 581                     case JPEG.SOF5:
 582                     case JPEG.SOF6:
 583                     case JPEG.SOF7:
 584                     case JPEG.JPG:
 585                     case JPEG.SOF9:
 586                     case JPEG.SOF10:
 587                     case JPEG.SOF11:
 588                     case JPEG.DAC:
 589                     case JPEG.SOF13:
 590                     case JPEG.SOF14:
 591                     case JPEG.SOF15:
 592                     case JPEG.SOS:
 593                     case JPEG.DQT:
 594                     case JPEG.DNL:
 595                     case JPEG.DRI:
 596                     case JPEG.DHP:
 597                     case JPEG.EXP:
 598                     case JPEG.APP0:
 599                     case JPEG.APP1:
 600                     case JPEG.APP2:
 601                     case JPEG.APP3:
 602                     case JPEG.APP4:
 603                     case JPEG.APP5:
 604                     case JPEG.APP6:
 605                     case JPEG.APP7:
 606                     case JPEG.APP8:
 607                     case JPEG.APP9:
 608                     case JPEG.APP10:
 609                     case JPEG.APP11:
 610                     case JPEG.APP12:
 611                     case JPEG.APP13:
 612                     case JPEG.APP14:
 613                     case JPEG.APP15:
 614                     case JPEG.COM:
 615                         // read length of header from next 2 bytes
 616                         int lengthHigherBits, lengthLowerBits, length;
 617                         lengthHigherBits = iis.read();
 618                         if (lengthHigherBits != (-1)) {
 619                             lengthLowerBits = iis.read();
 620                             if (lengthLowerBits != (-1)) {
 621                                 length = (lengthHigherBits << 8) |
 622                                         lengthLowerBits;
 623                                 // length contains already read 2 bytes
 624                                 length -= 2;
 625                             } else {
 626                                 throw new IndexOutOfBoundsException(IOOBE);
 627                             }
 628                         } else {
 629                             throw new IndexOutOfBoundsException(IOOBE);
 630                         }
 631                         // skip the length specified in marker
 632                         iis.skipBytes(length);
 633                         break;
 634                     case (-1):
 635                         throw new IndexOutOfBoundsException(IOOBE);
 636                     default:
 637                         throw new IOException("skipImage : Invalid marker "
 638                                 + "starting with ff "
 639                                 + Integer.toHexString(byteval));
 640                 }
 641             }
 642             foundFF = (byteval == 0xff);
 643         }
 644         throw new IndexOutOfBoundsException(IOOBE);
 645     }
 646 
 647     /**
 648      * Returns {@code true} if there is an image beyond
 649      * the current stream position.  Does not disturb the
 650      * stream position.
 651      */
 652     private boolean hasNextImage() throws IOException {
 653         if (debug) {
 654             System.out.print("hasNextImage called; returning ");
 655         }
 656         iis.mark();
 657         boolean foundFF = false;
 658         for (int byteval = iis.read();
 659              byteval != -1;
 660              byteval = iis.read()) {
 661 
 662             if (foundFF == true) {
 663                 if (byteval == JPEG.SOI) {
 664                     iis.reset();
 665                     if (debug) {
 666                         System.out.println("true");
 667                     }
 668                     return true;
 669                 }
 670             }
 671             foundFF = (byteval == 0xff) ? true : false;
 672         }
 673         // We hit the end of the stream before we hit an SOI, so no image
 674         iis.reset();
 675         if (debug) {
 676             System.out.println("false");
 677         }
 678         return false;
 679     }
 680 
 681     /**
 682      * Push back the given number of bytes to the input stream.
 683      * Called by the native code at the end of each image so
 684      * that the next one can be identified from Java.
 685      */
 686     private void pushBack(int num) throws IOException {
 687         if (debug) {
 688             System.out.println("pushing back " + num + " bytes");
 689         }
 690         cbLock.lock();
 691         try {
 692             iis.seek(iis.getStreamPosition()-num);
 693             // The buffer is clear after this, so no need to set haveSeeked.
 694         } finally {
 695             cbLock.unlock();
 696         }
 697     }
 698 
 699     /**
 700      * Reads header information for the given image, if possible.
 701      */
 702     private void readHeader(int imageIndex, boolean reset)
 703         throws IOException {
 704         gotoImage(imageIndex);
 705         readNativeHeader(reset); // Ignore return
 706         currentImage = imageIndex;
 707     }
 708 
 709     private boolean readNativeHeader(boolean reset) throws IOException {
 710         boolean retval = false;
 711         retval = readImageHeader(structPointer, haveSeeked, reset);
 712         haveSeeked = false;
 713         return retval;
 714     }
 715 
 716     /**
 717      * Read in the header information starting from the current
 718      * stream position, returning {@code true} if the
 719      * header was a tables-only image.  After this call, the
 720      * native IJG decompression struct will contain the image
 721      * information required by most query calls below
 722      * (e.g. getWidth, getHeight, etc.), if the header was not
 723      * a tables-only image.
 724      * If reset is {@code true}, the state of the IJG
 725      * object is reset so that it can read a header again.
 726      * This happens automatically if the header was a tables-only
 727      * image.
 728      */
 729     private native boolean readImageHeader(long structPointer,
 730                                            boolean clearBuffer,
 731                                            boolean reset)
 732         throws IOException;
 733 
 734     /*
 735      * Called by the native code whenever an image header has been
 736      * read.  Whether we read metadata or not, we always need this
 737      * information, so it is passed back independently of
 738      * metadata, which may never be read.
 739      */
 740     private void setImageData(int width,
 741                               int height,
 742                               int colorSpaceCode,
 743                               int outColorSpaceCode,
 744                               int numComponents,
 745                               byte [] iccData) {
 746         this.width = width;
 747         this.height = height;
 748         this.colorSpaceCode = colorSpaceCode;
 749         this.outColorSpaceCode = outColorSpaceCode;
 750         this.numComponents = numComponents;
 751 
 752         if (iccData == null) {
 753             iccCS = null;
 754             return;
 755         }
 756 
 757         ICC_Profile newProfile = null;
 758         try {
 759             newProfile = ICC_Profile.getInstance(iccData);
 760         } catch (IllegalArgumentException e) {
 761             /*
 762              * Color profile data seems to be invalid.
 763              * Ignore this profile.
 764              */
 765             iccCS = null;
 766             warningOccurred(WARNING_IGNORE_INVALID_ICC);
 767 
 768             return;
 769         }
 770         byte[] newData = newProfile.getData();
 771 
 772         ICC_Profile oldProfile = null;
 773         if (iccCS instanceof ICC_ColorSpace) {
 774             oldProfile = ((ICC_ColorSpace)iccCS).getProfile();
 775         }
 776         byte[] oldData = null;
 777         if (oldProfile != null) {
 778             oldData = oldProfile.getData();
 779         }
 780 
 781         /*
 782          * At the moment we can't rely on the ColorSpace.equals()
 783          * and ICC_Profile.equals() because they do not detect
 784          * the case when two profiles are created from same data.
 785          *
 786          * So, we have to do data comparison in order to avoid
 787          * creation of different ColorSpace instances for the same
 788          * embedded data.
 789          */
 790         if (oldData == null ||
 791             !java.util.Arrays.equals(oldData, newData))
 792         {
 793             iccCS = new ICC_ColorSpace(newProfile);
 794             // verify new color space
 795             try {
 796                 float[] colors = iccCS.fromRGB(new float[] {1f, 0f, 0f});
 797             } catch (CMMException e) {
 798                 /*
 799                  * Embedded profile seems to be corrupted.
 800                  * Ignore this profile.
 801                  */
 802                 iccCS = null;
 803                 cbLock.lock();
 804                 try {
 805                     warningOccurred(WARNING_IGNORE_INVALID_ICC);
 806                 } finally {
 807                     cbLock.unlock();
 808                 }
 809             }
 810         }
 811     }
 812 
 813     public int getWidth(int imageIndex) throws IOException {
 814         setThreadLock();
 815         try {
 816             if (currentImage != imageIndex) {
 817                 cbLock.check();
 818                 readHeader(imageIndex, true);
 819             }
 820             return width;
 821         } finally {
 822             clearThreadLock();
 823         }
 824     }
 825 
 826     public int getHeight(int imageIndex) throws IOException {
 827         setThreadLock();
 828         try {
 829             if (currentImage != imageIndex) {
 830                 cbLock.check();
 831                 readHeader(imageIndex, true);
 832             }
 833             return height;
 834         } finally {
 835             clearThreadLock();
 836         }
 837     }
 838 
 839     /////////// Color Conversion and Image Types
 840 
 841     /**
 842      * Return an ImageTypeSpecifier corresponding to the given
 843      * color space code, or null if the color space is unsupported.
 844      */
 845     private ImageTypeProducer getImageType(int code) {
 846         ImageTypeProducer ret = null;
 847 
 848         if ((code > 0) && (code < JPEG.NUM_JCS_CODES)) {
 849             ret = ImageTypeProducer.getTypeProducer(code);
 850         }
 851         return ret;
 852     }
 853 
 854     public ImageTypeSpecifier getRawImageType(int imageIndex)
 855         throws IOException {
 856         setThreadLock();
 857         try {
 858             if (currentImage != imageIndex) {
 859                 cbLock.check();
 860 
 861                 readHeader(imageIndex, true);
 862             }
 863 
 864             // Returns null if it can't be represented
 865             return getImageType(colorSpaceCode).getType();
 866         } finally {
 867             clearThreadLock();
 868         }
 869     }
 870 
 871     public Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex)
 872         throws IOException {
 873         setThreadLock();
 874         try {
 875             return getImageTypesOnThread(imageIndex);
 876         } finally {
 877             clearThreadLock();
 878         }
 879     }
 880 
 881     private Iterator<ImageTypeSpecifier> getImageTypesOnThread(int imageIndex)
 882         throws IOException {
 883         if (currentImage != imageIndex) {
 884             cbLock.check();
 885             readHeader(imageIndex, true);
 886         }
 887 
 888         // We return an iterator containing the default, any
 889         // conversions that the library provides, and
 890         // all the other default types with the same number
 891         // of components, as we can do these as a post-process.
 892         // As we convert Rasters rather than images, images
 893         // with alpha cannot be converted in a post-process.
 894 
 895         // If this image can't be interpreted, this method
 896         // returns an empty Iterator.
 897 
 898         // Get the raw ITS, if there is one.  Note that this
 899         // won't always be the same as the default.
 900         ImageTypeProducer raw = getImageType(colorSpaceCode);
 901 
 902         // Given the encoded colorspace, build a list of ITS's
 903         // representing outputs you could handle starting
 904         // with the default.
 905 
 906         ArrayList<ImageTypeProducer> list = new ArrayList<ImageTypeProducer>(1);
 907 
 908         switch (colorSpaceCode) {
 909         case JPEG.JCS_GRAYSCALE:
 910             list.add(raw);
 911             list.add(getImageType(JPEG.JCS_RGB));
 912             break;
 913         case JPEG.JCS_RGB:
 914             list.add(raw);
 915             list.add(getImageType(JPEG.JCS_GRAYSCALE));
 916             list.add(getImageType(JPEG.JCS_YCC));
 917             break;
 918         case JPEG.JCS_RGBA:
 919             list.add(raw);
 920             break;
 921         case JPEG.JCS_YCC:
 922             if (raw != null) {  // Might be null if PYCC.pf not installed
 923                 list.add(raw);
 924                 list.add(getImageType(JPEG.JCS_RGB));
 925             }
 926             break;
 927         case JPEG.JCS_YCCA:
 928             if (raw != null) {  // Might be null if PYCC.pf not installed
 929                 list.add(raw);
 930             }
 931             break;
 932         case JPEG.JCS_YCbCr:
 933             // As there is no YCbCr ColorSpace, we can't support
 934             // the raw type.
 935 
 936             // due to 4705399, use RGB as default in order to avoid
 937             // slowing down of drawing operations with result image.
 938             list.add(getImageType(JPEG.JCS_RGB));
 939 
 940             if (iccCS != null) {
 941                 list.add(new ImageTypeProducer() {
 942                     protected ImageTypeSpecifier produce() {
 943                         return ImageTypeSpecifier.createInterleaved
 944                          (iccCS,
 945                           JPEG.bOffsRGB,  // Assume it's for RGB
 946                           DataBuffer.TYPE_BYTE,
 947                           false,
 948                           false);
 949                     }
 950                 });
 951 
 952             }
 953 
 954             list.add(getImageType(JPEG.JCS_GRAYSCALE));
 955             list.add(getImageType(JPEG.JCS_YCC));
 956             break;
 957         case JPEG.JCS_YCbCrA:  // Default is to convert to RGBA
 958             // As there is no YCbCr ColorSpace, we can't support
 959             // the raw type.
 960             list.add(getImageType(JPEG.JCS_RGBA));
 961             break;
 962         }
 963 
 964         return new ImageTypeIterator(list.iterator());
 965     }
 966 
 967     /**
 968      * Checks the implied color conversion between the stream and
 969      * the target image, altering the IJG output color space if necessary.
 970      * If a java color conversion is required, then this sets up
 971      * {@code convert}.
 972      * If bands are being rearranged at all (either source or destination
 973      * bands are specified in the param), then the default color
 974      * conversions are assumed to be correct.
 975      * Throws an IIOException if there is no conversion available.
 976      */
 977     private void checkColorConversion(BufferedImage image,
 978                                       ImageReadParam param)
 979         throws IIOException {
 980 
 981         // If we are rearranging channels at all, the default
 982         // conversions remain in place.  If the user wants
 983         // raw channels then he should do this while reading
 984         // a Raster.
 985         if (param != null) {
 986             if ((param.getSourceBands() != null) ||
 987                 (param.getDestinationBands() != null)) {
 988                 // Accept default conversions out of decoder, silently
 989                 return;
 990             }
 991         }
 992 
 993         // XXX - We do not currently support any indexed color models,
 994         // though we could, as IJG will quantize for us.
 995         // This is a performance and memory-use issue, as
 996         // users can read RGB and then convert to indexed in Java.
 997 
 998         ColorModel cm = image.getColorModel();
 999 
1000         if (cm instanceof IndexColorModel) {
1001             throw new IIOException("IndexColorModel not supported");
1002         }
1003 
1004         // Now check the ColorSpace type against outColorSpaceCode
1005         // We may want to tweak the default
1006         ColorSpace cs = cm.getColorSpace();
1007         int csType = cs.getType();
1008         convert = null;
1009         switch (outColorSpaceCode) {
1010         case JPEG.JCS_GRAYSCALE:  // Its gray in the file
1011             if  (csType == ColorSpace.TYPE_RGB) { // We want RGB
1012                 // IJG can do this for us more efficiently
1013                 setOutColorSpace(structPointer, JPEG.JCS_RGB);
1014                 // Update java state according to changes
1015                 // in the native part of decoder.
1016                 outColorSpaceCode = JPEG.JCS_RGB;
1017                 numComponents = 3;
1018             } else if (csType != ColorSpace.TYPE_GRAY) {
1019                 throw new IIOException("Incompatible color conversion");
1020             }
1021             break;
1022         case JPEG.JCS_RGB:  // IJG wants to go to RGB
1023             if (csType ==  ColorSpace.TYPE_GRAY) {  // We want gray
1024                 if (colorSpaceCode == JPEG.JCS_YCbCr) {
1025                     // If the jpeg space is YCbCr, IJG can do it
1026                     setOutColorSpace(structPointer, JPEG.JCS_GRAYSCALE);
1027                     // Update java state according to changes
1028                     // in the native part of decoder.
1029                     outColorSpaceCode = JPEG.JCS_GRAYSCALE;
1030                     numComponents = 1;
1031                 }
1032             } else if ((iccCS != null) &&
1033                        (cm.getNumComponents() == numComponents) &&
1034                        (cs != iccCS)) {
1035                 // We have an ICC profile but it isn't used in the dest
1036                 // image.  So convert from the profile cs to the target cs
1037                 convert = new ColorConvertOp(iccCS, cs, null);
1038                 // Leave IJG conversion in place; we still need it
1039             } else if ((iccCS == null) &&
1040                        (!cs.isCS_sRGB()) &&
1041                        (cm.getNumComponents() == numComponents)) {
1042                 // Target isn't sRGB, so convert from sRGB to the target
1043                 convert = new ColorConvertOp(JPEG.JCS.sRGB, cs, null);
1044             } else if (csType != ColorSpace.TYPE_RGB) {
1045                 throw new IIOException("Incompatible color conversion");
1046             }
1047             break;
1048         case JPEG.JCS_RGBA:
1049             // No conversions available; image must be RGBA
1050             if ((csType != ColorSpace.TYPE_RGB) ||
1051                 (cm.getNumComponents() != numComponents)) {
1052                 throw new IIOException("Incompatible color conversion");
1053             }
1054             break;
1055         case JPEG.JCS_YCC:
1056             {
1057                 ColorSpace YCC = JPEG.JCS.getYCC();
1058                 if (YCC == null) { // We can't do YCC at all
1059                     throw new IIOException("Incompatible color conversion");
1060                 }
1061                 if ((cs != YCC) &&
1062                     (cm.getNumComponents() == numComponents)) {
1063                     convert = new ColorConvertOp(YCC, cs, null);
1064                 }
1065             }
1066             break;
1067         case JPEG.JCS_YCCA:
1068             {
1069                 ColorSpace YCC = JPEG.JCS.getYCC();
1070                 // No conversions available; image must be YCCA
1071                 if ((YCC == null) || // We can't do YCC at all
1072                     (cs != YCC) ||
1073                     (cm.getNumComponents() != numComponents)) {
1074                     throw new IIOException("Incompatible color conversion");
1075                 }
1076             }
1077             break;
1078         default:
1079             // Anything else we can't handle at all
1080             throw new IIOException("Incompatible color conversion");
1081         }
1082     }
1083 
1084     /**
1085      * Set the IJG output space to the given value.  The library will
1086      * perform the appropriate colorspace conversions.
1087      */
1088     private native void setOutColorSpace(long structPointer, int id);
1089 
1090     /////// End of Color Conversion & Image Types
1091 
1092     public ImageReadParam getDefaultReadParam() {
1093         return new JPEGImageReadParam();
1094     }
1095 
1096     public IIOMetadata getStreamMetadata() throws IOException {
1097         setThreadLock();
1098         try {
1099             if (!tablesOnlyChecked) {
1100                 cbLock.check();
1101                 checkTablesOnly();
1102             }
1103             return streamMetadata;
1104         } finally {
1105             clearThreadLock();
1106         }
1107     }
1108 
1109     public IIOMetadata getImageMetadata(int imageIndex)
1110         throws IOException {
1111         setThreadLock();
1112         try {
1113             // imageMetadataIndex will always be either a valid index or
1114             // -1, in which case imageMetadata will not be null.
1115             // So we can leave checking imageIndex for gotoImage.
1116             if ((imageMetadataIndex == imageIndex)
1117                 && (imageMetadata != null)) {
1118                 return imageMetadata;
1119             }
1120 
1121             cbLock.check();
1122 
1123             gotoImage(imageIndex);
1124 
1125             imageMetadata = new JPEGMetadata(false, false, iis, this);
1126 
1127             imageMetadataIndex = imageIndex;
1128 
1129             return imageMetadata;
1130         } finally {
1131             clearThreadLock();
1132         }
1133     }
1134 
1135     public BufferedImage read(int imageIndex, ImageReadParam param)
1136         throws IOException {
1137         setThreadLock();
1138         try {
1139             cbLock.check();
1140             try {
1141                 readInternal(imageIndex, param, false);
1142             } catch (RuntimeException e) {
1143                 resetLibraryState(structPointer);
1144                 throw e;
1145             } catch (IOException e) {
1146                 resetLibraryState(structPointer);
1147                 throw e;
1148             }
1149 
1150             BufferedImage ret = image;
1151             image = null;  // don't keep a reference here
1152             return ret;
1153         } finally {
1154             clearThreadLock();
1155         }
1156     }
1157 
1158     private Raster readInternal(int imageIndex,
1159                                 ImageReadParam param,
1160                                 boolean wantRaster) throws IOException {
1161         readHeader(imageIndex, false);
1162 
1163         WritableRaster imRas = null;
1164         int numImageBands = 0;
1165 
1166         if (!wantRaster){
1167             // Can we read this image?
1168             Iterator<ImageTypeSpecifier> imageTypes = getImageTypes(imageIndex);
1169             if (imageTypes.hasNext() == false) {
1170                 throw new IIOException("Unsupported Image Type");
1171             }
1172 
1173             image = getDestination(param, imageTypes, width, height);
1174             imRas = image.getRaster();
1175 
1176             // The destination may still be incompatible.
1177 
1178             numImageBands = image.getSampleModel().getNumBands();
1179 
1180             // Check whether we can handle any implied color conversion
1181 
1182             // Throws IIOException if the stream and the image are
1183             // incompatible, and sets convert if a java conversion
1184             // is necessary
1185             checkColorConversion(image, param);
1186 
1187             // Check the source and destination bands in the param
1188             checkReadParamBandSettings(param, numComponents, numImageBands);
1189         } else {
1190             // Set the output color space equal to the input colorspace
1191             // This disables all conversions
1192             setOutColorSpace(structPointer, colorSpaceCode);
1193             image = null;
1194         }
1195 
1196         // Create an intermediate 1-line Raster that will hold the decoded,
1197         // subsampled, clipped, band-selected image data in a single
1198         // byte-interleaved buffer.  The above transformations
1199         // will occur in C for performance.  Every time this Raster
1200         // is filled we will call back to acceptPixels below to copy
1201         // this to whatever kind of buffer our image has.
1202 
1203         int [] srcBands = JPEG.bandOffsets[numComponents-1];
1204         int numRasterBands = (wantRaster ? numComponents : numImageBands);
1205         destinationBands = null;
1206 
1207         Rectangle srcROI = new Rectangle(0, 0, 0, 0);
1208         destROI = new Rectangle(0, 0, 0, 0);
1209         computeRegions(param, width, height, image, srcROI, destROI);
1210 
1211         int periodX = 1;
1212         int periodY = 1;
1213 
1214         minProgressivePass = 0;
1215         maxProgressivePass = Integer.MAX_VALUE;
1216 
1217         if (param != null) {
1218             periodX = param.getSourceXSubsampling();
1219             periodY = param.getSourceYSubsampling();
1220 
1221             int[] sBands = param.getSourceBands();
1222             if (sBands != null) {
1223                 srcBands = sBands;
1224                 numRasterBands = srcBands.length;
1225             }
1226             if (!wantRaster) {  // ignore dest bands for Raster
1227                 destinationBands = param.getDestinationBands();
1228             }
1229 
1230             minProgressivePass = param.getSourceMinProgressivePass();
1231             maxProgressivePass = param.getSourceMaxProgressivePass();
1232 
1233             if (param instanceof JPEGImageReadParam) {
1234                 JPEGImageReadParam jparam = (JPEGImageReadParam) param;
1235                 if (jparam.areTablesSet()) {
1236                     abbrevQTables = jparam.getQTables();
1237                     abbrevDCHuffmanTables = jparam.getDCHuffmanTables();
1238                     abbrevACHuffmanTables = jparam.getACHuffmanTables();
1239                 }
1240             }
1241         }
1242 
1243         int lineSize = destROI.width*numRasterBands;
1244 
1245         buffer = new DataBufferByte(lineSize);
1246 
1247         int [] bandOffs = JPEG.bandOffsets[numRasterBands-1];
1248 
1249         raster = Raster.createInterleavedRaster(buffer,
1250                                                 destROI.width, 1,
1251                                                 lineSize,
1252                                                 numRasterBands,
1253                                                 bandOffs,
1254                                                 null);
1255 
1256         // Now that we have the Raster we'll decode to, get a view of the
1257         // target Raster that will permit a simple setRect for each scanline
1258         if (wantRaster) {
1259             target =  Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE,
1260                                                      destROI.width,
1261                                                      destROI.height,
1262                                                      lineSize,
1263                                                      numRasterBands,
1264                                                      bandOffs,
1265                                                      null);
1266         } else {
1267             target = imRas;
1268         }
1269         int [] bandSizes = target.getSampleModel().getSampleSize();
1270         for (int i = 0; i < bandSizes.length; i++) {
1271             if (bandSizes[i] <= 0 || bandSizes[i] > 8) {
1272                 throw new IIOException("Illegal band size: should be 0 < size <= 8");
1273             }
1274         }
1275 
1276         /*
1277          * If the process is sequential, and we have restart markers,
1278          * we could skip to the correct restart marker, if the library
1279          * lets us.  That's an optimization to investigate later.
1280          */
1281 
1282         // Check for update listeners (don't call back if none)
1283         boolean callbackUpdates = ((updateListeners != null)
1284                                    || (progressListeners != null));
1285 
1286         // Set up progression data
1287         initProgressData();
1288         // if we have a metadata object, we can count the scans
1289         // and set knownPassCount
1290         if (imageIndex == imageMetadataIndex) { // We have metadata
1291             knownPassCount = 0;
1292             for (Iterator<MarkerSegment> iter =
1293                     imageMetadata.markerSequence.iterator(); iter.hasNext();) {
1294                 if (iter.next() instanceof SOSMarkerSegment) {
1295                     knownPassCount++;
1296                 }
1297             }
1298         }
1299         progInterval = Math.max((target.getHeight()-1) / 20, 1);
1300         if (knownPassCount > 0) {
1301             progInterval *= knownPassCount;
1302         } else if (maxProgressivePass != Integer.MAX_VALUE) {
1303             progInterval *= (maxProgressivePass - minProgressivePass + 1);
1304         }
1305 
1306         if (debug) {
1307             System.out.println("**** Read Data *****");
1308             System.out.println("numRasterBands is " + numRasterBands);
1309             System.out.print("srcBands:");
1310             for (int i = 0; i<srcBands.length;i++)
1311                 System.out.print(" " + srcBands[i]);
1312             System.out.println();
1313             System.out.println("destination bands is " + destinationBands);
1314             if (destinationBands != null) {
1315                 for (int i = 0; i < destinationBands.length; i++) {
1316                     System.out.print(" " + destinationBands[i]);
1317                 }
1318                 System.out.println();
1319             }
1320             System.out.println("sourceROI is " + srcROI);
1321             System.out.println("destROI is " + destROI);
1322             System.out.println("periodX is " + periodX);
1323             System.out.println("periodY is " + periodY);
1324             System.out.println("minProgressivePass is " + minProgressivePass);
1325             System.out.println("maxProgressivePass is " + maxProgressivePass);
1326             System.out.println("callbackUpdates is " + callbackUpdates);
1327         }
1328 
1329         // Finally, we are ready to read
1330 
1331         processImageStarted(currentImage);
1332 
1333         boolean aborted = false;
1334 
1335         // Note that getData disables acceleration on buffer, but it is
1336         // just a 1-line intermediate data transfer buffer that will not
1337         // affect the acceleration of the resulting image.
1338         aborted = readImage(structPointer,
1339                             buffer.getData(),
1340                             numRasterBands,
1341                             srcBands,
1342                             bandSizes,
1343                             srcROI.x, srcROI.y,
1344                             srcROI.width, srcROI.height,
1345                             periodX, periodY,
1346                             abbrevQTables,
1347                             abbrevDCHuffmanTables,
1348                             abbrevACHuffmanTables,
1349                             minProgressivePass, maxProgressivePass,
1350                             callbackUpdates);
1351 
1352         if (aborted) {
1353             processReadAborted();
1354         } else {
1355             processImageComplete();
1356         }
1357 
1358         return target;
1359 
1360     }
1361 
1362     /**
1363      * This method is called back from C when the intermediate Raster
1364      * is full.  The parameter indicates the scanline in the target
1365      * Raster to which the intermediate Raster should be copied.
1366      * After the copy, we notify update listeners.
1367      */
1368     private void acceptPixels(int y, boolean progressive) {
1369         if (convert != null) {
1370             convert.filter(raster, raster);
1371         }
1372         target.setRect(destROI.x, destROI.y + y, raster);
1373 
1374         cbLock.lock();
1375         try {
1376             processImageUpdate(image,
1377                                destROI.x, destROI.y+y,
1378                                raster.getWidth(), 1,
1379                                1, 1,
1380                                destinationBands);
1381             if ((y > 0) && (y%progInterval == 0)) {
1382                 int height = target.getHeight()-1;
1383                 float percentOfPass = ((float)y)/height;
1384                 if (progressive) {
1385                     if (knownPassCount != UNKNOWN) {
1386                         processImageProgress((pass + percentOfPass)*100.0F
1387                                              / knownPassCount);
1388                     } else if (maxProgressivePass != Integer.MAX_VALUE) {
1389                         // Use the range of allowed progressive passes
1390                         processImageProgress((pass + percentOfPass)*100.0F
1391                                              / (maxProgressivePass - minProgressivePass + 1));
1392                     } else {
1393                         // Assume there are a minimum of MIN_ESTIMATED_PASSES
1394                         // and that there is always one more pass
1395                         // Compute the percentage as the percentage at the end
1396                         // of the previous pass, plus the percentage of this
1397                         // pass scaled to be the percentage of the total remaining,
1398                         // assuming a minimum of MIN_ESTIMATED_PASSES passes and
1399                         // that there is always one more pass.  This is monotonic
1400                         // and asymptotic to 1.0, which is what we need.
1401                         int remainingPasses = // including this one
1402                             Math.max(2, MIN_ESTIMATED_PASSES-pass);
1403                         int totalPasses = pass + remainingPasses-1;
1404                         progInterval = Math.max(height/20*totalPasses,
1405                                                 totalPasses);
1406                         if (y%progInterval == 0) {
1407                             percentToDate = previousPassPercentage +
1408                                 (1.0F - previousPassPercentage)
1409                                 * (percentOfPass)/remainingPasses;
1410                             if (debug) {
1411                                 System.out.print("pass= " + pass);
1412                                 System.out.print(", y= " + y);
1413                                 System.out.print(", progInt= " + progInterval);
1414                                 System.out.print(", % of pass: " + percentOfPass);
1415                                 System.out.print(", rem. passes: "
1416                                                  + remainingPasses);
1417                                 System.out.print(", prev%: "
1418                                                  + previousPassPercentage);
1419                                 System.out.print(", %ToDate: " + percentToDate);
1420                                 System.out.print(" ");
1421                             }
1422                             processImageProgress(percentToDate*100.0F);
1423                         }
1424                     }
1425                 } else {
1426                     processImageProgress(percentOfPass * 100.0F);
1427                 }
1428             }
1429         } finally {
1430             cbLock.unlock();
1431         }
1432     }
1433 
1434     private void initProgressData() {
1435         knownPassCount = UNKNOWN;
1436         pass = 0;
1437         percentToDate = 0.0F;
1438         previousPassPercentage = 0.0F;
1439         progInterval = 0;
1440     }
1441 
1442     private void passStarted (int pass) {
1443         cbLock.lock();
1444         try {
1445             this.pass = pass;
1446             previousPassPercentage = percentToDate;
1447             processPassStarted(image,
1448                                pass,
1449                                minProgressivePass,
1450                                maxProgressivePass,
1451                                0, 0,
1452                                1,1,
1453                                destinationBands);
1454         } finally {
1455             cbLock.unlock();
1456         }
1457     }
1458 
1459     private void passComplete () {
1460         cbLock.lock();
1461         try {
1462             processPassComplete(image);
1463         } finally {
1464             cbLock.unlock();
1465         }
1466     }
1467 
1468     void thumbnailStarted(int thumbnailIndex) {
1469         cbLock.lock();
1470         try {
1471             processThumbnailStarted(currentImage, thumbnailIndex);
1472         } finally {
1473             cbLock.unlock();
1474         }
1475     }
1476 
1477     // Provide access to protected superclass method
1478     void thumbnailProgress(float percentageDone) {
1479         cbLock.lock();
1480         try {
1481             processThumbnailProgress(percentageDone);
1482         } finally {
1483             cbLock.unlock();
1484         }
1485     }
1486 
1487     // Provide access to protected superclass method
1488     void thumbnailComplete() {
1489         cbLock.lock();
1490         try {
1491             processThumbnailComplete();
1492         } finally {
1493             cbLock.unlock();
1494         }
1495     }
1496 
1497     /**
1498      * Returns {@code true} if the read was aborted.
1499      */
1500     private native boolean readImage(long structPointer,
1501                                      byte [] buffer,
1502                                      int numRasterBands,
1503                                      int [] srcBands,
1504                                      int [] bandSizes,
1505                                      int sourceXOffset, int sourceYOffset,
1506                                      int sourceWidth, int sourceHeight,
1507                                      int periodX, int periodY,
1508                                      JPEGQTable [] abbrevQTables,
1509                                      JPEGHuffmanTable [] abbrevDCHuffmanTables,
1510                                      JPEGHuffmanTable [] abbrevACHuffmanTables,
1511                                      int minProgressivePass,
1512                                      int maxProgressivePass,
1513                                      boolean wantUpdates);
1514 
1515     public void abort() {
1516         setThreadLock();
1517         try {
1518             /**
1519              * NB: we do not check the call back lock here,
1520              * we allow to abort the reader any time.
1521              */
1522 
1523             super.abort();
1524             abortRead(structPointer);
1525         } finally {
1526             clearThreadLock();
1527         }
1528     }
1529 
1530     /** Set the C level abort flag. Keep it atomic for thread safety. */
1531     private native void abortRead(long structPointer);
1532 
1533     /** Resets library state when an exception occurred during a read. */
1534     private native void resetLibraryState(long structPointer);
1535 
1536     public boolean canReadRaster() {
1537         return true;
1538     }
1539 
1540     public Raster readRaster(int imageIndex, ImageReadParam param)
1541         throws IOException {
1542         setThreadLock();
1543         Raster retval = null;
1544         try {
1545             cbLock.check();
1546             /*
1547              * This could be further optimized by not resetting the dest.
1548              * offset and creating a translated raster in readInternal()
1549              * (see bug 4994702 for more info).
1550              */
1551 
1552             // For Rasters, destination offset is logical, not physical, so
1553             // set it to 0 before calling computeRegions, so that the destination
1554             // region is not clipped.
1555             Point saveDestOffset = null;
1556             if (param != null) {
1557                 saveDestOffset = param.getDestinationOffset();
1558                 param.setDestinationOffset(new Point(0, 0));
1559             }
1560             retval = readInternal(imageIndex, param, true);
1561             // Apply the destination offset, if any, as a logical offset
1562             if (saveDestOffset != null) {
1563                 target = target.createWritableTranslatedChild(saveDestOffset.x,
1564                                                               saveDestOffset.y);
1565             }
1566         } catch (RuntimeException e) {
1567             resetLibraryState(structPointer);
1568             throw e;
1569         } catch (IOException e) {
1570             resetLibraryState(structPointer);
1571             throw e;
1572         } finally {
1573             clearThreadLock();
1574         }
1575         return retval;
1576     }
1577 
1578     public boolean readerSupportsThumbnails() {
1579         return true;
1580     }
1581 
1582     public int getNumThumbnails(int imageIndex) throws IOException {
1583         setThreadLock();
1584         try {
1585             cbLock.check();
1586 
1587             getImageMetadata(imageIndex);  // checks iis state for us
1588             // Now check the jfif segments
1589             JFIFMarkerSegment jfif =
1590                 (JFIFMarkerSegment) imageMetadata.findMarkerSegment
1591                 (JFIFMarkerSegment.class, true);
1592             int retval = 0;
1593             if (jfif != null) {
1594                 retval = (jfif.thumb == null) ? 0 : 1;
1595                 retval += jfif.extSegments.size();
1596             }
1597             return retval;
1598         } finally {
1599             clearThreadLock();
1600         }
1601     }
1602 
1603     public int getThumbnailWidth(int imageIndex, int thumbnailIndex)
1604         throws IOException {
1605         setThreadLock();
1606         try {
1607             cbLock.check();
1608 
1609             if ((thumbnailIndex < 0)
1610                 || (thumbnailIndex >= getNumThumbnails(imageIndex))) {
1611                 throw new IndexOutOfBoundsException("No such thumbnail");
1612             }
1613             // Now we know that there is a jfif segment
1614             JFIFMarkerSegment jfif =
1615                 (JFIFMarkerSegment) imageMetadata.findMarkerSegment
1616                 (JFIFMarkerSegment.class, true);
1617             return  jfif.getThumbnailWidth(thumbnailIndex);
1618         } finally {
1619             clearThreadLock();
1620         }
1621     }
1622 
1623     public int getThumbnailHeight(int imageIndex, int thumbnailIndex)
1624         throws IOException {
1625         setThreadLock();
1626         try {
1627             cbLock.check();
1628 
1629             if ((thumbnailIndex < 0)
1630                 || (thumbnailIndex >= getNumThumbnails(imageIndex))) {
1631                 throw new IndexOutOfBoundsException("No such thumbnail");
1632             }
1633             // Now we know that there is a jfif segment
1634             JFIFMarkerSegment jfif =
1635                 (JFIFMarkerSegment) imageMetadata.findMarkerSegment
1636                 (JFIFMarkerSegment.class, true);
1637             return  jfif.getThumbnailHeight(thumbnailIndex);
1638         } finally {
1639             clearThreadLock();
1640         }
1641     }
1642 
1643     public BufferedImage readThumbnail(int imageIndex,
1644                                        int thumbnailIndex)
1645         throws IOException {
1646         setThreadLock();
1647         try {
1648             cbLock.check();
1649 
1650             if ((thumbnailIndex < 0)
1651                 || (thumbnailIndex >= getNumThumbnails(imageIndex))) {
1652                 throw new IndexOutOfBoundsException("No such thumbnail");
1653             }
1654             // Now we know that there is a jfif segment and that iis is good
1655             JFIFMarkerSegment jfif =
1656                 (JFIFMarkerSegment) imageMetadata.findMarkerSegment
1657                 (JFIFMarkerSegment.class, true);
1658             return  jfif.getThumbnail(iis, thumbnailIndex, this);
1659         } finally {
1660             clearThreadLock();
1661         }
1662     }
1663 
1664     private void resetInternalState() {
1665         // reset C structures
1666         resetReader(structPointer);
1667 
1668         // reset local Java structures
1669         numImages = 0;
1670         imagePositions = new ArrayList<>();
1671         currentImage = -1;
1672         image = null;
1673         raster = null;
1674         target = null;
1675         buffer = null;
1676         destROI = null;
1677         destinationBands = null;
1678         streamMetadata = null;
1679         imageMetadata = null;
1680         imageMetadataIndex = -1;
1681         haveSeeked = false;
1682         tablesOnlyChecked = false;
1683         iccCS = null;
1684         initProgressData();
1685     }
1686 
1687     public void reset() {
1688         setThreadLock();
1689         try {
1690             cbLock.check();
1691             super.reset();
1692         } finally {
1693             clearThreadLock();
1694         }
1695     }
1696 
1697     private native void resetReader(long structPointer);
1698 
1699     public void dispose() {
1700         setThreadLock();
1701         try {
1702             cbLock.check();
1703 
1704             if (structPointer != 0) {
1705                 disposerRecord.dispose();
1706                 structPointer = 0;
1707             }
1708         } finally {
1709             clearThreadLock();
1710         }
1711     }
1712 
1713     private static native void disposeReader(long structPointer);
1714 
1715     private static class JPEGReaderDisposerRecord implements DisposerRecord {
1716         private long pData;
1717 
1718         public JPEGReaderDisposerRecord(long pData) {
1719             this.pData = pData;
1720         }
1721 
1722         public synchronized void dispose() {
1723             if (pData != 0) {
1724                 disposeReader(pData);
1725                 pData = 0;
1726             }
1727         }
1728     }
1729 
1730     private Thread theThread = null;
1731     private int theLockCount = 0;
1732 
1733     private synchronized void setThreadLock() {
1734         Thread currThread = Thread.currentThread();
1735         if (theThread != null) {
1736             if (theThread != currThread) {
1737                 // it looks like that this reader instance is used
1738                 // by multiple threads.
1739                 throw new IllegalStateException("Attempt to use instance of " +
1740                                                 this + " locked on thread " +
1741                                                 theThread + " from thread " +
1742                                                 currThread);
1743             } else {
1744                 theLockCount ++;
1745             }
1746         } else {
1747             theThread = currThread;
1748             theLockCount = 1;
1749         }
1750     }
1751 
1752     private synchronized void clearThreadLock() {
1753         Thread currThread = Thread.currentThread();
1754         if (theThread == null || theThread != currThread) {
1755             throw new IllegalStateException("Attempt to clear thread lock " +
1756                                             " form wrong thread." +
1757                                             " Locked thread: " + theThread +
1758                                             "; current thread: " + currThread);
1759         }
1760         theLockCount --;
1761         if (theLockCount == 0) {
1762             theThread = null;
1763         }
1764     }
1765 
1766     private CallBackLock cbLock = new CallBackLock();
1767 
1768     private static class CallBackLock {
1769 
1770         private State lockState;
1771 
1772         CallBackLock() {
1773             lockState = State.Unlocked;
1774         }
1775 
1776         void check() {
1777             if (lockState != State.Unlocked) {
1778                 throw new IllegalStateException("Access to the reader is not allowed");
1779             }
1780         }
1781 
1782         private void lock() {
1783             lockState = State.Locked;
1784         }
1785 
1786         private void unlock() {
1787             lockState = State.Unlocked;
1788         }
1789 
1790         private static enum State {
1791             Unlocked,
1792             Locked
1793         }
1794     }
1795 }
1796 
1797 /**
1798  * An internal helper class that wraps producer's iterator
1799  * and extracts specifier instances on demand.
1800  */
1801 class ImageTypeIterator implements Iterator<ImageTypeSpecifier> {
1802      private Iterator<ImageTypeProducer> producers;
1803      private ImageTypeSpecifier theNext = null;
1804 
1805      public ImageTypeIterator(Iterator<ImageTypeProducer> producers) {
1806          this.producers = producers;
1807      }
1808 
1809      public boolean hasNext() {
1810          if (theNext != null) {
1811              return true;
1812          }
1813          if (!producers.hasNext()) {
1814              return false;
1815          }
1816          do {
1817              theNext = producers.next().getType();
1818          } while (theNext == null && producers.hasNext());
1819 
1820          return (theNext != null);
1821      }
1822 
1823      public ImageTypeSpecifier next() {
1824          if (theNext != null || hasNext()) {
1825              ImageTypeSpecifier t = theNext;
1826              theNext = null;
1827              return t;
1828          } else {
1829              throw new NoSuchElementException();
1830          }
1831      }
1832 
1833      public void remove() {
1834          producers.remove();
1835      }
1836 }
1837 
1838 /**
1839  * An internal helper class that provides means for deferred creation
1840  * of ImageTypeSpecifier instance required to describe available
1841  * destination types.
1842  *
1843  * This implementation only supports standard
1844  * jpeg color spaces (defined by corresponding JCS color space code).
1845  *
1846  * To support other color spaces one can override produce() method to
1847  * return custom instance of ImageTypeSpecifier.
1848  */
1849 class ImageTypeProducer {
1850 
1851     private ImageTypeSpecifier type = null;
1852     boolean failed = false;
1853     private int csCode;
1854 
1855     public ImageTypeProducer(int csCode) {
1856         this.csCode = csCode;
1857     }
1858 
1859     public ImageTypeProducer() {
1860         csCode = -1; // undefined
1861     }
1862 
1863     public synchronized ImageTypeSpecifier getType() {
1864         if (!failed && type == null) {
1865             try {
1866                 type = produce();
1867             } catch (Throwable e) {
1868                 failed = true;
1869             }
1870         }
1871         return type;
1872     }
1873 
1874     private static final ImageTypeProducer [] defaultTypes =
1875             new ImageTypeProducer [JPEG.NUM_JCS_CODES];
1876 
1877     public static synchronized ImageTypeProducer getTypeProducer(int csCode) {
1878         if (csCode < 0 || csCode >= JPEG.NUM_JCS_CODES) {
1879             return null;
1880         }
1881         if (defaultTypes[csCode] == null) {
1882             defaultTypes[csCode] = new ImageTypeProducer(csCode);
1883         }
1884         return defaultTypes[csCode];
1885     }
1886 
1887     protected ImageTypeSpecifier produce() {
1888         switch (csCode) {
1889             case JPEG.JCS_GRAYSCALE:
1890                 return ImageTypeSpecifier.createFromBufferedImageType
1891                         (BufferedImage.TYPE_BYTE_GRAY);
1892             case JPEG.JCS_YCbCr:
1893             //there is no YCbCr raw type so by default we assume it as RGB
1894             case JPEG.JCS_RGB:
1895                 return ImageTypeSpecifier.createInterleaved(JPEG.JCS.sRGB,
1896                         JPEG.bOffsRGB,
1897                         DataBuffer.TYPE_BYTE,
1898                         false,
1899                         false);
1900             case JPEG.JCS_RGBA:
1901                 return ImageTypeSpecifier.createPacked(JPEG.JCS.sRGB,
1902                         0xff000000,
1903                         0x00ff0000,
1904                         0x0000ff00,
1905                         0x000000ff,
1906                         DataBuffer.TYPE_INT,
1907                         false);
1908             case JPEG.JCS_YCC:
1909                 if (JPEG.JCS.getYCC() != null) {
1910                     return ImageTypeSpecifier.createInterleaved(
1911                             JPEG.JCS.getYCC(),
1912                         JPEG.bandOffsets[2],
1913                         DataBuffer.TYPE_BYTE,
1914                         false,
1915                         false);
1916                 } else {
1917                     return null;
1918                 }
1919             case JPEG.JCS_YCCA:
1920                 if (JPEG.JCS.getYCC() != null) {
1921                     return ImageTypeSpecifier.createInterleaved(
1922                             JPEG.JCS.getYCC(),
1923                         JPEG.bandOffsets[3],
1924                         DataBuffer.TYPE_BYTE,
1925                         true,
1926                         false);
1927                 } else {
1928                     return null;
1929                 }
1930             default:
1931                 return null;
1932         }
1933     }
1934 }