diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/J2KImageReadParam.java zzx2/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/J2KImageReadParam.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/J2KImageReadParam.java 2006-09-29 15:25:32.000000000 -0400 +++ zzx2/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/J2KImageReadParam.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,147 +0,0 @@ -/* - * $RCSfile: J2KImageReadParam.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.3 $ - * $Date: 2006/09/29 19:25:32 $ - * $State: Exp $ - */ -package com.sun.media.imageio.plugins.jpeg2000; - -import javax.imageio.ImageReadParam; - -/** - * A subclass of ImageReadParam for reading images in - * the JPEG 2000 format. - * - *

The decoding parameters for JPEG 2000 are listed below: - * - *

- * - * - * - * - * - * - * - * - * - * - *
JPEG 2000 Plugin Decoding Parameters
Parameter Name Description
decodingRateSpecifies the decoding rate in bits per pixel (bpp) where the - * number of pixels is related to the image's original size (Note: - * this parameter is not affected by resolution). - * The default is Double.MAX_VALUE. - * It means decoding with the encoding rate. - *
resolutionSpecifies the resolution level wanted for the decoded image - * (0 means the lowest available resolution, the resolution - * level gives an image with the original dimension). If the given index - * is greater than the number of available resolution levels of the - * compressed image, the decoded image has the lowest available - * resolution (among all tile-components). This parameter affects only - * the inverse wavelet transform and not the number of bytes read by the - * codestream parser, which depends only on decodingRate. - * The default value, -1, means to use the resolution level at encoding. - *
- */ -public class J2KImageReadParam extends ImageReadParam { - /** Specifies the decoding rate in bits per pixel (bpp) where the - * number of pixels is related to the image's original size - * (Note: this number is not affected by resolution). - */ - private double decodingRate = Double.MAX_VALUE; - - /** Specifies the resolution level wanted for the decoded image - * (0 means the lowest available resolution, the resolution - * level gives an image with the original dimension). If the given index - * is greater than the number of available resolution levels of the - * compressed image, the decoded image has the lowest available - * resolution (among all tile-components). This parameter - * affects only the inverse wavelet transform but not the number - * of bytes read by the codestream parser, which - * depends only on decodingRate. - */ - private int resolution = -1; - - /** Constructs a default instance of J2KImageReadParam. */ - public J2KImageReadParam() { - super(); - } - - /** - * Sets decodingRate. - * - * @param rate the decoding rate in bits per pixel. - * @see #getDecodingRate() - */ - public void setDecodingRate(double rate) { - this.decodingRate = rate; - } - - /** - * Gets decodingRate. - * - * @return the decoding rate in bits per pixel. - * @see #setDecodingRate(double) - */ - public double getDecodingRate() { - return decodingRate; - } - - /** - * Sets resolution. - * - * @param resolution the resolution level with 0 being - * the lowest available. - * @see #getResolution() - */ - public void setResolution(int resolution) { - this.resolution = Math.max(resolution, -1); - } - - /** - * Gets resolution. - * - * @return the resolution level with 0 being - * the lowest available. - * @see #setResolution(int) - */ - public int getResolution() { - return resolution; - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/J2KImageWriteParam.java zzx2/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/J2KImageWriteParam.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/J2KImageWriteParam.java 2006-09-20 19:23:30.000000000 -0400 +++ zzx2/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/J2KImageWriteParam.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,462 +0,0 @@ -/* - * $RCSfile: J2KImageWriteParam.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.2 $ - * $Date: 2006/09/20 23:23:30 $ - * $State: Exp $ - */ -package com.sun.media.imageio.plugins.jpeg2000; - -import java.awt.Rectangle; -import java.awt.image.Raster; -import java.awt.image.RenderedImage; -import java.util.Collections; -import java.util.Locale; -import java.util.Iterator; -import javax.imageio.ImageWriteParam; - -/** - * A subclass of ImageWriteParam for writing images in - * the JPEG 2000 format. - * - *

JPEG 2000 plugin supports to losslessly or lossy compress gray-scale, - * RGB, and RGBA images with byte, unsigned short or short data type. It also - * supports losslessly compress bilevel, and 8-bit color indexed images. The - * result data is in the of JP2 format -- JPEG 2000 Part 1 or baseline format. - * - *

The parameters for encoding JPEG 2000 are listed in the following table: - * - *

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
JPEG 2000 Plugin Decoding Parameters
Parameter Name Description
numDecompositionLevels The number of decomposition levels to generate. This value must - * be in the range - * 0 ≤ numDecompositionLevels ≤ 32 - * . The default value is 5. Note that the number - * of resolution levels is - * numDecompositionLevels + 1. - * The number of decomposition levels is constant across - * all components and all tiles. - *
encodingRate The bitrate in bits-per-pixel for encoding. Should be set when - * lossy compression scheme is used. With the default value - * Double.MAX_VALUE, a lossless compression will be done. - *
lossless Indicates using the lossless scheme or not. It is equivalent to - * use reversible quantization and 5x3 integer wavelet filters. The - * default is true. - *
componentTransformation Specifies to utilize the component transformation on some tiles. - * If the wavelet transform is reversible (w5x3 filter), the Reversible - * Component Transformation (RCT) is applied. If not reversible - * (w9x7 filter), the Irreversible Component Transformation (ICT) is used. - *
filters Specifies which wavelet filters to use for the specified - * tile-components. JPEG 2000 part I only supports w5x3 and w9x7 filters. - *
codeBlockSize Specifies the maximum code-block size to use for tile-component. - * The maximum width and height is 1024, however the block size - * (i.e. width x height) must not exceed 4096. The minimum width and - * height is 4. The default values are (64, 64). - *
progressionType Specifies which type of progression should be used when generating - * the codestream. - *

The format is ont of the progression types defined below: - * - *

res : Resolution-Layer-Component-Position - *

layer: Layer-Resolution-Component-Position - *

res-pos: Resolution-Position-Component-Layer - *

pos-comp: Position-Component-Resolution-Layer - *

comp-pos: Component-Position-Resolution-Layer - *

SOPSpecifies whether start of packet (SOP) markers should be used. - * true enables, false disables it. The default value is false. - *
EPHSpecifies whether end of packet header (EPH) markers should be used. - * true enables, false disables it. The default value is false. - *
writeCodeStreamOnlySpecifies whether write only the jpeg2000 code stream, i.e, no any - * box is written. The default value is false. - *
- */ -public class J2KImageWriteParam extends ImageWriteParam { - /** The filter for lossy compression. */ - public static final String FILTER_97 = "w9x7"; - - /** The filter for lossless compression. */ - public static final String FILTER_53 = "w5x3"; - - /** - * The number of decomposition levels. - */ - private int numDecompositionLevels = 5; - - /** - * The bitrate in bits-per-pixel for encoding. Should be set when lossy - * compression scheme is used. The default is - * Double.MAX_VALUE. - */ - private double encodingRate = Double.MAX_VALUE; - - /** - * Indicates using the lossless scheme or not. It is equivalent to - * use reversible quantization and 5x3 integer wavelet filters. - */ - private boolean lossless = true; - - /** Specifies to utilize the component transformation with some tiles. - * If the wavelet transform is reversible (w5x3 filter), the - * Reversible Component Transformation (RCT) is applied. If not reversible - * (w9x7 filter), the Irreversible Component Transformation (ICT) - * is used. - */ - private boolean componentTransformation = true; - - /** Specifies which filters to use for the specified tile-components. - * JPEG 2000 part I only supports w5x3 and w9x7 filters. - */ - private String filter = FILTER_53; - - /** Specifies the maximum code-block size to use for tile-component. - * The maximum width and height is 1024, however the image area - * (i.e. width x height) must not exceed 4096. The minimum - * width and height is 4. Default: 64 64. - */ - private int[] codeBlockSize = new int[]{64, 64}; - - /** See above. - */ - private String progressionType = "layer"; - - /** Specifies whether end of packet header (EPH) markers should be used. - * true enables, false disables it. Default: false. - */ - private boolean EPH = false; - - /** Specifies whether start of packet (SOP) markers should be used. - * true enables, false disables it. Default: false. - */ - private boolean SOP = false; - - /** Specifies whether write only the jpeg2000 code stream, i.e, no any - * box is written. The default value is false. - */ - private boolean writeCodeStreamOnly = false; - - /** - * Constructor which sets the Locale. - * - * @param locale a Locale to be used to localize - * compression type names and quality descriptions, or - * null. - */ - public J2KImageWriteParam(Locale locale) { - super(locale); - setDefaults(); - } - - /** - * Constructs a J2KImageWriteParam object with default - * values for all parameters. - */ - public J2KImageWriteParam() { - super(); - setDefaults(); - } - - /** Set source */ - private void setDefaults() { - // override the params in the super class - canOffsetTiles = true; - canWriteTiles = true; - canOffsetTiles = true; - compressionTypes = new String[] {"JPEG2000"}; - canWriteCompressed = true; - tilingMode = MODE_EXPLICIT; - } - - /** - * Sets numDecompositionLevels. - * - * @param numDecompositionLevels the number of decomposition levels. - * @throws IllegalArgumentException if numDecompositionLevels - * is negative or greater than 32. - * @see #getNumDecompositionLevels - */ - public void setNumDecompositionLevels(int numDecompositionLevels) { - if(numDecompositionLevels < 0 || numDecompositionLevels > 32) { - throw new IllegalArgumentException - ("numDecompositionLevels < 0 || numDecompositionLevels > 32"); - } - this.numDecompositionLevels = numDecompositionLevels; - } - - /** - * Gets numDecompositionLevels. - * - * @return the number of decomposition levels. - * @see #setNumDecompositionLevels - */ - public int getNumDecompositionLevels() { - return numDecompositionLevels; - } - - /** - * Sets encodingRate. - * - * @param rate the encoding rate in bits-per-pixel. - * @see #getEncodingRate() - */ - public void setEncodingRate(double rate) { - this.encodingRate = rate; - if (encodingRate != Double.MAX_VALUE) { - lossless = false; - filter = FILTER_97; - } else { - lossless = true; - filter = FILTER_53; - } - } - - /** - * Gets encodingRate. - * - * @return the encoding rate in bits-per-pixel. - * @see #setEncodingRate(double) - */ - public double getEncodingRate() { - return encodingRate; - } - - /** - * Sets lossless. - * - * @param lossless whether the compression scheme is lossless. - * @see #getLossless() - */ - public void setLossless(boolean lossless) { - this.lossless = lossless; - } - - /** - * Gets lossless. - * - * @return whether the compression scheme is lossless. - * @see #setLossless(boolean) - */ - public boolean getLossless() { - return lossless; - } - - /** - * Sets filter. - * - * @param value which wavelet filters to use for the specified - * tile-components. - * @see #getFilter() - */ - public void setFilter(String value) { - filter = value; - } - - /** - * Gets filters. - * - * @return which wavelet filters to use for the specified - * tile-components. - * @see #setFilter(String) - */ - public String getFilter() { - return filter; - } - - /** - * Sets componentTransformation. - * - * @param value whether to utilize the component transformation. - * @see #getComponentTransformation() - */ - public void setComponentTransformation(boolean value) { - componentTransformation = value; - } - - /** - * Gets componentTransformation. - * - * @return whether to utilize the component transformation. - * @see #setComponentTransformation(boolean) - */ - public boolean getComponentTransformation() { - return componentTransformation; - } - - /** - * Sets codeBlockSize. - * - * @param value the maximum code-block size to use per tile-component. - * @see #getCodeBlockSize() - */ - public void setCodeBlockSize(int[] value) { - codeBlockSize = value; - } - - /** - * Gets codeBlockSize. - * - * @return the maximum code-block size to use per tile-component. - * @see #setCodeBlockSize(int[]) - */ - public int[] getCodeBlockSize() { - return codeBlockSize; - } - - /** - * Sets SOP. - * - * @param value whether start of packet (SOP) markers should be used. - * @see #getSOP() - */ - public void setSOP(boolean value) { - SOP = value; - } - - /** - * Gets SOP. - * - * @return whether start of packet (SOP) markers should be used. - * @see #setSOP(boolean) - */ - public boolean getSOP() { - return SOP; - } - - /** - * Sets EPH. - * - * @param value whether end of packet header (EPH) markers should be used. - * @see #getEPH() - */ - public void setEPH(boolean value) { - EPH = value; - } - - /** - * Gets EPH. - * - * @return whether end of packet header (EPH) markers should be used. - * @see #setEPH(boolean) - */ - public boolean getEPH() { - return EPH; - } - - /** - * Sets progressionType. - * - * @param value which type of progression should be used when generating - * the codestream. - * @see #getProgressionType() - */ - public void setProgressionType(String value) { - progressionType = value; - } - - /** - * Gets progressionType. - * - * @return which type of progression should be used when generating - * the codestream. - * @see #setProgressionType(String) - */ - public String getProgressionType() { - return progressionType; - } - - /** Sets writeCodeStreamOnly. - * - * @param value Whether the jpeg2000 code stream only or the jp2 format - * will be written into the output. - * @see #getWriteCodeStreamOnly() - */ - public void setWriteCodeStreamOnly(boolean value) { - writeCodeStreamOnly = value; - } - - /** Gets writeCodeStreamOnly. - * - * @return whether the jpeg2000 code stream only or the jp2 format - * will be written into the output. - * @see #setWriteCodeStreamOnly(boolean) - */ - public boolean getWriteCodeStreamOnly() { - return writeCodeStreamOnly; - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/package.html zzx2/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/package.html --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/package.html 2005-02-11 00:01:16.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageio/plugins/jpeg2000/package.html 1969-12-31 19:00:00.000000000 -0500 @@ -1,768 +0,0 @@ - - -Package containing the public classes used by the Sun JPEG 2000 plug-in for -the Image I/O Framework. - -

Image Metadata

- -

Document Type Definition

- -The DTD for the native image metadata format is as follows: - -

-

-<!DOCTYPE "com_sun_media_imageio_plugins_jpeg2000_image_1.0" [ 
-
-  <!ELEMENT com_sun_media_imageio_plugins_jpeg2000_image_1.0 (JPEG2000SignatureBox,
-                                              JPEG2000FileTypeBox,
-                                              OtherBoxes) >
-
-  <!-- JPEG2000HeaderSuperBox should be before JPEG2000CodeStreamBox;  This
-      is the only constraint for the sequence of these boxes -->
-  <!ELEMENT OtherBoxes (JPEG2000HeaderSuperBox,
-                          JPEG2000CodeStreamBox,
-                          JPEG2000IntellectualPropertyRightsBox*,
-                          JPEG2000XMLBox*,
-                          JPEG2000UUIDBox*,
-                          JPEG2000UUIDInfoBox*)>
-
-  <!-- JPEG 2000 Signature box -->
-  <!ELEMENT JPEG2000SignatureBox EMPTY>
-    <!ATTLIST JPEG2000SignatureBox
-              Length CDATA #FIXED "12"
-              Type CDATA #FIXED "jP  "
-              Signature CDATA #FIXED "0x0D0A870A">
-
-  <!-- JPEG 2000 File type box -->
-  <!ELEMENT JPEG2000FileTypeBox (Brand, MinorVersion, CompatibilityList) >
-    <!ELEMENT Brand (#PCDATA)>
-    <!ELEMENT MinorVersion (#PCDATA)>
-    <!ELEMENT CompatibilityList (#PCDATA)>
-    <!ATTLIST JPEG2000FileTypeBox
-              Length CDATA #FIXED "12"
-              Type CDATA #FIXED "jP  "
-              ExtraLength CDATA #IMPLIED>
-
-  <!-- JPEG 2000 header super box-->
-  <!ELEMENT JPEG2000HeaderSuperBox (JPEG2000HeaderBox, OptionalBoxes) >
-    <!ELEMENT OptionalBoxes (JPEG2000BitsPerComponentBox,
-                                JPEG2000ColorSpecificationBox,
-                                JPEG2000PaletteBox?,
-                                JPEG2000ComponentMappingBox?,
-                                JPEG2000ChannelDefinitionBox?,
-                                JPEG2000ResolutionBox?)>
-    <!ATTLIST JPEG2000HeaderSuperBox
-              Length CDATA #REQUIRED
-              Type CDATA #FIXED "jp2h"
-              ExtraLength CDATA #IMPLIED>
-
-  <!-- JPEG 2000 image header box -->
-  <!ELEMENT JPEG2000HeaderBox (Width, Height, NumComponents, BitDepth,
-                                 CompressionType, UnknownColorspace,
-                                 IntellectualProperty)>
-    <!ELEMENT Width (#PCDATA)>
-    <!ELEMENT Height (#PCDATA)>
-    <!ELEMENT NumComponents (#PCDATA)>
-    <!ELEMENT BitDepth (#PCDATA)>
-    <!ELEMENT CompressionType (#PCDATA)>
-    <!ELEMENT UnknownColorspace (#PCDATA)>
-    <!ELEMENT IntellectualProperty (#PCDATA)>
-    <!ATTLIST JPEG2000HeaderBox
-              Length CDATA #FIXED "22"
-              Type CDATA #FIXED "ihdr">
-
-  <!-- JPEG 2000 bits per component box -->
-  <!ELEMENT JPEG2000BitsPerComponentBox (BitDepth)>
-    <!ATTLIST JPEG2000BitsPerComponentBox
-              Length CDATA #REQUIRED
-              Type CDATA #FIXED "bpcc"
-              ExtraLength CDATA #IMPLIED>
-
-  <!-- JPEG 2000 color specification box -->
-  <!ELEMENT JPEG2000ColorSpecificationBox (Method, Precedence,
-                                             ApproximationAccuracy,
-                                             EnumeratedColorSpace,
-                                             ICCProfile)>
-    <!ELEMENT Method (#PCDATA)>
-    <!ELEMENT Precedence (#PCDATA)>
-    <!ELEMENT ApproximationAccuracy (#PCDATA)>
-    <!ELEMENT EnumeratedColorSpace (#PCDATA)>
-    <!ELEMENT ICCProfile (#PCDATA)>
-    <!ATTLIST JPEG2000ColorSpecificationBox
-              Length CDATA #REQUIRED
-              Type CDATA #FIXED "colr"
-              ExtraLength CDATA #IMPLIED>
-
-  <!-- JPEG 2000 palette box -->
-  <!ELEMENT JPEG2000PaletteBox (NumberEntries, NumberColors,
-                                  BitDepth,
-                                  LUT)>
-    <!ELEMENT NumberEntries (#PCDATA)>
-    <!ELEMENT NumberColors (#PCDATA)>
-    <!ELEMENT LUT (LUTRow*)>
-    <!ELEMENT LUTRow (#PCDATA)>
-    <!ATTLIST JPEG2000PaletteBox
-              Length CDATA #REQUIRED
-              Type CDATA #FIXED "pclr"
-              ExtraLength CDATA #IMPLIED>
-
-  <!-- JPEG 2000 component mapping box-->
-  <!ELEMENT JPEG2000ComponentMappingBox (Component, ComponentType,
-                                           ComponentAssociation)>
-    <!ELEMENT Component (#PCDATA)>
-    <!ELEMENT ComponentType (#PCDATA)>
-    <!ELEMENT ComponentAssociation (#PCDATA)>
-    <!ATTLIST JPEG2000ComponentMappingBox
-              Length CDATA #REQUIRED
-              Type CDATA #FIXED "cmap"
-              ExtraLength CDATA #IMPLIED>
-
-  <!-- JPEG 2000 channel definition box-->
-  <!ELEMENT JPEG2000ChannelDefinitionBox (NumberOfDefinition, Definitions)>
-    <!ELEMENT NumberOfDefinition (#PCDATA)>
-    <!ELEMENT Definitions (ChannelNumber, ChannelType)*>
-    <!ELEMENT ChannelNumber (#PCDATA)>
-    <!ELEMENT ChannelType (#PCDATA)>
-    <!ELEMENT ChannelAssociation (#PCDATA)>
-    <!ATTLIST JPEG2000ChannelDefinitionBox
-              Length CDATA #REQUIRED
-              Type CDATA #FIXED "cdef"
-              ExtraLength CDATA #IMPLIED>
-
-  <!-- JPEG 2000 resolution box-->
-  <!ELEMENT JPEG2000ResolutionBox (JPEG2000CaptureResolutionBox,
-                                     JPEG2000DefaultDisplayResolutionBox)>
-    <!ATTLIST JPEG2000ResolutionBox
-              Length CDATA #REQUIRED
-              Type CDATA #FIXED "res "
-              ExtraLength CDATA #IMPLIED>
-
-  <!-- JPEG 2000 capture resolution box-->
-  <!ELEMENT JPEG2000CaptureResolutionBox (VerticalResolutionNumerator,
-                                            VerticalResolutionDenominator,
-                                            HorizontalResolutionNumerator,
-                                            HorizontalResolutionDenominator,
-                                            VerticalResolutionExponent,
-                                            HorizontalResolutionExponent)>
-    <!ELEMENT VerticalResolutionNumerator (#PCDATA)>
-    <!ELEMENT VerticalResolutionDenominator (#PCDATA)>
-    <!ELEMENT HorizontalResolutionNumerator (#PCDATA)>
-    <!ELEMENT HorizontalResolutionDenominator (#PCDATA)>
-    <!ELEMENT VerticalResolutionExponent (#PCDATA)>
-    <!ELEMENT HorizontalResolutionExponent (#PCDATA)>
-    <!ATTLIST JPEG2000CaptureResolutionBox
-              Length CDATA #REQUIRED
-              Type CDATA #FIXED "resc"
-              ExtraLength CDATA #IMPLIED>
-
-  <!-- JPEG 2000 default display resolution box-->
-  <!ELEMENT JPEG2000DefaultDisplayResolutionBox (VerticalResolutionNumerator,
-                                            VerticalResolutionDenominator,
-                                            HorizontalResolutionNumerator,
-                                            HorizontalResolutionDenominator,
-                                            VerticalResolutionExponent,
-                                            HorizontalResolutionExponent)>
-    <!ATTLIST JPEG2000DefaultDisplayResolutionBox
-              Length CDATA #REQUIRED
-              Type CDATA #FIXED "resd"
-              ExtraLength CDATA #IMPLIED>
-
-  <!-- JPEG 2000 code stream box-->
-  <!ELEMENT JPEG2000CodeStreamBox (CodeStream)>
-    <!ELEMENT CodeStream (#PCDATA)>
-    <!ATTLIST JPEG2000CodeStreamBox
-              Length CDATA #REQUIRED
-              Type CDATA #FIXED "jp2c"
-              ExtraLength CDATA #IMPLIED>
-
-  <!-- JPEG 2000 intellectual property rights box-->
-  <!ELEMENT JPEG2000IntellectualPropertyRightsBox (Content)>
-    <!ELEMENT Content (#PCDATA)>
-    <!ATTLIST JPEG2000IntellectualPropertyRightsBox
-              Length CDATA #REQUIRED
-              Type CDATA #FIXED "jp2i"
-              ExtraLength CDATA #IMPLIED>
-
-  <!-- JPEG 2000 XML box-->
-  <!ELEMENT JPEG2000XMLBox (Content)>
-    <!ATTLIST JPEG2000XMLBox
-              Length CDATA #REQUIRED
-              Type CDATA #FIXED "xml "
-              ExtraLength CDATA #IMPLIED>
-
-  <!-- JPEG 2000 UUID box-->
-  <!ELEMENT JPEG2000UUIDBox (UUID, Data)>
-    <!ELEMENT UUID (#PCDATA)>
-    <!ELEMENT Data (#PCDATA)>
-    <!ATTLIST JPEG2000UUIDBox
-              Length CDATA #REQUIRED
-              Type CDATA #FIXED "uuid"
-              ExtraLength CDATA #IMPLIED>
-
-  <!-- JPEG 2000 UUID info box-->
-  <!ELEMENT JPEG2000UUIDInfoBox (JPEG2000UUIDListBox, JPEG2000DataEntryURLBox)>
-    <!ATTLIST JPEG2000UUIDInfoBox
-              Length CDATA #REQUIRED
-              Type CDATA #FIXED "uinf"
-              ExtraLength CDATA #IMPLIED>
-
-  <!-- JPEG 2000 UUID list box-->
-  <!ELEMENT JPEG2000UUIDListBox (NumberUUID, UUID*)>
-    <!ELEMENT NumberUUID (#PCDATA)>
-    <!ATTLIST JPEG2000UUIDListBox
-              Length CDATA #REQUIRED
-              Type CDATA #FIXED "ulst"
-              ExtraLength CDATA #IMPLIED>
-
-  <!-- JPEG 2000 Data Entry URL box-->
-  <!ELEMENT JPEG2000DataEntryURLBox (Version, Flags, Location)>
-    <!ELEMENT Version (#PCDATA)>
-    <!ELEMENT Flags (#PCDATA)>
-    <!ELEMENT URL (#PCDATA)>
-    <!ATTLIST JPEG2000DataEntryURLBox
-              Length CDATA #REQUIRED
-              Type CDATA #FIXED "url "
-              ExtraLength CDATA #IMPLIED> ]
-
-

- -

XML Schema

- -The XML schema for the native image metadata format is as follows: - -
-
-<?xml version="1.0" ?>
-<!--Schema for JPEG 2000 image format -->
-
-<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
-	    xmlns="http://com.sun.media.imageio"
-	    targetNamespace="http://com.sun.media.imageio">
-
-  <!-- JPEG 2000 Image File-->
-  <xsd:element name="com_sun_media_imageio_plugins_jpeg2000_image_1.0">
-    <xsd:complexType>
-      <xsd:sequence>
-        <xsd:element ref="JPEG2000SignatureBox" />
-        <xsd:element ref="JPEG2000FileTypeBox" />
-        <!-- JPEG2000HeaderSuperBox should be before JPEG2000CodeStreamBox;
-          This is the only constraint for the sequence of these boxes -->
-        <xsd:element name="OtherBoxes">
-        <xsd:complexType>
-          <xsd:all>
-            <xsd:element ref="JPEG2000HeaderSuperBox" />
-            <xsd:element ref="JPEG2000CodeStreamBox" />
-
-            <xsd:element ref="JPEG2000IntellectualPropertyRightsBox" minOccurs="0" maxOccurs="unbounded" />
-            <xsd:element ref="JPEG2000XMLBox" minOccurs="0" maxOccurs="unbounded" />
-            <xsd:element ref="JPEG2000UUIDBox" minOccurs="0" maxOccurs="unbounded" />
-            <xsd:element ref="JPEG2000UUIDInfoBox" minOccurs="0" maxOccurs="unbounded" />
-          </xsd:all>
-        </xsd:complexType>
-        </xsd:element>
-      </xsd:sequence>
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 Signature box -->
-  <xsd:element name="JPEG2000SignatureBox">
-    <xsd:complexType>
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" fixed="12" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="jP  " />
-      <xsd:attribute name="Signature" type="xsd:hexBinary" use="required" fixed="0D0A870A" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 File type box -->
-  <xsd:element name="JPEG2000FileTypeBox">
-    <xsd:complexType>
-      <xsd:sequence>
-        <xsd:element name="Brand" type = "xsd:unsignedInt" />
-
-        <xsd:element name="MinorVersion" minOccurs="0">
-          <xsd:simpleType>
-            <xsd:restriction base="xsd:unsignedInt">
-              <xsd:enumeration value="0" />
-            </xsd:restriction>
-          </xsd:simpleType>
-        </xsd:element>
-
-        <xsd:element name="CompatibilityList" type="IntegerList" />
-      </xsd:sequence>
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="ftyp" />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 header super box-->
-  <xsd:element name="JPEG2000HeaderSuperBox">
-    <xsd:complexType>
-      <xsd:sequence>
-        <xsd:element ref="JPEG2000HeaderBox" />
-        <xsd:element name="OptionalBoxes" minOccurs="0" >
-          <xsd:complexType>
-            <xsd:all>
-              <xsd:element ref="JPEG2000BitsPerComponentBox" />
-              <xsd:element ref="JPEG2000ColorSpecificationBox" />
-              <xsd:element ref="JPEG2000PaletteBox" minOccurs="0" />
-              <xsd:element ref="JPEG2000ComponentMappingBox" minOccurs="0" />
-              <xsd:element ref="JPEG2000ChannelDefinitionBox" minOccurs="0" />
-              <xsd:element ref="JPEG2000ResolutionBox" minOccurs="0" />
-            </xsd:all>
-          </xsd:complexType>
-        </xsd:element>
-      </xsd:sequence>
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="jp2h" />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 image header box -->
-  <xsd:element name="JPEG2000HeaderBox">
-    <xsd:complexType>
-      <xsd:sequence>
-        <xsd:element name="Width" type="xsd:unsignedInt" />
-        <xsd:element name="Height" type="xsd:unsignedInt" />
-        <xsd:element name="NumComponents" type="xsd:unsignedShort" />
-        <xsd:element name="BitDepth" type="xsd:byte" />
-        <xsd:element name="CompressionType" type="xsd:unsignedByte" />
-        <xsd:element name="UnknownColorspace" type="xsd:unsignedByte" />
-        <xsd:element name="IntellectualProperty">
-          <xsd:simpleType>
-            <xsd:restriction base="xsd:unsignedByte">
-              <xsd:enumeration value="0" />
-              <xsd:enumeration value="1" />
-            </xsd:restriction>
-          </xsd:simpleType>
-        </xsd:element>
-
-      </xsd:sequence>
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" fixed="22" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="ihdr" />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 bits per component box -->
-  <xsd:element name="JPEG2000BitsPerComponentBox">
-    <xsd:complexType>
-      <xsd:sequence>
-        <xsd:element name="BitDepth" type="ByteList" />
-      </xsd:sequence>
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="bpcc" />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 color specification box -->
-  <xsd:element name="JPEG2000ColorSpecificationBox">
-    <xsd:complexType>
-      <xsd:sequence>
-
-        <xsd:element name="Method">
-          <xsd:simpleType>
-            <xsd:restriction base="xsd:unsignedByte">
-              <xsd:enumeration value="1" />
-              <xsd:enumeration value="2" />
-            </xsd:restriction>
-          </xsd:simpleType>
-        </xsd:element>
-
-        <xsd:element name="Precedence" type="xsd:byte" />
-        <xsd:element name="ApproximationAccuracy" type="xsd:byte" />
-        <xsd:element name="EnumeratedColorSpace" type="xsd:unsignedInt" />
-        <xsd:element name="ICCProfile" type="xsd:anyType" />
-
-      </xsd:sequence>
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="colr" />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 palette box -->
-  <xsd:element name="JPEG2000PaletteBox">
-    <xsd:complexType>
-      <xsd:sequence>
-
-        <xsd:element name="NumberEntries">
-          <xsd:simpleType>
-            <xsd:restriction base="xsd:unsignedShort">
-              <xsd:minInclusive value="1" />
-              <xsd:maxInclusive value="1024" />
-            </xsd:restriction>
-          </xsd:simpleType>
-        </xsd:element>
-
-        <xsd:element name="NumberColors">
-          <xsd:simpleType>
-            <xsd:restriction base="xsd:unsignedShort">
-              <xsd:minInclusive value="1" />
-              <xsd:maxInclusive value="255" />
-            </xsd:restriction>
-          </xsd:simpleType>
-        </xsd:element>
-
-        <xsd:element name="BitDepth" type="ByteList" />
-
-        <xsd:element name="LUT">
-          <xsd:complexType>
-            <xsd:sequence>
-              <xsd:element name="LUTRow" maxOccurs="unbounded" type="ByteList" />
-            </xsd:sequence>
-          </xsd:complexType>
-        </xsd:element>
-
-      </xsd:sequence>
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="pclr" />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 component mapping box-->
-  <xsd:element name="JPEG2000ComponentMappingBox">
-    <xsd:complexType>
-      <xsd:sequence maxOccurs="unbounded">
-        <xsd:element name="Component" type="xsd:unsignedShort" />
-        <xsd:element name="ComponentType" type="xsd:unsignedByte" />
-        <xsd:element name="ComponentAssociation" type="xsd:unsignedByte" />
-      </xsd:sequence>
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="cmap" />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 channel definition box-->
-  <xsd:element name="JPEG2000ChannelDefinitionBox">
-    <xsd:complexType>
-      <xsd:sequence>
-        <xsd:element name="NumberOfDefinition" type="xsd:unsignedShort" />
-        <xsd:element name="Definitions">
-          <xsd:complexType>
-            <xsd:sequence maxOccurs="unbounded">
-              <xsd:element name="ChannelNumber" type="xsd:unsignedShort" />
-              <xsd:element name="ChannelType">
-                <xsd:simpleType>
-                  <xsd:restriction base="xsd:unsignedShort">
-                    <xsd:enumeration value="0" />
-                    <xsd:enumeration value="1" />
-                    <xsd:enumeration value="2" />
-                    <xsd:enumeration value="65535" />
-                  </xsd:restriction>
-                </xsd:simpleType>
-              </xsd:element>
-              <xsd:element name="ChannelAssociation" type="xsd:unsignedShort" />
-            </xsd:sequence>
-          </xsd:complexType>
-        </xsd:element>
-      </xsd:sequence>
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="cdef" />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 resolution box-->
-  <xsd:element name="JPEG2000ResolutionBox">
-    <xsd:complexType>
-      <xsd:sequence>
-        <xsd:element ref="JPEG2000CaptureResolutionBox" minOccurs="0" />
-        <xsd:element ref="JPEG2000DefaultDisplayResolutionBox" minOccurs="0" />
-      </xsd:sequence>
-
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="res " />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 capture resolution box-->
-  <xsd:element name="JPEG2000CaptureResolutionBox">
-    <xsd:complexType>
-
-      <xsd:sequence>
-        <xsd:element name="VerticalResolutionNumerator" type="xsd:unsignedShort" />
-        <xsd:element name="VerticalResolutionDenominator" type="xsd:unsignedShort" />
-        <xsd:element name="HorizontalResolutionNumerator" type="xsd:unsignedShort" />
-        <xsd:element name="HorizontalResolutionDenominator" type="xsd:unsignedShort" />
-        <xsd:element name="VerticalResolutionExponent" type="xsd:byte" />
-        <xsd:element name="HorizontalResolutionExponent" type="xsd:byte" />
-      </xsd:sequence>
-
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" fixed ="18" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="resc" />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 default display resolution box-->
-  <xsd:element name="JPEG2000DefaultDisplayResolutionBox">
-    <xsd:complexType>
-
-      <xsd:sequence>
-        <xsd:element name="VerticalResolutionNumerator" type="xsd:unsignedShort" />
-        <xsd:element name="VerticalResolutionDenominator" type="xsd:unsignedShort" />
-        <xsd:element name="HorizontalResolutionNumerator" type="xsd:unsignedShort" />
-        <xsd:element name="HorizontalResolutionDenominator" type="xsd:unsignedShort" />
-        <xsd:element name="VerticalResolutionExponent" type="xsd:byte" />
-        <xsd:element name="HorizontalResolutionExponent" type="xsd:byte" />
-      </xsd:sequence>
-
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" fixed ="18" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="resd" />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 code stream box-->
-  <xsd:element name="JPEG2000CodeStreamBox" >
-    <xsd:complexType>
-      <xsd:sequence>
-        <xsd:element name="CodeStream" type="xsd:anyType" />
-      </xsd:sequence>
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="jp2c" />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 intellectual property rights box-->
-  <xsd:element name="JPEG2000IntellectualPropertyRightsBox" >
-    <xsd:complexType>
-      <xsd:sequence>
-        <!-- The structure of this box is defined in Part 2 so keep it
-                  general -->
-        <xsd:element name="Content" type="xsd:anyType"  />
-      </xsd:sequence>
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="jp2i" />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 XML box-->
-  <xsd:element name="JPEG2000XMLBox">
-    <xsd:complexType>
-      <xsd:sequence>
-        <xsd:element name="Content" type="xsd:string" />
-      </xsd:sequence>
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="xml " />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 UUID box-->
-  <xsd:element name="JPEG2000UUIDBox">
-    <xsd:complexType>
-      <xsd:sequence>
-        <xsd:element name="UUID">
-          <xsd:simpleType>
-            <xsd:restriction base="ByteList">
-              <xsd:length value="16" />
-            </xsd:restriction>
-          </xsd:simpleType>
-        </xsd:element>
-        <xsd:element name="Data" type="xsd:anyType" />
-      </xsd:sequence>
-
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="uuid" />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 UUID info box-->
-  <xsd:element name="JPEG2000UUIDInfoBox">
-    <xsd:complexType>
-      <xsd:sequence>
-        <xsd:element ref="JPEG2000UUIDListBox" />
-        <xsd:element ref="JPEG2000DataEntryURLBox" />
-      </xsd:sequence>
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="uinf" />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 UUID list box-->
-  <xsd:element name="JPEG2000UUIDListBox">
-    <xsd:complexType>
-      <xsd:sequence>
-        <xsd:element name="NumberUUID" type="xsd:unsignedShort" />
-        <xsd:element name="UUID" maxOccurs="unbounded">
-          <xsd:simpleType>
-            <xsd:restriction base="ByteList">
-              <xsd:length value="16" />
-            </xsd:restriction>
-          </xsd:simpleType>
-        </xsd:element>
-      </xsd:sequence>
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="ulst" />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- JPEG 2000 Data Entry URL box-->
-  <xsd:element name="JPEG2000DataEntryURLBox">
-    <xsd:complexType>
-      <xsd:sequence>
-        <xsd:element name="Version" type="xsd:unsignedByte" />
-        <xsd:element name="Flags">
-          <xsd:simpleType>
-            <xsd:restriction base="ByteList">
-              <xsd:length value="3" />
-            </xsd:restriction>
-          </xsd:simpleType>
-        </xsd:element>
-        <xsd:element name="URL" type="xsd:anyURI" />
-      </xsd:sequence>
-      <xsd:attribute name="Length" type="xsd:unsignedInt" use="required" />
-      <xsd:attribute name="Type" type="xsd:string" use="required" fixed="url " />
-      <xsd:attribute name="ExtraLength" type="LongNoLessThan16" use="optional" />
-    </xsd:complexType>
-  </xsd:element>
-
-  <!-- The basic types defined and used in JPEG 2000 schema -->
-  <xsd:simpleType name="IntegerList">
-    <xsd:list itemType="xsd:unsignedInt" />
-  </xsd:simpleType>
-
-  <xsd:simpleType name="ByteList">
-    <xsd:list itemType="xsd:byte" />
-  </xsd:simpleType>
-
-  <xsd:simpleType name="LongNoLessThan16">
-    <xsd:restriction base="xsd:long">
-      <xsd:minInclusive value="16" />
-    </xsd:restriction>
-  </xsd:simpleType>
-
-</xsd:schema>
-
- -

Standard Image Metadata Derivation

- -The conversion between the native image metadata format and the standard -image metadata format is based on the following mapping: - -
-Standard Metadata Attribute        JP2 Box Element
----------------------------        ---------------
-/Chroma
-    /ColorSpaceType
-	@name			   if UnknownColorSpace in header box is 0
-				   then if EnumeratedColorSpace in
-					color specification box is 16 --> RGB
-				        if EnumeratedColorSpace in
-                                        color specification box is 17 -->GRAY
-    /NumChannels
-	@value			   if palette box exists
-					the component number in palette box 
-				   else
-					the component number in header box
-    /Palette			   if palette box exits
-	/PaletteEntry
-	    @index		   
-	    @red		   lut[index][0]
-	    @green		   lut[index][1]
-	    @blue		   lut[index][2]
-	    @alpha 		   lut[index][3] if the component number is 4
-
-/Compression
-    @value			   "JPEG2000"
-
-/Data
-    /SampleFormat
-	@value			   if the palette box exists, -->"Index"
-				   else if bit depth in header box or 
-					bits per component box has the sign bit
-					     --> "SignedIntegral"
-					else --> "UnsignedIntegral"
-    /BitsPerSample
-	@value			   derive from the bit depth of header box
-				   or bits per component box
-    /PlanarConfiguration
-	@value			   --> "TileInterleaved"
-
-/Dimension
-    /PixelAspectRatio
-	@value			   the ratio of the horizontal and vertical
-				   resolution in the capture resolution box
-    /HorizontalPhysicalPixelSpacing
-	@value			   derived from the horizontal resolution
-				   (in pixel-per-meter) in the capture 
-				   resolution box
-    /VerticalPhysicalPixelSpacing 
-        @value                     derived from the vertical resolution         
-                                   (in pixel-per-meter) in the capture i
-				   resolution box
-/Transparency
-    /Alpha
-	@value			   --> "none" if no channel definition box or
-					no alpha channel is defined in channel
-					definition box
-				   --> "nonpremultiplied" if no premultiplied
-					channel is defined in the channel 
-					definition box
-				   --> "premultiplied" if any premultiplied
-					channel(s) defined in the channel 
-					definition box
-/Text
-    /TextEntry
-	@value			   The content of any XML box; each XML box
-				   defines a TextEntry
-
- -@since 1.0 - - diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/BitsPerComponentBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/BitsPerComponentBox.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/BitsPerComponentBox.java 2005-02-11 00:01:31.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/BitsPerComponentBox.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,91 +0,0 @@ -/* - * $RCSfile: BitsPerComponentBox.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:31 $ - * $State: Exp $ - */ - -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.metadata.IIOMetadataNode; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** This class is defined to represent a Bits Per Component Box of JPEG - * JP2 file format. A Bits Per Component box has a length, and a fixed - * type of "bpcc". Its content is a byte array containing the bit - * depths of the color components. - * - * This box is necessary only when the bit depth are not identical for all - * the components. - */ -public class BitsPerComponentBox extends Box { - /** Counstructs a BitsPerComponentBox from the provided - * byte array containing the bit depths of each color component. - */ - public BitsPerComponentBox(byte[] bitDepth) { - super(8 + bitDepth.length, 0x62706363, null); - data = bitDepth; - } - - /** Constructs a BitsPerComponentBox based on the provide - * org.w3c.dom.Node. - */ - public BitsPerComponentBox(Node node) throws IIOInvalidTreeException { - super(node); - NodeList children = node.getChildNodes(); - - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - String name = child.getNodeName(); - - if ("BitDepth".equals(name)) { - data = Box.getByteArrayElementValue(child); - } - } - } - - /** Returns the bit depths for all the image components. */ - public byte[] getBitDepth() { - return data; - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/Box.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/Box.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/Box.java 2007-09-05 16:03:20.000000000 -0400 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/Box.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,643 +0,0 @@ -/* - * $RCSfile: Box.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.6 $ - * $Date: 2007/09/05 20:03:20 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.lang.reflect.InvocationTargetException; -import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.metadata.IIOMetadataNode; - -import java.io.EOFException; -import java.io.IOException; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.StringTokenizer; - -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import javax.imageio.IIOException; -import javax.imageio.stream.ImageOutputStream; -import javax.imageio.stream.ImageInputStream; - -import com.sun.media.imageioimpl.common.ImageUtil; - -/** - * This class is defined to create the box of JP2 file format. A box has - * a length, a type, an optional extra length and its content. The subclasses - * should explain the content information. - */ -public class Box { - /** The table to link tag names for all the JP2 boxes. */ - private static Hashtable names = new Hashtable(); - - // Initializes the hash table "names". - static { - //children for the root - names.put(new Integer(0x6A502020), "JPEG2000SignatureBox"); - names.put(new Integer(0x66747970), "JPEG2000FileTypeBox"); - - // children for the boxes other than - //JPEG2000SignatureBox/JPEG2000FileTypeBox - names.put(new Integer(0x6A703269), - "JPEG2000IntellectualPropertyRightsBox"); - names.put(new Integer(0x786D6C20), "JPEG2000XMLBox"); - names.put(new Integer(0x75756964), "JPEG2000UUIDBox"); - names.put(new Integer(0x75696E66), "JPEG2000UUIDInfoBox"); - - // Children of HeadCStream - names.put(new Integer(0x6a703268), "JPEG2000HeaderSuperBox"); - names.put(new Integer(0x6a703263), "JPEG2000CodeStreamBox"); - - // Children of JPEG2000HeaderSuperBox - names.put(new Integer(0x69686472), "JPEG2000HeaderBox"); - - // Optional boxes in JPEG2000HeaderSuperBox - names.put(new Integer(0x62706363), "JPEG2000BitsPerComponentBox"); - names.put(new Integer(0x636f6c72), "JPEG2000ColorSpecificationBox"); - names.put(new Integer(0x70636c72), "JPEG2000PaletteBox"); - names.put(new Integer(0x636d6170), "JPEG2000ComponentMappingBox"); - names.put(new Integer(0x63646566), "JPEG2000ChannelDefinitionBox"); - names.put(new Integer(0x72657320), "JPEG2000ResolutionBox"); - - // Children of JPEG2000ResolutionBox - names.put(new Integer(0x72657363), "JPEG2000CaptureResolutionBox"); - names.put(new Integer(0x72657364), - "JPEG2000DefaultDisplayResolutionBox"); - - // Children of JPEG2000UUIDInfoBox - names.put(new Integer(0x756c7374), "JPEG2000UUIDListBox"); - names.put(new Integer(0x75726c20), "JPEG2000DataEntryURLBox"); - } - - /** A Hashtable contains the class names for each type of the boxes. - * This table will be used to construct a Box object from a Node object - * by using reflection. - */ - private static Hashtable boxClasses = new Hashtable(); - - // Initializes the hash table "boxClasses". - static { - //children for the root - boxClasses.put(new Integer(0x6A502020), SignatureBox.class); - boxClasses.put(new Integer(0x66747970), FileTypeBox.class); - - // children for the boxes other than - //JPEG2000SignatureBox/JPEG2000FileTypeBox - boxClasses.put(new Integer(0x6A703269), Box.class); - boxClasses.put(new Integer(0x786D6C20), XMLBox.class); - boxClasses.put(new Integer(0x75756964), UUIDBox.class); - - // Children of JPEG2000HeaderSuperBox - boxClasses.put(new Integer(0x69686472), HeaderBox.class); - - // Optional boxes in JPEG2000HeaderSuperBox - boxClasses.put(new Integer(0x62706363), BitsPerComponentBox.class); - boxClasses.put(new Integer(0x636f6c72), ColorSpecificationBox.class); - boxClasses.put(new Integer(0x70636c72), PaletteBox.class); - boxClasses.put(new Integer(0x636d6170), ComponentMappingBox.class); - boxClasses.put(new Integer(0x63646566), ChannelDefinitionBox.class); - boxClasses.put(new Integer(0x72657320), ResolutionBox.class); - - // Children of JPEG2000ResolutionBox - boxClasses.put(new Integer(0x72657363), ResolutionBox.class); - boxClasses.put(new Integer(0x72657364), ResolutionBox.class); - - // Children of JPEG2000UUIDInfoBox - boxClasses.put(new Integer(0x756c7374), UUIDListBox.class); - boxClasses.put(new Integer(0x75726c20), DataEntryURLBox.class); - } - - /** Returns the XML tag name defined in JP2 XML xsd/dtd for the box - * with the provided type. If the type is - * not known, the string "unknown" is returned. - */ - public static String getName(int type) { - String name = (String)names.get(new Integer(type)); - return name == null ? "unknown" : name; - } - - /** Returns the Box class for the box with the provided type. - */ - public static Class getBoxClass(int type) { - if (type == 0x6a703268 || type == 0x72657320) - return null; - return (Class)boxClasses.get(new Integer(type)); - } - - /** Returns the type String based on the provided name. */ - public static String getTypeByName(String name) { - Enumeration keys = names.keys(); - while (keys.hasMoreElements()) { - Integer i = (Integer)keys.nextElement(); - if (name.equals(names.get(i))) - return getTypeString(i.intValue()); - } - return null; - } - - /** Creates a Box object with the provided type - * based on the provided Node object based on reflection. - */ - public static Box createBox(int type, - Node node) throws IIOInvalidTreeException { - Class boxClass = (Class)boxClasses.get(new Integer(type)); - - try { - // gets the constructor with NodeBox instance. - e.printStackTrace(); - return new Box(node); - } catch(InvocationTargetException e) { - e.printStackTrace(); - return new Box(node); - } catch (IllegalAccessException e) { - e.printStackTrace(); - return new Box(node); - } catch (InstantiationException e) { - e.printStackTrace(); - return new Box(node); - } - - return null; - } - - /** Extracts the value of the attribute from name. */ - public static Object getAttribute(Node node, String name) { - NamedNodeMap map = node.getAttributes(); - node = map.getNamedItem(name); - return (node != null) ? node.getNodeValue() : null; - } - - /** Parses the byte array expressed by a string. */ - public static byte[] parseByteArray(String value) { - if (value == null) - return null; - - StringTokenizer token = new StringTokenizer(value); - int count = token.countTokens(); - - byte[] buf = new byte[count]; - int i = 0; - while(token.hasMoreElements()) { - buf[i++] = new Byte(token.nextToken()).byteValue(); - } - return buf; - } - - /** Parses the integer array expressed a string. */ - protected static int[] parseIntArray(String value) { - if (value == null) - return null; - - StringTokenizer token = new StringTokenizer(value); - int count = token.countTokens(); - - int[] buf = new int[count]; - int i = 0; - while(token.hasMoreElements()) { - buf[i++] = new Integer(token.nextToken()).intValue(); - } - return buf; - } - - /** Gets its String value from an IIOMetadataNode. - */ - protected static String getStringElementValue(Node node) { - - if (node instanceof IIOMetadataNode) { - Object obj = ((IIOMetadataNode)node).getUserObject(); - if (obj instanceof String) - return (String)obj; - } - - return node.getNodeValue(); - } - - /** Gets its byte value from an IIOMetadataNode. */ - protected static byte getByteElementValue(Node node) { - if (node instanceof IIOMetadataNode) { - Object obj = ((IIOMetadataNode)node).getUserObject(); - if (obj instanceof Byte) - return ((Byte)obj).byteValue(); - } - - String value = node.getNodeValue(); - if (value != null) - return new Byte(value).byteValue(); - return (byte)0; - } - - /** Gets its integer value from an IIOMetadataNode. */ - protected static int getIntElementValue(Node node) { - if (node instanceof IIOMetadataNode) { - Object obj = ((IIOMetadataNode)node).getUserObject(); - if (obj instanceof Integer) - return ((Integer)obj).intValue(); - } - - String value = node.getNodeValue(); - if (value != null) - return new Integer(value).intValue(); - return 0; - } - - /** Gets its short value from an IIOMetadataNode. */ - protected static short getShortElementValue(Node node) { - if (node instanceof IIOMetadataNode) { - Object obj = ((IIOMetadataNode)node).getUserObject(); - if (obj instanceof Short) - return ((Short)obj).shortValue(); - } - String value = node.getNodeValue(); - if (value != null) - return new Short(value).shortValue(); - return (short)0; - } - - /** Gets the byte array from an IIOMetadataNode. */ - protected static byte[] getByteArrayElementValue(Node node) { - if (node instanceof IIOMetadataNode) { - Object obj = ((IIOMetadataNode)node).getUserObject(); - if (obj instanceof byte[]) - return (byte[])obj; - } - - return parseByteArray(node.getNodeValue()); - } - - /** Gets the integer array from an IIOMetadataNode. */ - protected static int[] getIntArrayElementValue(Node node) { - if (node instanceof IIOMetadataNode) { - Object obj = ((IIOMetadataNode)node).getUserObject(); - if (obj instanceof int[]) - return (int[])obj; - } - - return parseIntArray(node.getNodeValue()); - } - - /** Copies that four bytes of an integer into the byte array. Necessary - * for the subclasses to compose the content array from the data elements - */ - public static void copyInt(byte[] data, int pos, int value) { - data[pos++] = (byte)(value >> 24); - data[pos++] = (byte)(value >> 16); - data[pos++] = (byte)(value >> 8); - data[pos++] = (byte)(value & 0xFF); - } - - /** Converts the box type from integer to string. This is necessary because - * type is defined as String in xsd/dtd and integer in the box classes. - */ - public static String getTypeString(int type) { - byte[] buf = new byte[4]; - for (int i = 3; i >= 0; i--) { - buf[i] = (byte)(type & 0xFF); - type >>>= 8; - } - - return new String(buf); - } - - /** - * Converts the box type from integer to string. This is necessary because - * type is defined as String in xsd/dtd and integer in the box classes. - */ - public static int getTypeInt(String s) { - byte[] buf = s.getBytes(); - int t = buf[0]; - for (int i = 1; i < 4; i++) { - t = (t <<8) | buf[i]; - } - - return t; - } - - /** Box length, extra length, type and content data array */ - protected int length; - protected long extraLength; - protected int type; - protected byte[] data; - - /** Constructs a Box instance using the provided - * the box type and the box content in byte array format. - * - * @param length The provided box length. - * @param type The provided box type. - * @param data The provided box content in a byte array. - * - * @throws IllegalArgumentException If the length of the content byte array - * is not length - 8. - */ - public Box(int length, int type, byte[] data) { - this.type = type; - setLength(length); - setContent(data); - } - - /** Constructs a Box instance using the provided - * the box type, the box extra length, and the box content in byte - * array format. In this case, the length of the box is set to 1, - * which indicates the extra length is meaningful. - * - * @param length The provided box length. - * @param type The provided box type. - * @param extraLength The provided box extra length. - * @param data The provided box content in a byte array. - * - * @throws IllegalArgumentException If the length of the content byte array - * is not extra length - 16. - */ - public Box(int length, int type, long extraLength, byte[] data) { - this.type = type; - setLength(length); - if (length == 1) - setExtraLength(extraLength); - setContent(data); - } - - /** Constructs a Box instance from the provided - * ImageInputStream at the specified position. - * - * @param iis The ImageInputStream contains the box. - * @param pos The position from where to read the box. - * @throws IOException If any IOException is thrown in the called read - * methods. - */ - public Box(ImageInputStream iis, int pos) throws IOException { - read(iis, pos); - } - - /** - * Constructs a Box from an "unknown" Node. This node has at - * least the attribute "Type", and may have the attribute "Length", - * "ExtraLength" and a child "Content". The child node content is a - * IIOMetaDataNode with a byte[] user object. - */ - public Box(Node node) throws IIOInvalidTreeException { - NodeList children = node.getChildNodes(); - - String value = (String)Box.getAttribute(node, "Type"); - type = getTypeInt(value); - if (value == null || names.get(new Integer(type)) == null) - throw new IIOInvalidTreeException("Type is not defined", node); - - value = (String)Box.getAttribute(node, "Length"); - if (value != null) - length = new Integer(value).intValue(); - - value = (String)Box.getAttribute(node, "ExtraLength"); - if (value != null) - extraLength = new Long(value).longValue(); - - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - if ("Content".equals(child.getNodeName())) { - if (child instanceof IIOMetadataNode) { - IIOMetadataNode cnode = (IIOMetadataNode)child; - try { - data = (byte[])cnode.getUserObject(); - } catch (Exception e) { - } - }else { - data = getByteArrayElementValue(child); - } - - if (data == null) { - value = node.getNodeValue(); - if (value != null) - data = value.getBytes(); - } - } - } - } - - /** Creates an IIOMetadataNode from this - * box. The format of this node is defined in the XML dtd and xsd - * for the JP2 image file. - */ - public IIOMetadataNode getNativeNode() { - String name = Box.getName(getType()); - if (name == null) - name = "unknown"; - - IIOMetadataNode node = new IIOMetadataNode(name); - setDefaultAttributes(node); - IIOMetadataNode child = new IIOMetadataNode("Content"); - child.setUserObject(data); - child.setNodeValue(ImageUtil.convertObjectToString(data)); - node.appendChild(child); - - return node; - } - - /** Creates an IIOMetadataNode from this - * box. The format of this node is defined in the XML dtd and xsd - * for the JP2 image file. - * - * This method is designed for the types of boxes whose XML tree - * only has 2 levels. - */ - protected IIOMetadataNode getNativeNodeForSimpleBox() { - try { - Method m = this.getClass().getMethod("getElementNames", - (Class[])null); - String[] elementNames = (String[])m.invoke(null, (Object[])null); - - IIOMetadataNode node = new IIOMetadataNode(Box.getName(getType())); - setDefaultAttributes(node); - for (int i = 0; i < elementNames.length; i++) { - IIOMetadataNode child = new IIOMetadataNode(elementNames[i]); - m = this.getClass().getMethod("get" + elementNames[i], - (Class[])null); - Object obj = m.invoke(this, (Object[])null); - child.setUserObject(obj); - child.setNodeValue(ImageUtil.convertObjectToString(obj)); - node.appendChild(child); - } - return node; - } catch (Exception e) { - throw new IllegalArgumentException(I18N.getString("Box0")); - } - } - - /** Sets the default attributes, "Length", "Type", and "ExtraLength", to - * the provided IIOMetadataNode. - */ - protected void setDefaultAttributes(IIOMetadataNode node) { - node.setAttribute("Length", Integer.toString(length)); - node.setAttribute("Type", getTypeString(type)); - - if (length == 1) { - node.setAttribute("ExtraLength", Long.toString(extraLength)); - } - } - - /** Returns the box length. */ - public int getLength() { - return length; - } - - /** Returns the box type. */ - public int getType() { - return type; - } - - /** Returns the box extra length. */ - public long getExtraLength() { - return extraLength; - } - - /** Returns the box content in byte array. */ - public byte[] getContent() { - if (data == null) - compose(); - return data; - } - - /** Sets the box length to the provided value. */ - public void setLength(int length) { - this.length = length; - } - - /** Sets the box extra length length to the provided value. */ - public void setExtraLength(long extraLength) { - if (length != 1) - throw new IllegalArgumentException(I18N.getString("Box1")); - this.extraLength = extraLength; - } - - /** Sets the box content. If the content length is not length -8 or - * extra length - 16, IllegalArgumentException will be thrown. - */ - public void setContent(byte[] data) { - if (data != null && - ((length ==1 && (extraLength - 16 != data.length)) || - (length != 1 && length - 8 != data.length))) - throw new IllegalArgumentException(I18N.getString("Box2")); - this.data = data; - if (data != null) - parse(data); - } - - /** Writes this box instance into a ImageOutputStream. */ - public void write(ImageOutputStream ios) throws IOException { - ios.writeInt(length); - ios.writeInt(type); - if (length == 1) { - ios.writeLong(extraLength); - ios.write(data, 0, (int)extraLength); - } else if (data != null) - ios.write(data, 0, length); - } - - /** Reads a box from the ImageInputStream= 8 && length < (1 << 32)) { - // Length given by L parameter. - dataLength = length - 8; - } else { - // Illegal value for L parameter. - throw new IIOException("Illegal value "+length+ - " for box length parameter."); - } - data = new byte[dataLength]; - iis.readFully(data); - iis.reset(); - } - - /** Parses the data elements from the byte array. The subclasses should - * override this method. - */ - protected void parse(byte[] data) { - } - - /** Composes the content byte array from the data elements. - */ - protected void compose() { - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ChannelDefinitionBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ChannelDefinitionBox.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ChannelDefinitionBox.java 2005-02-11 00:01:31.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ChannelDefinitionBox.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,272 +0,0 @@ -/* - * $RCSfile: ChannelDefinitionBox.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:31 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.awt.image.ColorModel; -import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.metadata.IIOMetadataNode; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** This class is designed to represent a Channel Definition Box of - * JPEG JP2 file format. A Channel Definition Box has a length, and - * a fixed type of "cdef". Its content defines the type of the image - * channels: color channel, alpha channel or premultiplied alpha channel. - */ -public class ChannelDefinitionBox extends Box { - /** The cached data elements. */ - private short num; - private short[] channels; - private short[] types; - private short[] associations; - - /** Computes the length of this box from the provided - * ColorModel. - */ - private static int computeLength(ColorModel colorModel) { - int length = colorModel.getComponentSize().length - 1; - return 10 + - (colorModel.isAlphaPremultiplied() ? length * 18 : length * 12); - } - - /** Fills the channel definitions into the arrays based on the number - * of components and isPremultiplied. - */ - public static void fillBasedOnBands(int numComps, - boolean isPremultiplied, - short[] c, - short[] t, - short[] a) { - int num = numComps * (isPremultiplied ? 3 : 2); - if (isPremultiplied) { - for (int i = numComps * 2; i < num; i++) { - c[i] = (short)(i - numComps * 2); - t[i] = 2; // 2 -- premultiplied - a[i] = (short)(i + 1 - numComps * 2); - } - } - - for (int i = 0; i < numComps; i++) { - int j = i + numComps; - c[i] = (short)i; - t[i] = 0; // The original channel - a[j] = a[i] = (short)(i + 1); - - c[j] = (short)numComps; - t[j] = 1; // 1 -- transparency - } - } - - /** Constructs a ChannelDefinitionBox based on the provided - * ColorModel. - */ - public ChannelDefinitionBox(ColorModel colorModel) { - super(computeLength(colorModel), 0x63646566, null); - - // creates the buffers for the channel definitions. - short length = (short)(colorModel.getComponentSize().length - 1); - num = (short)(length * (colorModel.isAlphaPremultiplied() ? 3 : 2)); - channels = new short[num]; - types = new short[num]; - associations = new short[num]; - - // fills the arrays. - fillBasedOnBands(length, - colorModel.isAlphaPremultiplied(), - channels, - types, - associations); - } - - /** Constructs a ChannelDefinitionBox based on the provided - * content in byte array. - */ - public ChannelDefinitionBox(byte[] data) { - super(8 + data.length, 0x63646566, data); - } - - /** Constructs a ChannelDefinitionBox based on the provided - * channel definitions. - */ - public ChannelDefinitionBox(short[] channel, short[] types, - short[] associations) { - super(10 + channel.length * 6, 0x63646566, null); - this.num = (short)channel.length; - this.channels = channel; - this.types = types; - this.associations = associations; - } - - /** Constructs a ChannelDefinitionBox based on the provided - * org.w3c.dom.Node. - */ - public ChannelDefinitionBox(Node node) throws IIOInvalidTreeException { - super(node); - NodeList children = node.getChildNodes(); - int index = 0; - - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - String name = child.getNodeName(); - - if ("NumberOfDefinition".equals(name)) { - num = Box.getShortElementValue(child); - } - - if ("Definitions".equals(name)) { - channels = new short[num]; - types = new short[num]; - associations = new short[num]; - - NodeList children1 = child.getChildNodes(); - - for (int j = 0; j < children1.getLength(); j++) { - child = children1.item(j); - name = child.getNodeName(); - if ("ChannelNumber".equals(name)) { - channels[index] = Box.getShortElementValue(child); - } - - if ("ChannelType".equals(name)) { - types[index] = Box.getShortElementValue(child); - } - - if ("Association".equals(name)) { - associations[index++] = Box.getShortElementValue(child); - } - } - } - } - } - - /** Parse the channel definitions from the content data array. */ - protected void parse(byte[] data) { - num = (short)((data[0] << 8) | data[1]); - channels = new short[num]; - types = new short[num]; - associations = new short[num]; - - for (int i = 0, j = 2; i < num; i++) { - channels[i] = - (short)(((data[j++] & 0xFF) << 8) + (data[j++] & 0xFF)); - types[i] = (short)(((data[j++] & 0xFF) << 8) + (data[j++] & 0xFF)); - associations[i] = - (short)(((data[j++] & 0xFF) << 8) + (data[j++] & 0xFF)); - } - } - - /** Returns the defined channels. */ - public short[] getChannel() { - return channels; - } - - /** Returns the channel types. */ - public short[] getTypes() { - return types; - } - - /** Returns the association which associates a color channel to a color - * component in the color space of the image. - */ - public short[] getAssociation() { - return associations; - } - - /** Creates an IIOMetadataNode from this channel definition - * box. The format of this node is defined in the XML dtd and xsd - * for the JP2 image file. - */ - public IIOMetadataNode getNativeNode() { - IIOMetadataNode node = new IIOMetadataNode(Box.getName(getType())); - setDefaultAttributes(node); - - IIOMetadataNode child = new IIOMetadataNode("NumberOfDefinition"); - child.setUserObject(new Short(num)); - child.setNodeValue("" + num); - node.appendChild(child); - - child = new IIOMetadataNode("Definitions"); - node.appendChild(child); - - for (int i = 0; i < num; i++) { - IIOMetadataNode child1 = new IIOMetadataNode("ChannelNumber"); - child1.setUserObject(new Short(channels[i])); - child1.setNodeValue("" + channels[i]); - child.appendChild(child1); - - child1 = new IIOMetadataNode("ChannelType"); - child1.setUserObject(new Short(types[i])); - child1.setNodeValue("" + types[i]); - child.appendChild(child1); - - child1 = new IIOMetadataNode("Association"); - child1.setUserObject(new Short(associations[i])); - child1.setNodeValue("" + associations[i]); - child.appendChild(child1); - } - - return node; - } - - protected void compose() { - if (data != null) - return; - int len = num * 6 + 2; - data = new byte[len]; - data[0] = (byte)(num >> 8); - data[1] = (byte)(num & 0xFF); - - for (int i = 0, j = 2; i < num; i++) { - data[j++] = (byte)(channels[i] >> 8); - data[j++] = (byte)(channels[i] & 0xFF); - - data[j++] = (byte)(types[i] >> 8); - data[j++] = (byte)(types[i] & 0xFF); - - data[j++] = (byte)(associations[i] >> 8); - data[j++] = (byte)(associations[i] & 0xFF); - } - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ColorSpecificationBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ColorSpecificationBox.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ColorSpecificationBox.java 2005-02-11 00:01:32.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ColorSpecificationBox.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,222 +0,0 @@ -/* - * $RCSfile: ColorSpecificationBox.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:32 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.awt.color.ICC_Profile; -import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.metadata.IIOMetadataNode; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** This class is defined to represent a Color Specification Box of JPEG JP2 - * file format. A Channel Definition Box has a length, and a fixed type - * of "colr". Its content contains the method to define the color space, - * the precedence and approximation accuracy (0 for JP2 files), the - * enumerated color space, and the ICC color profile if any. - */ -public class ColorSpecificationBox extends Box { - /** The enumerated color space defined in JP2 file format. */ - public static final int ECS_sRGB = 16; - public static final int ECS_GRAY = 17; - public static final int ECS_YCC = 18; - - /** Cache the element names for this box's xml definition */ - private static String[] elementNames = {"Method", "Precedence", - "ApproximationAccuracy", - "EnumeratedColorSpace", - "ICCProfile"}; - - /** This method will be called by the getNativeNodeForSimpleBox of the - * class Box to get the element names. - */ - public static String[] getElementNames() { - return elementNames; - } - - /** The elements' values. */ - private byte method; - private byte precedence; - private byte approximation; - private int ecs; - private ICC_Profile profile; - - /** Computes the length of this box when profile is present. */ - private static int computeLength(byte m, ICC_Profile profile) { - int ret = 15; - if (m == 2 && profile != null) { - ret += profile.getData().length; - } - return ret; - } - - /** Creates a ColorSpecificationBox from the provided data - * elements. - */ - public ColorSpecificationBox(byte m, byte p, byte a, int ecs, - ICC_Profile profile) { - super(computeLength(m, profile), 0x636F6C72, null); - this.method = m; - this.precedence = p; - this.approximation = a; - this.ecs = ecs; - this.profile = profile; - } - - /** Creates a ColorSpecificationBox from the provided byte - * array. - */ - public ColorSpecificationBox(byte[] data) { - super(8 + data.length, 0x636F6C72, data); - } - - /** Constructs a ColorSpecificationBox based on the provided - * org.w3c.dom.Node. - */ - public ColorSpecificationBox(Node node) throws IIOInvalidTreeException { - super(node); - NodeList children = node.getChildNodes(); - - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - String name = child.getNodeName(); - - if ("Method".equals(name)) { - method = Box.getByteElementValue(child); - } - - if ("Precedence".equals(name)) { - precedence = Box.getByteElementValue(child); - } - - if ("ApproximationAccuracy".equals(name)) { - approximation = Box.getByteElementValue(child); - } - - if ("EnumeratedColorSpace".equals(name)) { - ecs = Box.getIntElementValue(child); - } - - if ("ICCProfile".equals(name)) { - if (child instanceof IIOMetadataNode) - profile = - (ICC_Profile)((IIOMetadataNode)child).getUserObject(); - else { - String value = node.getNodeValue(); - if (value != null) - profile = ICC_Profile.getInstance(Box.parseByteArray(value)); - } - } - } - } - - /** Returns the method to define the color space. */ - public byte getMethod() { - return method; - } - - /** Returns Precedence. */ - public byte getPrecedence() { - return precedence; - } - - /** Returns ApproximationAccuracy. */ - public byte getApproximationAccuracy() { - return approximation; - } - - /** Returns the enumerated color space. */ - public int getEnumeratedColorSpace() { - return ecs; - } - - /** Returns the ICC color profile in this color specification box. */ - public ICC_Profile getICCProfile() { - return profile; - } - - /** Creates an IIOMetadataNode from this color specification - * box. The format of this node is defined in the XML dtd and xsd - * for the JP2 image file. - */ - public IIOMetadataNode getNativeNode() { - return getNativeNodeForSimpleBox(); - } - - protected void parse(byte[] data) { - method = data[0]; - precedence = data[1]; - approximation = data[2]; - if (method == 2) { - byte[] proData = new byte[data.length - 3]; - System.arraycopy(data, 3, proData, 0, data.length - 3); - profile = ICC_Profile.getInstance(proData); - } else - ecs = ((data[3] & 0xFF) << 24) | ((data[4] & 0xFF) << 16) | - ((data[5] & 0xFF) << 8) | (data[6] & 0xFF); - - } - - protected void compose() { - if (data != null) - return; - int len = 7; - byte[] profileData = null; - if (profile != null) { - profileData = profile.getData(); - len += profileData.length; - } - - data = new byte[len]; - - data[0] = (byte)method; - data[1] = (byte)precedence; - data[2] = (byte)approximation; - - copyInt(data, 3, ecs); - - if (profile != null) - System.arraycopy(profileData, 0, data, 7, len - 7); - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ComponentMappingBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ComponentMappingBox.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ComponentMappingBox.java 2005-02-11 00:01:32.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ComponentMappingBox.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,181 +0,0 @@ -/* - * $RCSfile: ComponentMappingBox.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:32 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.metadata.IIOMetadataNode; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** This class is defined to represent a Color Specification Box of JPEG JP2 - * file format. A Channel Definition Box has a length, and a fixed type - * of "cmap". This box exists if and only is a PaletteBox exists. Its - * content defines the type LUT output components and their mapping to the - * color component. - */ -public class ComponentMappingBox extends Box { - /** The data elements. */ - private short[] components; - private byte[] type; - private byte[] map; - - /** Constructs a ComponentMappingBox from the provided - * content byte array. - */ - public ComponentMappingBox(byte[] data) { - super(8 + data.length, 0x636D6170, data); - } - - /** Constructs a ComponentMappingBox from the provided - * component mapping. - */ - public ComponentMappingBox(short[] comp, byte[] t, byte[] m) { - super(8 + (comp.length << 2), 0x636D6170, null); - this.components = comp; - this.type = t; - this.map = m; - } - - /** Constructs a ComponentMappingBox based on the provided - * org.w3c.dom.Node. - */ - public ComponentMappingBox(Node node) throws IIOInvalidTreeException { - super(node); - NodeList children = node.getChildNodes(); - int len = children.getLength() / 3; - components = new short[len]; - type = new byte[len]; - map = new byte[len]; - - len *= 3; - int index = 0; - - for (int i = 0; i < len; i++) { - Node child = children.item(i); - String name = child.getNodeName(); - - if ("Component".equals(name)) { - components[index] = Box.getShortElementValue(child); - } - - if ("ComponentType".equals(name)) { - type[index] = Box.getByteElementValue(child); - } - - if ("ComponentAssociation".equals(name)) { - map[index++] = Box.getByteElementValue(child); - } - } - } - - /** Parse the component mapping from the provided content data array. */ - protected void parse(byte[] data) { - int len = data.length / 4; - components = new short[len]; - type = new byte[len]; - map = new byte[len]; - - for (int i = 0, j = 0; i < len; i++) { - components[i] = - (short)(((data[j++] & 0xFF) << 8) | (data[j++] & 0xFF)); - type[i] = data[j++]; - map[i] = data[j++]; - } - } - - /** Creates an IIOMetadataNode from this component mapping - * box. The format of this node is defined in the XML dtd and xsd - * for the JP2 image file. - */ - public IIOMetadataNode getNativeNode() { - IIOMetadataNode node = new IIOMetadataNode(Box.getName(getType())); - setDefaultAttributes(node); - - for (int i = 0; i < components.length; i++) { - IIOMetadataNode child = new IIOMetadataNode("Component"); - Short obj = new Short(components[i]); - child.setUserObject(new Short(components[i])); - child.setNodeValue("" + components[i]); - node.appendChild(child); - - child = new IIOMetadataNode("ComponentType"); - child.setUserObject(new Byte(type[i])); - child.setNodeValue("" + type[i]); - node.appendChild(child); - - child = new IIOMetadataNode("ComponentAssociation"); - child.setUserObject(new Byte(map[i])); - child.setNodeValue("" + map[i]); - node.appendChild(child); - } - - return node; - } - - public short[] getComponent() { - return components; - } - - public byte[] getComponentType() { - return type; - } - - public byte[] getComponentAssociation() { - return map; - } - - protected void compose() { - if (data != null) - return; - data = new byte[type.length << 2]; - - for (int i = 0, j = 0; i < type.length; i++) { - data[j++] = (byte)(components[i] >> 8); - data[j++] = (byte)(components[i] & 0xFF); - data[j++] = type[i]; - data[j++] = map[i]; - } - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/DataEntryURLBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/DataEntryURLBox.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/DataEntryURLBox.java 2005-02-11 00:01:32.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/DataEntryURLBox.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,154 +0,0 @@ -/* - * $RCSfile: DataEntryURLBox.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:32 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.metadata.IIOMetadataNode; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** This class is defined to represent a Data Entry URL Box of JPEG JP2 - * file format. A Data Entry URL Box has a length, and a fixed type - * of "url ". Its content are a one-byte version, a three-byte flags and - * a URL pertains to the UUID List box within its UUID Info superbox. - */ -public class DataEntryURLBox extends Box { - /** Cache the element names for this box's xml definition */ - private static String[] elementNames = {"Version", "Flags", "URL"}; - - /** This method will be called by the getNativeNodeForSimpleBox of the - * class Box to get the element names. - */ - public static String[] getElementNames() { - return elementNames; - } - - /** The element values. */ - private byte version; - private byte[] flags; - private String url; - - /** Constructs a DataEntryURLBox from its content data. */ - public DataEntryURLBox(byte[] data) { - super(8 + data.length, 0x75726C20, data); - } - - /** Constructs a DataEntryURLBox from its data elements. */ - public DataEntryURLBox(byte version, byte[] flags, String url) { - super(12 + url.length(), 0x75726C20, null); - this.version = version; - this.flags = flags; - this.url = url; - } - - /** Constructs a DataEntryURLBox from a Node. */ - public DataEntryURLBox(Node node) throws IIOInvalidTreeException { - super(node); - NodeList children = node.getChildNodes(); - - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - String name = child.getNodeName(); - - if ("Version".equals(name)) { - version = Box.getByteElementValue(child); - } - - if ("Flags".equals(name)) { - flags = Box.getByteArrayElementValue(child); - } - - if ("URL".equals(name)) { - url = Box.getStringElementValue(child); - } - } - } - - /** Parses the content of this box from its content byte array. */ - protected void parse(byte[] data) { - version = data[0]; - flags = new byte[3]; - flags[0] = data[1]; - flags[1] = data[2]; - flags[2] = data[3]; - - url = new String(data, 4, data.length - 4); - } - - /** Creates an IIOMetadataNode from this data entry URL - * box. The format of this node is defined in the XML dtd and xsd - * for the JP2 image file. - */ - public IIOMetadataNode getNativeNode() { - return getNativeNodeForSimpleBox(); - } - - /** Returns the Version data element. */ - public byte getVersion() { - return version; - } - - /** Returns the Flags data element. */ - public byte[] getFlags() { - return flags; - } - - /** Returns the URL data element. */ - public String getURL() { - return url; - } - - protected void compose() { - if (data != null) - return; - data = new byte[4 + url.length()]; - - data[0] = version; - data[1] = flags[0]; - data[2] = flags[1]; - data[3] = flags[2]; - System.arraycopy(url.getBytes(), 0, data, 4, url.length()); - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/FileTypeBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/FileTypeBox.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/FileTypeBox.java 2005-02-11 00:01:32.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/FileTypeBox.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,174 +0,0 @@ -/* - * $RCSfile: FileTypeBox.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:32 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.metadata.IIOMetadataNode; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** This class is defined to represent a File Type Box of JPEG JP2 file - * format. A File Type Box has a length, and a fixed type of "ftyp". - * - * The content of a file type box contains the brand ("jp2 " for JP2 file", - * the minor version (0 for JP2 file format), and a compatibility list (one of - * which should be "jp2 " if brand is not "jp2 ".) - */ -public class FileTypeBox extends Box { - /** Cache the element names for this box's xml definition */ - private static String[] elementNames = {"Brand", - "MinorVersion", - "CompatibilityList"}; - - /** This method will be called by the getNativeNodeForSimpleBox of the - * class Box to get the element names. - */ - public static String[] getElementNames() { - return elementNames; - } - - /** The element values. */ - private int brand; - private int minorVersion; - private int[] compatibility; - - /** Constructs a FileTypeBox from the provided brand, minor - * version and compatibility list. - */ - public FileTypeBox(int br, int minorVersion, int[] comp) { - super(16 + (comp == null ? 0 : (comp.length << 2)), 0x66747970, null); - this.brand = br; - this.minorVersion = minorVersion; - this.compatibility = comp; - } - - /** Constructs a FileTypeBox from the provided byte array. - */ - public FileTypeBox(byte[] data) { - super(8 + data.length, 0x66747970, data); - } - - /** Constructs a FileTypeBox from - * org.w3c.dom.Node. - */ - public FileTypeBox(Node node) throws IIOInvalidTreeException { - super(node); - NodeList children = node.getChildNodes(); - - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - String name = child.getNodeName(); - - if ("Brand".equals(name)) { - brand = Box.getIntElementValue(child); - } - - if ("MinorVersion".equals(name)) { - minorVersion = Box.getIntElementValue(child); - } - - if ("CompatibilityList".equals(name)) { - compatibility = Box.getIntArrayElementValue(child); - } - } - } - - /** Returns the brand of this file type box. */ - public int getBrand() { - return brand; - } - - /** Returns the minor version of this file type box. */ - public int getMinorVersion() { - return minorVersion; - } - - /** Returns the compatibilty list of this file type box. */ - public int[] getCompatibilityList() { - return compatibility; - } - - /** Creates an IIOMetadataNode from this file type box. - * The format of this node is defined in the XML dtd and xsd - * for the JP2 image file. - */ - public IIOMetadataNode getNativeNode() { - return getNativeNodeForSimpleBox(); - } - - protected void parse(byte[] data) { - if (data == null) - return; - brand = ((data[0] & 0xFF) << 24) | ((data[1] & 0xFF) << 16) | - ((data[2] & 0xFF) << 8) | (data[3] & 0xFF); - - minorVersion = ((data[4] & 0xFF) << 24) | ((data[5] & 0xFF) << 16) | - ((data[6] & 0xFF) << 8) | (data[7] & 0xFF); - - int len = (data.length - 8) / 4; - if (len > 0) { - compatibility = new int[len]; - for (int i = 0, j = 8; i < len; i++, j += 4) - compatibility[i] = ((data[j] & 0xFF) << 24) | - ((data[j+1] & 0xFF) << 16) | - ((data[j+2] & 0xFF) << 8) | - (data[j+3] & 0xFF); - } - } - - protected void compose() { - if (data != null) - return; - data = - new byte[8 + - (compatibility != null ? (compatibility.length << 2) : 0)]; - - copyInt(data, 0, brand); - copyInt(data, 4, minorVersion); - if (compatibility != null) - for (int i = 0, j = 8; i < compatibility.length; i++, j += 4) - copyInt(data, j, compatibility[i]); - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/HeaderBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/HeaderBox.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/HeaderBox.java 2005-02-11 00:01:32.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/HeaderBox.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,218 +0,0 @@ -/* - * $RCSfile: HeaderBox.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:32 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.metadata.IIOMetadataNode; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** This class is defined to represent an Image Header Box of JPEG JP2 file - * format. An Image Header Box has a length, and a fixed type of "ihdr". - * - * The content of an image header box contains the width/height, number of - * image components, the bit depth (coded with sign/unsign information), - * the compression type (7 for JP2 file), the flag to indicate the color - * space is known or not, and a flag to indicate whether the intellectual - * property information included in this file. - */ -public class HeaderBox extends Box { - /** Cache the element names for this box's xml definition */ - private static String[] elementNames = {"Height", - "Width", - "NumComponents", - "BitDepth", - "CompressionType", - "UnknownColorspace", - "IntellectualProperty"}; - - /** This method will be called by the getNativeNodeForSimpleBox of the - * class Box to get the element names. - */ - public static String[] getElementNames() { - return elementNames; - } - - /** The element values. */ - private int width; - private int height; - private short numComp; - private byte bitDepth; - private byte compressionType; - private byte unknownColor; - private byte intelProp; - - /** Create an Image Header Box from the element values. */ - public HeaderBox(int height, int width, int numComp, int bitDepth, - int compressionType, int unknownColor, int intelProp) { - super(22, 0x69686472, null); - this.height = height; - this.width = width; - this.numComp = (short)numComp; - this.bitDepth = (byte)bitDepth; - this.compressionType = (byte)compressionType; - this.unknownColor = (byte)unknownColor; - this.intelProp = (byte)intelProp; - } - - /** Create an Image Header Box using the content data. */ - public HeaderBox(byte[] data) { - super(8 + data.length, 0x69686472, data); - } - - /** Constructs an Image Header Box from a Node. */ - public HeaderBox(Node node) throws IIOInvalidTreeException { - super(node); - NodeList children = node.getChildNodes(); - - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - String name = child.getNodeName(); - - if ("Height".equals(name)) { - height = Box.getIntElementValue(child); - } - - if ("Width".equals(name)) { - width = Box.getIntElementValue(child); - } - - if ("NumComponents".equals(name)) { - numComp = Box.getShortElementValue(child); - } - - if ("BitDepth".equals(name)) { - bitDepth = Box.getByteElementValue(child); - } - - if ("CompressionType".equals(name)) { - compressionType = Box.getByteElementValue(child); - } - - if ("UnknownColorspace".equals(name)) { - unknownColor = Box.getByteElementValue(child); - } - - if ("IntellectualProperty".equals(name)) { - intelProp = Box.getByteElementValue(child); - } - } - } - - /** Parse the data elements from the byte array of the content. */ - protected void parse(byte[] data) { - height = ((data[0] & 0xFF) << 24) | - ((data[1] & 0xFF) << 16) | - ((data[2] & 0xFF) << 8) | - (data[3]& 0xFF); - width = ((data[4] & 0xFF) << 24) | - ((data[5] & 0xFF) << 16) | - ((data[6] & 0xFF) << 8) | - (data[7] & 0xFF); - numComp = (short)(((data[8] & 0xFF) << 8) | (data[9] & 0xFF)); - bitDepth = data[10]; - compressionType = data[11]; - unknownColor = data[12]; - intelProp = data[13]; - } - - /** Returns the height of the image. */ - public int getHeight() { - return height; - } - - /** Returns the width of the image. */ - public int getWidth() { - return width; - } - - /** Returns the number of image components. */ - public short getNumComponents() { - return numComp; - } - - /** Returns the compression type. */ - public byte getCompressionType() { - return compressionType; - } - - /** Returns the bit depth for all the image components. */ - public byte getBitDepth() { - return bitDepth; - } - - /** Returns the UnknowColorspace flag. */ - public byte getUnknownColorspace() { - return unknownColor; - } - - /** Returns the IntellectualProperty flag. */ - public byte getIntellectualProperty() { - return intelProp; - } - - /** Creates an IIOMetadataNode from this image header box. - * The format of this node is defined in the XML dtd and xsd - * for the JP2 image file. - */ - public IIOMetadataNode getNativeNode() { - return getNativeNodeForSimpleBox(); - } - - protected void compose() { - if (data != null) - return; - data = new byte[14]; - copyInt(data, 0, height); - copyInt(data, 4, width); - - data[8] = (byte)(numComp >> 8); - data[9] = (byte)(numComp & 0xFF); - data[10] = bitDepth; - data[11] = compressionType; - data[12] = unknownColor; - data[13] = intelProp; - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/I18N.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/I18N.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/I18N.java 2005-02-11 00:01:32.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/I18N.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,53 +0,0 @@ -/* - * $RCSfile: I18N.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:32 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import com.sun.media.imageioimpl.common.I18NImpl; - -final class I18N extends I18NImpl { - static String getString(String key) { - return getString("com.sun.media.imageioimpl.plugins.jpeg2000.I18N", key); - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/IISRandomAccessIO.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/IISRandomAccessIO.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/IISRandomAccessIO.java 2006-08-07 20:31:47.000000000 -0400 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/IISRandomAccessIO.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,235 +0,0 @@ -/* - * $RCSfile: IISRandomAccessIO.java,v $ - * - * - * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2006/08/08 00:31:47 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.io.IOException; -import java.nio.ByteOrder; -import javax.imageio.stream.ImageInputStream; -import jj2000.j2k.io.EndianType; -import jj2000.j2k.io.RandomAccessIO; - -/** - * A wrapper for converting an ImageInputStream into a - * RandomAccessIO. The resulting class is read-only. - */ -public class IISRandomAccessIO implements RandomAccessIO { - - /** The ImageInputStream that is wrapped */ - private ImageInputStream iis; - - /** - * Creates a RandomAccessIO instance from the supplied - * ImageInputStream. - * - * @param iis The source ImageInputStream. - */ - public IISRandomAccessIO(ImageInputStream iis) { - if (iis == null) { - throw new IllegalArgumentException("iis == null!"); - } - this.iis = iis; - } - - public void close() throws IOException { - iis.close(); - } - - /** - * Returns the stream position clamped to a maximum of - * Integer.MAX_VALUE. - */ - public int getPos() throws IOException { - long pos = iis.getStreamPosition(); - return pos > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)pos; - } - - public void seek(int off) throws IOException { - iis.seek(off); - } - - /** - * Returns the length of the data stream. - * - *

If the length of the ImageInputStream is not - * -1, then it is returned after being clamped to - * a maximum value of Integer.MAX_VALUE. If the - * ImageInputStream is -1, the stream - * is read to a maximum position of Integer.MAX_VALUE - * and its final position is returned. The position of the stream - * is unchanged from the value it had prior to the call.

- */ - public int length() throws IOException { - long len = iis.length(); - - // If the length is non-negative, use it. - if(len != -1L) { - return len > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)len; - } - - // If the length is negative, read until the stream ends. - iis.mark(); - int bufLen = 1024; - byte[] buf = new byte[bufLen]; - long pos = iis.getStreamPosition(); - while(pos < Integer.MAX_VALUE) { - int numRead = iis.read(buf, 0, bufLen); - if(numRead == -1) break; // EOF - pos += numRead; - } - iis.reset(); - - // Return the last position. - return pos > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)pos; - } - - public int read() throws IOException { - return iis.read(); - } - - public void readFully(byte b[], int off, int n) throws IOException { - iis.readFully(b, off, n); - } - - public int getByteOrdering() { - return iis.getByteOrder() == ByteOrder.BIG_ENDIAN ? - EndianType.BIG_ENDIAN : EndianType.LITTLE_ENDIAN; - } - - public byte readByte() throws IOException { - return iis.readByte(); - } - - public int readUnsignedByte() throws IOException { - return iis.readUnsignedByte(); - } - - public short readShort() throws IOException { - return iis.readShort(); - } - - public int readUnsignedShort() throws IOException { - return iis.readUnsignedShort(); - } - - public int readInt() throws IOException { - return iis.readInt(); - } - - public long readUnsignedInt() throws IOException { - return iis.readUnsignedInt(); - } - - public long readLong() throws IOException { - return iis.readLong(); - } - - public float readFloat() throws IOException { - return iis.readFloat(); - } - - public double readDouble() throws IOException { - return iis.readDouble(); - } - - public int skipBytes(int n) throws IOException { - return iis.skipBytes(n); - } - - /** - * A null operation as writing is not supported. - */ - public void flush() { - // Intentionally empty. - } - - /** - * Throws an IOException as writing is not supported. - */ - public void write(int b) throws IOException { - throw new IOException("Writing is not supported!"); - } - - /** - * Throws an IOException as writing is not supported. - */ - public void writeByte(int v) throws IOException { - throw new IOException("Writing is not supported!"); - } - - /** - * Throws an IOException as writing is not supported. - */ - public void writeShort(int v) throws IOException { - throw new IOException("Writing is not supported!"); - } - - /** - * Throws an IOException as writing is not supported. - */ - public void writeInt(int v) throws IOException { - throw new IOException("Writing is not supported!"); - } - - /** - * Throws an IOException as writing is not supported. - */ - public void writeLong(long v) throws IOException { - throw new IOException("Writing is not supported!"); - } - - /** - * Throws an IOException as writing is not supported. - */ - public void writeFloat(float v) throws IOException { - throw new IOException("Writing is not supported!"); - } - - /** - * Throws an IOException as writing is not supported. - */ - public void writeDouble(double v) throws IOException { - throw new IOException("Writing is not supported!"); - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ImageInputStreamWrapper.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ImageInputStreamWrapper.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ImageInputStreamWrapper.java 2005-02-11 00:01:32.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ImageInputStreamWrapper.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,104 +0,0 @@ -/* - * $RCSfile: ImageInputStreamWrapper.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:32 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.io.InputStream; -import java.io.IOException; -import javax.imageio.stream.ImageInputStream; - -/** - * This class is designed to wrap a ImageInputStream into - * a InputStream. The reason is that ImageInputStream - * implements DataInput but doesn't extend - * InputStream. However, the JJ2000 JPEG 2000 packages accepts - * a InputStream when reads a JPEG 2000 image file. - */ -public class ImageInputStreamWrapper extends InputStream { - - /** The ImageInputStream to be wrapped. */ - private ImageInputStream src; - - /** Constructs an ImageInputStreamWrapper from the provided - * ImageInputStream. - * - * @param src The ImageInputStream to be wrapped. - */ - public ImageInputStreamWrapper(ImageInputStream src) { - this.src = src; - } - - // Override the methods defined in InputStream - public int read() throws IOException { - return src.read(); - } - - public void close() throws IOException { - src.close(); - } - - public synchronized void mark(int readlimit) { - src.mark(); - } - - public boolean markSupported() { - return true; - } - - public int read(byte b[]) throws IOException { - return src.read(b, 0, b.length); - } - - public int read(byte b[], int off, int len) throws IOException { - return src.read(b, off, len); - } - - public synchronized void reset() throws IOException { - src.reset(); - } - - public long skip(long n) throws IOException { - return src.skipBytes(n); - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderCodecLib.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderCodecLib.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderCodecLib.java 2006-09-29 16:19:55.000000000 -0400 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderCodecLib.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,471 +0,0 @@ -/* - * $RCSfile: J2KImageReaderCodecLib.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.4 $ - * $Date: 2006/09/29 20:19:55 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import com.sun.media.imageio.plugins.jpeg2000.J2KImageReadParam; - -import java.awt.Point; -import java.awt.image.ColorModel; -import java.awt.image.Raster; -import java.awt.image.RenderedImage; -import java.awt.image.SampleModel; -import java.awt.image.WritableRaster; -import java.io.IOException; -import java.util.Hashtable; - -import javax.imageio.IIOException; -import javax.imageio.ImageReader; -import javax.imageio.ImageReadParam; -import javax.imageio.ImageTypeSpecifier; -import javax.imageio.metadata.IIOMetadata; -import javax.imageio.spi.ImageReaderSpi; -import javax.imageio.stream.ImageInputStream; - -import java.util.ArrayList; -import java.util.Iterator; -import javax.imageio.metadata.IIOMetadata; -import java.awt.image.BufferedImage; - -import com.sun.media.imageioimpl.common.SimpleRenderedImage; - -import com.sun.medialib.codec.jp2k.Decoder; -import com.sun.medialib.codec.jp2k.Size; -import com.sun.medialib.codec.jiio.*; - -public class J2KImageReaderCodecLib extends ImageReader { - /** Wrapper for the protected method processImageUpdate - * So it can be access from the classes which are not in - * ImageReader hierachy. - */ - public void processImageUpdateWrapper(BufferedImage theImage, - int minX, int minY, - int width, int height, - int periodX, int periodY, - int[] bands) { - processImageUpdate(theImage, - minX, minY, - width, height, - periodX, periodY, - bands); - } - - /** Wrapper for the protected method processImageProgress - * So it can be access from the classes which are not in - * ImageReader hierachy. - */ - public void processImageProgressWrapper(float percentageDone) { - processImageProgress(percentageDone); - } - - /** The input stream where reads from */ - private ImageInputStream iis = null; - - /** Stream position when setInput() was called. */ - private long streamPosition0; - - /** Indicates whether the header is read. */ - private boolean gotHeader = false; - - /** The image width. */ - private int width = -1; - - /** The image height. */ - private int height = -1; - - /** The image tile width. */ - private int tileWidth = -1; - - /** The image tile height. */ - private int tileHeight = -1; - - /** The image tile grid X offset. */ - private int tileGridXOffset = 0; - - /** The image tile grid Y offset. */ - private int tileGridYOffset = 0; - - /** Image metadata, valid for the imageMetadataIndex only. */ - private J2KMetadata imageMetadata = null; - - /** The RenderedImage decoded from the stream. */ - SimpleRenderedImage image = null; - - public J2KImageReaderCodecLib(ImageReaderSpi originator) { - super(originator); - } - - /** Overrides the method defined in the superclass. */ - public void setInput(Object input, - boolean seekForwardOnly, - boolean ignoreMetadata) { - super.setInput(input, seekForwardOnly, ignoreMetadata); - this.ignoreMetadata = ignoreMetadata; - iis = (ImageInputStream) input; // Always works - iis.mark(); // Mark the initial position. - imageMetadata = null; - try { - this.streamPosition0 = iis.getStreamPosition(); - } catch(IOException e) { - // XXX ignore - } - } - - public ImageReadParam getDefaultReadParam() { - return new J2KImageReadParam(); - } - public int getNumImages(boolean allowSearch) throws java.io.IOException { - if(input == null) { - throw new IllegalStateException(I18N.getString("J2KImageReader6")); - } else if(seekForwardOnly) { - throw new IllegalStateException(I18N.getString("J2KImageReader7")); - } - - return 1; - } - - public Iterator getImageTypes(int imageIndex) throws java.io.IOException { - checkIndex(imageIndex); - readHeader(); - if (image != null) { - ArrayList list = new ArrayList(); - list.add(new ImageTypeSpecifier(image.getColorModel(), - image.getSampleModel())); - return list.iterator(); - } - return null; - } - - public int getWidth(int imageIndex) throws java.io.IOException { - checkIndex(imageIndex); - readHeader(); - return width; - } - - public int getHeight(int imageIndex) throws java.io.IOException { - checkIndex(imageIndex); - readHeader(); - return height; - } - - public int getTileGridXOffset(int imageIndex) throws IOException { - checkIndex(imageIndex); - readHeader(); - return tileGridXOffset; - } - - public int getTileGridYOffset(int imageIndex) throws IOException { - checkIndex(imageIndex); - readHeader(); - return tileGridYOffset; - } - - public int getTileWidth(int imageIndex) throws IOException { - checkIndex(imageIndex); - readHeader(); - return tileWidth; - } - - public int getTileHeight(int imageIndex) throws IOException { - checkIndex(imageIndex); - readHeader(); - return tileHeight; - } - - /** - * Returns true if the image is organized into - * tiles, that is, equal-sized non-overlapping rectangles. - * - *

A reader plug-in may choose whether or not to expose tiling - * that is present in the image as it is stored. It may even - * choose to advertise tiling when none is explicitly present. In - * general, tiling should only be advertised if there is some - * advantage (in speed or space) to accessing individual tiles. - * Regardless of whether the reader advertises tiling, it must be - * capable of reading an arbitrary rectangular region specified in - * an ImageReadParam. - * - *

A reader for which all images are guaranteed to be tiled, - * or are guaranteed not to be tiled, may return true - * or false respectively without accessing any image - * data. In such cases, it is not necessary to throw an exception - * even if no input source has been set or the image index is out - * of bounds. - * - *

The default implementation just returns false. - * - * @param imageIndex the index of the image to be queried. - * - * @return true if the image is tiled. - * - * @exception IllegalStateException if an input source is required - * to determine the return value, but none has been set. - * @exception IndexOutOfBoundsException if an image must be - * accessed to determine the return value, but the supplied index - * is out of bounds. - * @exception IOException if an error occurs during reading. - */ - public boolean isImageTiled(int imageIndex) throws IOException { - int w = getWidth(imageIndex); - int tw = getTileWidth(imageIndex); - if(tw > 0 && ((w + tw - 1)/tw) > 1) { - return true; - } - - int h = getHeight(imageIndex); - int th = getTileHeight(imageIndex); - if(th > 0 && ((h + th - 1)/th) > 1) { - return true; - } - - return false; - } - - public IIOMetadata getStreamMetadata() throws java.io.IOException { - return null; - } - - public IIOMetadata getImageMetadata(int imageIndex) throws - java.io.IOException { - if (ignoreMetadata) - return null; - - checkIndex(imageIndex); - - if (imageMetadata == null) { - try { - iis.reset(); // Reset to initial position. - iis.mark(); // Re-mark initial position. - if (image == null || - !(image instanceof J2KRenderedImageCodecLib)) - image = new J2KRenderedImageCodecLib(iis, this, null); - imageMetadata = - ((J2KRenderedImageCodecLib)image).readImageMetadata(); - } catch(IOException ioe) { - throw ioe; - } catch(RuntimeException re) { - throw re; - } finally { - iis.reset(); // Reset to initial position. - iis.mark(); // Re-mark initial position. - } - } - return imageMetadata; - } - - public boolean isRandomAccessEasy(int imageIndex) throws IOException { - // No check done because neither input source nor image is - // required to determine the return value. - return true; - } - - public RenderedImage readAsRenderedImage(int imageIndex, - ImageReadParam param) - throws java.io.IOException { - checkIndex(imageIndex); - if (param == null) - param = getDefaultReadParam(); - clearAbortRequest(); - processImageStarted(0); - - if(param instanceof J2KImageReadParam && - ((J2KImageReadParam)param).getResolution() >= 0) { - // XXX Workaround for java.sun.com change request 5089981: - // fall back to Java reader for lower resolution levels. - // This code should be removed when this problem is fixed - // in the codecLib JPEG2000 decoder. - ImageReader jreader = new J2KImageReader(null); - iis.seek(streamPosition0); - jreader.setInput(iis); - image = - (SimpleRenderedImage)jreader.readAsRenderedImage(imageIndex, - param); - } else { - image = new J2KRenderedImageCodecLib(iis, - this, - param); - } - if (abortRequested()) - processReadAborted(); - else - processImageComplete(); - return image; - } - - public BufferedImage read(int imageIndex, - ImageReadParam param) throws java.io.IOException { - checkIndex(imageIndex); - clearAbortRequest(); - if (param == null) - param = getDefaultReadParam(); - processImageStarted(imageIndex); - - if(param instanceof J2KImageReadParam && - ((J2KImageReadParam)param).getResolution() >= 0) { - // XXX Workaround for java.sun.com change request 5089981: - // fall back to Java reader for lower resolution levels. - // This code should be removed when this problem is fixed - // in the codecLib JPEG2000 decoder. - ImageReader jreader = new J2KImageReader(null); - iis.seek(streamPosition0); - jreader.setInput(iis); - if (abortRequested()) - processReadAborted(); - else - processImageComplete(); - return jreader.read(imageIndex, param); - } - - BufferedImage bi = param.getDestination(); - iis.reset(); // Reset to initial position. - iis.mark(); // Re-mark initial position. - // XXX Need to add a try-catch IOException block and reset/mark iis. - image = new J2KRenderedImageCodecLib(iis, - this, - param); - J2KRenderedImageCodecLib jclibImage = (J2KRenderedImageCodecLib)image; - Point offset = param.getDestinationOffset(); - WritableRaster raster; - - if (bi == null) { - ColorModel colorModel = jclibImage.getColorModel(); - SampleModel sampleModel = jclibImage.getSampleModel(); - - // If the destination type is specified, use the color model of it. - ImageTypeSpecifier type = param.getDestinationType(); - if (type != null) - colorModel = type.getColorModel(); - - raster = Raster.createWritableRaster( - sampleModel.createCompatibleSampleModel(jclibImage.getMinX()+ - jclibImage.getWidth(), - jclibImage.getMinY() + - jclibImage.getHeight()), - new Point(0, 0)); - - bi = new BufferedImage(colorModel, - raster, - colorModel != null ? - colorModel.isAlphaPremultiplied() : false, - new Hashtable()); - } else { - raster = bi.getWritableTile(0, 0); - } - - jclibImage.setDestImage(bi); - jclibImage.readAsRaster(raster); - jclibImage.clearDestImage(); - - if (abortRequested()) - processReadAborted(); - else - processImageComplete(); - return bi; - } - - public Raster readRaster(int imageIndex, - ImageReadParam param) throws IOException { - BufferedImage bi = read(imageIndex, param); - return bi.getWritableTile(0, 0); - } - - public void readHeader() throws java.io.IOException { - if (gotHeader) - return; - - try { - iis.reset(); // Reset to initial position. - iis.mark(); // Re-mark initial position. - - if (image == null) - image = new J2KRenderedImageCodecLib(iis, this, null); - - this.width = image.getWidth(); - this.height = image.getHeight(); - this.tileWidth = image.getTileWidth(); - this.tileHeight = image.getTileHeight(); - this.tileGridXOffset = image.getTileGridXOffset(); - this.tileGridYOffset = image.getTileGridYOffset(); - } catch(IOException ioe) { - throw ioe; - } catch(RuntimeException re) { - throw re; - } finally { - iis.reset(); // Reset to initial position. - iis.mark(); // Re-mark initial position. - } - - this.gotHeader = true; - } - - private void checkIndex(int imageIndex) { - if(input == null) { - throw new IllegalStateException(I18N.getString("J2KImageReader6")); - } - if (imageIndex != 0) { - throw new IndexOutOfBoundsException(I18N.getString("J2KImageReader4")); - } - } - - /** This method wraps the protected method abortRequested - * to allow the abortions be monitored by J2KReadState. - */ - public boolean getAbortRequest() { - return abortRequested(); - } - - public void reset() { - super.reset(); - iis = null; - gotHeader = false; - width = -1; - height = -1; - tileWidth = -1; - tileHeight = -1; - tileGridXOffset = 0; - tileGridYOffset = 0; - imageMetadata = null; - image = null; - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderCodecLibSpi.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderCodecLibSpi.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderCodecLibSpi.java 2006-03-31 14:43:39.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderCodecLibSpi.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,171 +0,0 @@ -/* - * $RCSfile: J2KImageReaderCodecLibSpi.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.2 $ - * $Date: 2006/03/31 19:43:39 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.util.Locale; -import javax.imageio.spi.ImageReaderSpi; -import javax.imageio.stream.ImageInputStream; -import javax.imageio.spi.IIORegistry; -import javax.imageio.spi.ServiceRegistry; -import java.io.IOException; -import javax.imageio.ImageReader; -import javax.imageio.IIOException; - -import com.sun.media.imageioimpl.common.PackageUtil; - -public class J2KImageReaderCodecLibSpi extends ImageReaderSpi { - - private static String [] writerSpiNames = - {"com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriterCodecLibSpi"}; - private static String[] formatNames = - {"jpeg 2000", "JPEG 2000", "jpeg2000", "JPEG2000"}; - private static String[] extensions = - {"jp2"}; // Should add jpx or jpm - private static String[] mimeTypes = {"image/jp2", "image/jpeg2000"}; - private boolean registered = false; - - public J2KImageReaderCodecLibSpi() { - super(PackageUtil.getVendor(), - PackageUtil.getVersion(), - formatNames, - extensions, - mimeTypes, - "com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderCodecLib", - STANDARD_INPUT_TYPE, - writerSpiNames, - false, - null, null, - null, null, - true, - "com_sun_media_imageio_plugins_jpeg2000_image_1.0", - "com.sun.media.imageioimpl.plugins.jpeg2000.J2KMetadataFormat", - null, null); - } - - public void onRegistration(ServiceRegistry registry, - Class category) { - if (registered) { - return; - } - - registered = true; - - // Branch based on codecLib availability. - if(!PackageUtil.isCodecLibAvailable()) { - // Deregister provider. - registry.deregisterServiceProvider(this); - } else { - // Set pairwise ordering to give codecLib reader precedence. - Class javaReaderSPIClass = null; - try { - javaReaderSPIClass = - Class.forName("com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderSpi"); - } catch(Throwable t) { - // Ignore it. - } - - if(javaReaderSPIClass != null) { - Object javaReaderSPI = - registry.getServiceProviderByClass(javaReaderSPIClass); - if(javaReaderSPI != null) { - registry.setOrdering(category, this, javaReaderSPI); - } - } - } - } - - public String getDescription(Locale locale) { - String desc = PackageUtil.getSpecificationTitle() + - " natively-accelerated JPEG 2000 Image Reader"; - return desc; - } - - public boolean canDecodeInput(Object source) throws IOException { - if (!(source instanceof ImageInputStream)) { - return false; - } - - ImageInputStream stream = (ImageInputStream)source; - - //fix of 4938421 - stream.mark(); - int marker = (stream.read() << 8) | stream.read(); - - if (marker == 0xFF4F) { - stream.reset(); - return true; - } - - stream.reset(); - stream.mark(); - byte[] b = new byte[12]; - stream.readFully(b); - stream.reset(); - - //Verify the signature box - - // The length of the signature box is 12 - if (b[0] !=0 || b[1]!=0 || b[2] != 0 || b[3] != 12) - return false; - - // The signature box type is "jP " - if ((b[4] & 0xff) != 0x6A || (b[5] & 0xFF) != 0x50 || - (b[6] & 0xFF) !=0x20 || (b[7] & 0xFF) != 0x20) - return false; - - // The signture content is 0x0D0A870A - if ((b[8] & 0xFF) != 0x0D || (b[9] & 0xFF) != 0x0A || - (b[10] & 0xFF) != 0x87 || (b[11] &0xFF) != 0x0A) - return false; - - return true; - } - - public ImageReader createReaderInstance(Object extension) - throws IIOException { - return new J2KImageReaderCodecLib(this); - } -} - diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReader.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReader.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReader.java 2006-10-04 21:08:30.000000000 -0400 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReader.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,601 +0,0 @@ -/* - * $RCSfile: J2KImageReader.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.7 $ - * $Date: 2006/10/05 01:08:30 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.awt.Rectangle; -import java.awt.Point; - -import javax.imageio.IIOException; -import javax.imageio.ImageReader; -import javax.imageio.ImageReadParam; -import javax.imageio.ImageTypeSpecifier; -import javax.imageio.metadata.IIOMetadata; -import javax.imageio.spi.ImageReaderSpi; -import javax.imageio.stream.ImageInputStream; -import com.sun.media.imageio.plugins.jpeg2000.J2KImageReadParam; - -import java.awt.image.BufferedImage; -import java.awt.image.Raster; -import java.awt.image.RenderedImage; - -import java.io.*; -import java.util.List; -import java.util.Iterator; -import java.util.ArrayList; - -import jj2000.j2k.quantization.dequantizer.*; -import jj2000.j2k.wavelet.synthesis.*; -import jj2000.j2k.image.invcomptransf.*; -import jj2000.j2k.fileformat.reader.*; -import jj2000.j2k.codestream.reader.*; -import jj2000.j2k.entropy.decoder.*; -import jj2000.j2k.codestream.*; -import jj2000.j2k.decoder.*; -import jj2000.j2k.image.*; -import jj2000.j2k.util.*; -import jj2000.j2k.roi.*; -import jj2000.j2k.io.*; -import jj2000.j2k.*; - -/** This class is the Java Image IO plugin reader for JPEG 2000 JP2 image file - * format. It has the capability to load the compressed bilevel images, - * color-indexed byte images, or multi-band images in byte/ushort/short/int - * data type. It may subsample the image, select bands, clip the image, - * and shift the decoded image origin if the proper decoding parameter - * are set in the provided J2KImageReadParam. - */ -public class J2KImageReader extends ImageReader implements MsgLogger { - /** The input stream where reads from */ - private ImageInputStream iis = null; - - /** Stream position when setInput() was called. */ - private long streamPosition0; - - /** Indicates whether the header is read. */ - private boolean gotHeader = false; - - /** The image width. */ - private int width; - - /** The image height. */ - private int height; - - /** Image metadata, valid for the imageMetadataIndex only. */ - private J2KMetadata imageMetadata = null; - - /** The image index for the cached metadata. */ - private int imageMetadataIndex = -1; - - /** The J2K HeaderDecoder defined in jj2000 packages. Used to extract image - * header information. - */ - private HeaderDecoder hd; - - /** The J2KReadState for this reading session based on the current input - * and J2KImageReadParam. - */ - private J2KReadState readState = null; - - /** - * Whether to log JJ2000 messages. - */ - private boolean logJJ2000Msg = false; - - /** Wrapper for the protected method computeRegions. So it - * can be access from the classes which are not in ImageReader - * hierarchy. - */ - public static void computeRegionsWrapper(ImageReadParam param, - boolean allowZeroDestOffset, - int srcWidth, - int srcHeight, - BufferedImage image, - Rectangle srcRegion, - Rectangle destRegion) { - if (srcRegion == null) { - throw new IllegalArgumentException(I18N.getString("J2KImageReader0")); - } - if (destRegion == null) { - throw new IllegalArgumentException(I18N.getString("J2KImageReader1")); - } - - // Clip that to the param region, if there is one - int periodX = 1; - int periodY = 1; - int gridX = 0; - int gridY = 0; - if (param != null) { - Rectangle paramSrcRegion = param.getSourceRegion(); - if (paramSrcRegion != null) { - srcRegion.setBounds(srcRegion.intersection(paramSrcRegion)); - } - periodX = param.getSourceXSubsampling(); - periodY = param.getSourceYSubsampling(); - gridX = param.getSubsamplingXOffset(); - gridY = param.getSubsamplingYOffset(); - srcRegion.translate(gridX, gridY); - srcRegion.width -= gridX; - srcRegion.height -= gridY; - if(allowZeroDestOffset) { - destRegion.setLocation(param.getDestinationOffset()); - } else { - Point destOffset = param.getDestinationOffset(); - if(destOffset.x != 0 || destOffset.y != 0) { - destRegion.setLocation(param.getDestinationOffset()); - } - } - } - - // Now clip any negative destination offsets, i.e. clip - // to the top and left of the destination image - if (destRegion.x < 0) { - int delta = -destRegion.x*periodX; - srcRegion.x += delta; - srcRegion.width -= delta; - destRegion.x = 0; - } - if (destRegion.y < 0) { - int delta = -destRegion.y*periodY; - srcRegion.y += delta; - srcRegion.height -= delta; - destRegion.y = 0; - } - - // Now clip the destination Region to the subsampled width and height - int subsampledWidth = (srcRegion.width + periodX - 1)/periodX; - int subsampledHeight = (srcRegion.height + periodY - 1)/periodY; - destRegion.width = subsampledWidth; - destRegion.height = subsampledHeight; - - // Now clip that to right and bottom of the destination image, - // if there is one, taking subsampling into account - if (image != null) { - Rectangle destImageRect = new Rectangle(0, 0, - image.getWidth(), - image.getHeight()); - destRegion.setBounds(destRegion.intersection(destImageRect)); - if (destRegion.isEmpty()) { - throw new IllegalArgumentException - (I18N.getString("J2KImageReader2")); - } - - int deltaX = destRegion.x + subsampledWidth - image.getWidth(); - if (deltaX > 0) { - srcRegion.width -= deltaX*periodX; - } - int deltaY = destRegion.y + subsampledHeight - image.getHeight(); - if (deltaY > 0) { - srcRegion.height -= deltaY*periodY; - } - } - if (srcRegion.isEmpty() || destRegion.isEmpty()) { - throw new IllegalArgumentException(I18N.getString("J2KImageReader3")); - } - } - - /** Wrapper for the protected method checkReadParamBandSettings. - * So it can be access from the classes which are not in - * ImageReader hierarchy. - */ - public static void checkReadParamBandSettingsWrapper(ImageReadParam param, - int numSrcBands, - int numDstBands) { - checkReadParamBandSettings(param, numSrcBands, numDstBands); - } - - /** - * Convert a rectangle provided in the coordinate system of the JPEG2000 - * reference grid to coordinates at a lower resolution level where zero - * denotes the lowest resolution level. - * - * @param r A rectangle in references grid coordinates. - * @param maxLevel The highest resolution level in the image. - * @param level The resolution level of the returned rectangle. - * @param subX The horizontal subsampling step size. - * @param subY The vertical subsampling step size. - * @return The parameter rectangle converted to a lower resolution level. - * @throws IllegalArgumentException if r is null, - * maxLevel or level is negative, or - * level is greater than maxLevel. - */ - static Rectangle getReducedRect(Rectangle r, int maxLevel, int level, - int subX, int subY) { - if(r == null) { - throw new IllegalArgumentException("r == null!"); - } else if(maxLevel < 0 || level < 0) { - throw new IllegalArgumentException("maxLevel < 0 || level < 0!"); - } else if(level > maxLevel) { - throw new IllegalArgumentException("level > maxLevel"); - } - - // At the highest level; return the parameter. - if(level == maxLevel && subX == 1 && subY == 1) { - return r; - } - - // Resolution divisor is step*2^(maxLevel - level). - int divisor = 1 << (maxLevel - level); - int divX = divisor*subX; - int divY = divisor*subY; - - // Convert upper left and lower right corners. - int x1 = (r.x + divX - 1)/divX; - int x2 = (r.x + r.width + divX - 1)/divX; - int y1 = (r.y + divY - 1)/divY; - int y2 = (r.y + r.height + divY - 1)/divY; - - // Create lower resolution rectangle and return. - return new Rectangle(x1, y1, x2 - x1, y2 - y1); - } - - /** Wrapper for the protected method processImageUpdate - * So it can be access from the classes which are not in - * ImageReader hierarchy. - */ - public void processImageUpdateWrapper(BufferedImage theImage, - int minX, int minY, - int width, int height, - int periodX, int periodY, - int[] bands) { - processImageUpdate(theImage, - minX, minY, - width, height, - periodX, periodY, - bands); - } - - /** Wrapper for the protected method processImageProgress - * So it can be access from the classes which are not in - * ImageReader hierarchy. - */ - public void processImageProgressWrapper(float percentageDone) { - processImageProgress(percentageDone); - } - - /** Constructs J2KImageReader from the provided - * ImageReaderSpi. - */ - public J2KImageReader(ImageReaderSpi originator) { - super(originator); - - this.logJJ2000Msg = Boolean.getBoolean("jj2000.j2k.decoder.log"); - - FacilityManager.registerMsgLogger(null, this); - } - - /** Overrides the method defined in the superclass. */ - public void setInput(Object input, - boolean seekForwardOnly, - boolean ignoreMetadata) { - super.setInput(input, seekForwardOnly, ignoreMetadata); - this.ignoreMetadata = ignoreMetadata; - iis = (ImageInputStream) input; // Always works - imageMetadata = null; - try { - this.streamPosition0 = iis.getStreamPosition(); - } catch(IOException e) { - // XXX ignore - } - } - - /** Overrides the method defined in the superclass. */ - public int getNumImages(boolean allowSearch) throws IOException { - return 1; - } - - public int getWidth(int imageIndex) throws IOException { - checkIndex(imageIndex); - readHeader(); - return width; - } - - public int getHeight(int imageIndex) throws IOException { - checkIndex(imageIndex); - readHeader(); - return height; - } - - public int getTileGridXOffset(int imageIndex) throws IOException { - checkIndex(imageIndex); - readHeader(); - return hd.getTilingOrigin(null).x; - } - - public int getTileGridYOffset(int imageIndex) throws IOException { - checkIndex(imageIndex); - readHeader(); - return hd.getTilingOrigin(null).y; - } - - public int getTileWidth(int imageIndex) throws IOException { - checkIndex(imageIndex); - readHeader(); - return hd.getNomTileWidth(); - } - - public int getTileHeight(int imageIndex) throws IOException { - checkIndex(imageIndex); - readHeader(); - return hd.getNomTileHeight(); - } - - private void checkIndex(int imageIndex) { - if (imageIndex != 0) { - throw new IndexOutOfBoundsException(I18N.getString("J2KImageReader4")); - } - } - - public void readHeader() { - if (gotHeader) - return; - - if (readState == null) { - try { - iis.seek(streamPosition0); - } catch(IOException e) { - // XXX ignore - } - - readState = - new J2KReadState(iis, - new J2KImageReadParamJava(getDefaultReadParam()), - this); - } - - hd = readState.getHeader(); - gotHeader = true; - - this.width = hd.getImgWidth(); - this.height = hd.getImgHeight(); - } - - public Iterator getImageTypes(int imageIndex) - throws IOException { - checkIndex(imageIndex); - readHeader(); - if (readState != null) { - ArrayList list = new ArrayList(); - list.add(new ImageTypeSpecifier(readState.getColorModel(), - readState.getSampleModel())); - return list.iterator(); - } - return null; - } - - public ImageReadParam getDefaultReadParam() { - return new J2KImageReadParam(); - } - - public IIOMetadata getImageMetadata(int imageIndex) - throws IOException { - checkIndex(imageIndex); - if (ignoreMetadata) - return null; - - if (imageMetadata == null) { - iis.mark(); - imageMetadata = new J2KMetadata(iis, this); - iis.reset(); - } - return imageMetadata; - } - - public IIOMetadata getStreamMetadata() throws IOException { - return null; - } - - public BufferedImage read(int imageIndex, ImageReadParam param) - throws IOException { - checkIndex(imageIndex); - clearAbortRequest(); - processImageStarted(imageIndex); - - if (param == null) - param = getDefaultReadParam(); - - param = new J2KImageReadParamJava(param); - - if (!ignoreMetadata) { - imageMetadata = new J2KMetadata(); - iis.seek(streamPosition0); - readState = new J2KReadState(iis, - (J2KImageReadParamJava)param, - imageMetadata, - this); - } else { - iis.seek(streamPosition0); - readState = new J2KReadState(iis, - (J2KImageReadParamJava)param, - this); - } - - BufferedImage bi = readState.readBufferedImage(); - if (abortRequested()) - processReadAborted(); - else - processImageComplete(); - return bi; - } - - public RenderedImage readAsRenderedImage(int imageIndex, - ImageReadParam param) - throws IOException { - checkIndex(imageIndex); - RenderedImage ri = null; - clearAbortRequest(); - processImageStarted(imageIndex); - - if (param == null) - param = getDefaultReadParam(); - - param = new J2KImageReadParamJava(param); - if (!ignoreMetadata) { - if (imageMetadata == null) - imageMetadata = new J2KMetadata(); - ri = new J2KRenderedImage(iis, - (J2KImageReadParamJava)param, - imageMetadata, - this); - } - else - ri = new J2KRenderedImage(iis, (J2KImageReadParamJava)param, this); - if (abortRequested()) - processReadAborted(); - else - processImageComplete(); - return ri; - } - - public boolean canReadRaster() { - return true; - } - - public boolean isRandomAccessEasy(int imageIndex) throws IOException { - checkIndex(imageIndex); - return false; - } - - public Raster readRaster(int imageIndex, - ImageReadParam param) throws IOException { - checkIndex(imageIndex); - processImageStarted(imageIndex); - param = new J2KImageReadParamJava(param); - - if (!ignoreMetadata) { - imageMetadata = new J2KMetadata(); - iis.seek(streamPosition0); - readState = new J2KReadState(iis, - (J2KImageReadParamJava)param, - imageMetadata, - this); - } else { - iis.seek(streamPosition0); - readState = new J2KReadState(iis, - (J2KImageReadParamJava)param, - this); - } - - Raster ras = readState.readAsRaster(); - if (abortRequested()) - processReadAborted(); - else - processImageComplete(); - return ras; - } - - public boolean isImageTiled(int imageIndex) { - checkIndex(imageIndex); - readHeader(); - if (readState != null) { - RenderedImage image = new J2KRenderedImage(readState); - if (image.getNumXTiles() * image.getNumYTiles() > 0) - return true; - return false; - } - return false; - } - - public void reset() { - // reset local Java structures - super.reset(); - - iis = null; - gotHeader = false; - imageMetadata = null; - readState = null; - System.gc(); - } - - /** This method wraps the protected method abortRequested - * to allow the abortions be monitored by J2KReadState. - */ - public boolean getAbortRequest() { - return abortRequested(); - } - - private ImageTypeSpecifier getImageType(int imageIndex) - throws IOException { - checkIndex(imageIndex); - readHeader(); - if (readState != null) { - return new ImageTypeSpecifier(readState.getColorModel(), - readState.getSampleModel()); - } - return null; - } - - // --- Begin jj2000.j2k.util.MsgLogger implementation --- - public void flush() { - // Do nothing. - } - - public void println(String str, int flind, int ind) { - printmsg(INFO, str); - } - - public void printmsg(int sev, String msg) { - if(logJJ2000Msg) { - String msgSev; - switch(sev) { - case ERROR: - msgSev = "ERROR"; - break; - case INFO: - msgSev = "INFO"; - break; - case LOG: - msgSev = "LOG"; - break; - case WARNING: - default: - msgSev = "WARNING"; - break; - } - - processWarningOccurred("[JJ2000 "+msgSev+"] "+msg); - } - } - // --- End jj2000.j2k.util.MsgLogger implementation --- -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderResources.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderResources.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderResources.java 2005-02-11 00:01:34.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderResources.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,56 +0,0 @@ -/* - * $RCSfile: J2KImageReaderResources.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:34 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -public class J2KImageReaderResources { - static final Object[][] contents = { - }; - - public J2KImageReaderResources() {} - - public Object[][] getContents() { - return contents; - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderSpi.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderSpi.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderSpi.java 2006-03-31 14:43:39.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReaderSpi.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,167 +0,0 @@ -/* - * $RCSfile: J2KImageReaderSpi.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.2 $ - * $Date: 2006/03/31 19:43:39 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.util.Locale; -import javax.imageio.spi.ImageReaderSpi; -import javax.imageio.stream.ImageInputStream; -import javax.imageio.spi.IIORegistry; -import javax.imageio.spi.ServiceRegistry; -import java.io.IOException; -import javax.imageio.ImageReader; -import javax.imageio.IIOException; - -import com.sun.media.imageioimpl.common.PackageUtil; - -import com.sun.medialib.codec.jiio.Util; - -public class J2KImageReaderSpi extends ImageReaderSpi { - - private static String [] writerSpiNames = - {"com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriterSpi"}; - private static String[] formatNames = - {"jpeg 2000", "JPEG 2000", "jpeg2000", "JPEG2000"}; - private static String[] extensions = - {"jp2"}; // Should add jpx or jpm - private static String[] mimeTypes = {"image/jp2", "image/jpeg2000"}; - private boolean registered = false; - - public J2KImageReaderSpi() { - super(PackageUtil.getVendor(), - PackageUtil.getVersion(), - formatNames, - extensions, - mimeTypes, - "com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReader", - STANDARD_INPUT_TYPE, - writerSpiNames, - false, - null, null, - null, null, - true, - "com_sun_media_imageio_plugins_jpeg2000_image_1.0", - "com.sun.media.imageioimpl.plugins.jpeg2000.J2KMetadataFormat", - null, null); - } - - public void onRegistration(ServiceRegistry registry, - Class category) { - if (registered) { - return; - } - - registered = true; - - // Set pairwise ordering to give codecLib reader precedence. - Class codecLibReaderSPIClass = null; - try { - codecLibReaderSPIClass = - Class.forName("com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderCodecLibSpi"); - } catch(Throwable t) { - // Ignore it. - } - - if(codecLibReaderSPIClass != null) { - Object codecLibReaderSPI = - registry.getServiceProviderByClass(codecLibReaderSPIClass); - if(codecLibReaderSPI != null) { - registry.setOrdering(category, codecLibReaderSPI, this); - } - } - } - - public String getDescription(Locale locale) { - String desc = PackageUtil.getSpecificationTitle() + - " JPEG 2000 Image Reader"; - return desc; - } - - public boolean canDecodeInput(Object source) throws IOException { - if (!(source instanceof ImageInputStream)) { - return false; - } - - ImageInputStream stream = (ImageInputStream)source; - - //fix of 4938421 - stream.mark(); - int marker = (stream.read() << 8) | stream.read(); - - if (marker == 0xFF4F) { - stream.reset(); - return true; - } - - stream.reset(); - stream.mark(); - byte[] b = new byte[12]; - stream.readFully(b); - stream.reset(); - - //Verify the signature box - - // The length of the signature box is 12 - if (b[0] !=0 || b[1]!=0 || b[2] != 0 || b[3] != 12) - return false; - - // The signature box type is "jP " - if ((b[4] & 0xff) != 0x6A || (b[5] & 0xFF) != 0x50 || - (b[6] & 0xFF) !=0x20 || (b[7] & 0xFF) != 0x20) - return false; - - // The signture content is 0x0D0A870A - if ((b[8] & 0xFF) != 0x0D || (b[9] & 0xFF) != 0x0A || - (b[10] & 0xFF) != 0x87 || (b[11] &0xFF) != 0x0A) - return false; - - return true; - } - - public ImageReader createReaderInstance(Object extension) - throws IIOException { - return new J2KImageReader(this); - } -} - diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReadParamJava.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReadParamJava.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReadParamJava.java 2005-02-11 00:01:33.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageReadParamJava.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,166 +0,0 @@ -/* - * $RCSfile: J2KImageReadParamJava.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:33 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import javax.imageio.ImageReadParam; -import com.sun.media.imageio.plugins.jpeg2000.J2KImageReadParam; -/** - * A subclass of ImageReadParam for reading images in - * the JPEG 2000 format. - * - *

The decoding parameters for JPEG 2000 are listed below: - * - *

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
JPEG 2000 Plugin Decoding Parameters
Parameter Name Description
decodingRateSpecifies the decoding rate in bits per pixel (bpp) where the - * number of pixels is related to the image's original size (Note: - * this parameter is not affected by resolution). The - * codestream is either parsed (default) or truncated depending - * parsingEnabled. The default is Double.MAX_VALUE. - * It means decoding with the encoding rate. - *
resolutionSpecifies the resolution level wanted for the decoded image - * (0 means the lowest available resolution, the resolution - * level gives an image with the original dimension). If the given index - * is greater than the number of available resolution levels of the - * compressed image, the decoded image has the lowest available - * resolution (among all tile-components). This parameter affects only - * the inverse wavelet transform and not the number of bytes read by the - * codestream parser, which depends only on decodingRate. - *
noROIDescalingEnsures that no ROI de-scaling is performed. Decompression is done - * like there is no ROI in the image. - *
parsingEnabledEnable the parsing mode or not when the decoding rate is specified. - * If it is false, the codestream is decoded as if it were truncated to - * the given rate. If it is true, the decoder creates, truncates and - * decodes a virtual layer progressive codestream with the same - * truncation points in each code-block. - *
- */ -public class J2KImageReadParamJava extends J2KImageReadParam { - - /** Ensures that no ROI de-scaling is performed. Decompression - * is done like there is no ROI in the image. - */ - private boolean noROIDescaling = true; - - /** Enable the parsing mode or not when the decoding rate is specified . - * If it is false, the codestream is decoded as if it were truncated to - * the given rate. If it is true, the decoder creates, truncates and - * decodes a virtual layer progressive codestream with the same - * truncation points in each code-block. - */ - private boolean parsingEnabled = true; - - /** Constructs a default instance of J2KImageReadParamJava. */ - public J2KImageReadParamJava() { - super(); - } - - public J2KImageReadParamJava(ImageReadParam param) { - super(); - - // Generic settings. - if(param.hasController()) { - setController(param.getController()); - } - setSourceRegion(param.getSourceRegion()); - setSourceBands(param.getSourceBands()); - setDestinationBands(param.getDestinationBands()); - setDestination(param.getDestination()); - - setDestinationOffset(param.getDestinationOffset()); - setSourceSubsampling(param.getSourceXSubsampling(), - param.getSourceYSubsampling(), - param.getSubsamplingXOffset(), - param.getSubsamplingYOffset()); - setDestinationType(param.getDestinationType()); - - // J2K settings. - J2KImageReadParam j2kParam; - if(param instanceof J2KImageReadParam) { - j2kParam = (J2KImageReadParam)param; - } else { - j2kParam = new J2KImageReadParam(); - } - setDecodingRate(j2kParam.getDecodingRate()); - setResolution(j2kParam.getResolution()); - } - - /** Sets noROIDescaling */ - public void setNoROIDescaling(boolean value) { - this.noROIDescaling = value; - } - - /** Gets noROIDescaling */ - public boolean getNoROIDescaling() { - return noROIDescaling; - } - - /** Sets parsingEnabled */ - public void setParsingEnabled(boolean value) { - this.parsingEnabled = value; - } - - /** Gets parsingEnabled */ - public boolean getParsingEnabled() { - return parsingEnabled; - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriteParamJava.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriteParamJava.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriteParamJava.java 2006-09-20 19:23:30.000000000 -0400 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriteParamJava.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,1297 +0,0 @@ -/* - * $RCSfile: J2KImageWriteParamJava.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.2 $ - * $Date: 2006/09/20 23:23:30 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.awt.Rectangle; -import java.awt.image.Raster; -import java.awt.image.RenderedImage; -import java.util.Collections; -import java.util.Locale; -import java.util.Iterator; -import javax.imageio.IIOImage; -import javax.imageio.ImageWriteParam; -import jj2000.j2k.*; -import jj2000.j2k.roi.*; -import jj2000.j2k.quantization.*; -import jj2000.j2k.wavelet.analysis.AnWTFilterSpec; -import jj2000.j2k.image.forwcomptransf.ForwCompTransfSpec; -import jj2000.j2k.entropy.CBlkSizeSpec; -import jj2000.j2k.entropy.PrecinctSizeSpec; -import jj2000.j2k.entropy.ProgressionSpec; -import jj2000.j2k.image.BlkImgDataSrc; -import jj2000.j2k.entropy.encoder.LayersInfo; -import com.sun.media.imageio.plugins.jpeg2000.J2KImageWriteParam; - -/** - * A subclass of ImageWriteParam for writing images in - * the JPEG 2000 format. - * - *

JPEG 2000 plugin supports to losslessly or lossy compress gray-scale, - * RGB, and RGBA images with byte, unsigned short or short data type. It also - * supports losslessly compress bilevel, and 8-bit indexed. The result data - * is in the format of JP2 (JPEG 2000 Part 1 or baseline format). - * - *

Many encoding parameters for JPEG 2000 can be tile-component specific. - * These parameters are marked as Yes in the column - * TC_SPEC in the following parameter table. - * They must be provided according to the pattern: - * [<tile-component idx>] <param> (repeated as many time as needed), - * where <tile-component idx> respect the following policy according to - * the degree of priority: - * - * - * - * - * - *
(1) t<idx> c<idx> : Tile-component specification.
(2) t<idx> : Tile specification.
(3) c<idx> : Component specification.
(4) <void> : Default specification.
- *

Where the priorities of the specifications are: - * (1) > (2) > (3) > (4), (">" means "overrides") - * <idx>: "," separates indexes, "-" separates bounds of indexes list. - * (for example, 0,2-4 means indexes 0,2,3 and 4). - * - *

The parameters for encoding JPEG 2000 are listed in the following table: - * - * *

- * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
JPEG 2000 Plugin Decoding Parameters
Parameter Name DescriptionTC_SPEC
encodingRate The bitrate in bits-per-pixel for encoding. Should be set when - * lossy compression scheme is used. With the default value - * Double.MAX_VALUE, a lossless compression will be done. - * No
lossless Indicates using the loseless scheme or not. It is equivalent to - * use reversible quantization and 5x3 integer wavelet filters. The - * default is true. - * No
componentTransformation Specifies to utilize the component transformation on some tiles. - * If the wavelet transform is reversible (w5x3 filter), the Reversible - * Component Transformation (RCT) is applied. If not reversible - * (w9x7 filter), the Irreversible Component Transformation (ICT) is used. - * Yes, Tile_Specific
filters Specifies which wavelet filters to use for the specified - * tile-components. JPEG 2000 part I only supports w5x3 and w9x7 filters. - * Yes
decompositionLevel Specifies the wavelet decomposition levels to apply to - * the image. If it is 0, no wavelet transform is performed, in which - * case the original image data will be sent to the encoder and an example - * is the binary data. All components and all tiles have the same number - * of decomposition levels. The default value is 5. - * No
guardBits The number of bits used for each tile-component in the quantizer - * to avoid overflow. It takes values in the range 0 through 7. The - * default value is 2. - * Yes
quantizationStep This parameter specifies the base normalized quantization step - * size for the tiles/components. It is normalized to a dynamic range - * of 1 in the image domain. This parameter is ignored in reversible - * coding. The default value is 0.0078125. - * Yes
quantizationType Specifies which quantization type to use for specified - * tiles/components. Not specified for lossless compression. By default, - * the quantization step size is "expounded". Supported quantization - * types specification are : "reversible" (no quantization), "derived" - * (derived quantization step size) and "expounded". - * Yes
codeBlockSize Specifies the maximum code-block size to use for tile-component. - * The maximum width and height is 1024, however the block size - * (i.e. width x height) must not exceed 4096. The minimum width and - * height is 4. The default values are (64, 64). - * Yes
progressionType Specifies which type of progression should be used when generating - * the codestream. - *

The format is [<tile index>] - * res|layer|res-pos|pos-comp|comp-pos [res_start comp_start layer_end - * res_end comp_end prog] [[res_start comp_start layer_end res_end - * comp_end prog]...] [[<tile-component idx]...]. - *

The value "res" generates a resolution progressive - * codestream with the number of layers specified by "layers" parameter. - * The value "layer" generates a layer progressive codestream with - * multiple layers. In any case, the rate-allocation algorithm optimizes - * for best quality in each layer. The quality measure is mean squared - * error (MSE) or a weighted version of it (WMSE). If no progression - * type is specified or imposed by other parameters, the default value - * is "layer". It is also possible to describe progression order - * changes. In this case, "res_start" is the index (from 0) of the - * first resolution level, "comp_start" is the index (from 0) of the - * first component, "layer_end" is the index (from 0) of the first layer - * not included, "res_end" is the index (from 0) of the first - * resolution level not included, "comp_end" is index (from 0) of - * the first component not included and "prog" is the progression type - * to be used for the rest of the tile/image. Several progression - * order changes can be specified, one after the other. - *

Yes
packPacketHeaderInTile Indicates that the packet headers are packed in the tiles' headers. - * The default is false. - * No
packPacketHeaderInMain Indicates that the packet headers are packed in the main header. - * The default is false. - * No
packetPerTilePart Specifies the maximum number of packets to be put into one tile-part. - * Zero means putting all packets in the first tile-part of each tile. - * No
ROIs Specifies ROIs shape and location. The component index specifies - * which components contain the ROI. If this parameter is used, the - * codestream is layer progressive by default unless it is overridden by - * the progressionType. A rectanglar or circular ROI can be - * specified in the format: [<component idx>] R <left> - * <top> <width> <height> or [<component idx>] C - * <center x> <center y> <radius>. An arbitrary shape - * can be assigned by [<component idx>] A <PGM file> - * Yes, component-specified
startLevelROI This parameter defines the lowest resolution levels to belong to - * the ROI. By doing this, it is possible to avoid getting - * information for the ROI at an early stage of transmission. - * startLevelROI = 0 means the lowest resolution level belongs to - * the ROI, 1 means the second lowest etc. The default values, -1, - * deactivates this parameter. - * No
alignROI By specifying this parameter, the ROI mask will be limited to - * covering only entire code-blocks. The ROI coding can then be - * performed without any actual scaling of the coefficients but by - * instead scaling the distortion estimates. - * No
bypass Uses the lazy coding mode with the entropy coder. This will bypass - * the MQ coder for some of the coding passes, where the distribution - * is often close to uniform. Since the MQ codeword will be terminated - * at least once per lazy pass, it is important to use an efficient - * termination algorithm, methodForMQTermination. - * true enables, and false disables it. The default value is false. - * Yes
resetMQ If this is enabled the probability estimates of the MQ coder are - * reset after each arithmetically coded (i.e. non-lazy) coding pass. - * true enables, and false disables it. The default value is false. - * Yes
terminateOnByte If this is enabled the codeword (raw or MQ) is terminated on a byte - * boundary after each coding pass. In this case it is important to use - * an efficient termination algorithm, "methodForMQTermination". - * true enables, and false disables it. The default value is false. - * Yes
causalCXInfo Uses vertically stripe causal context formation. If this is - * enabled the context formation process in one stripe is independant of - * the next stripe (i.e. the one below it). true enables, and false - * disables it. The default value is false. - * Yes
codeSegSymbol Inserts an error resilience segmentation symbol in the MQ codeword - * at the end of each bit-plane (cleanup pass). Decoders can use this - * information to detect and conceal errors. true enables, and false - * disables it. The default value is false. - * Yes
methodForMQTermination Specifies the algorithm used to terminate the MQ codeword. The - * most efficient one is "near_opt", which delivers a codeword which - * in almost all cases is the shortest possible. The "easy" is a - * simpler algorithm that delivers a codeword length that is close - * to the previous one (in average 1 bit longer). The "predict" is - * almost the same as the "easy" but it leaves error resilient - * information on the spare least significant bits (in average 3.5 bits), - * which can be used by a decoder to detect errors. The "full" algorithm - * performs a full flush of the MQ coder and is highly inefficient. It - * is important to use a good termination policy since the MQ codeword - * can be terminated quite often, specially if the "bypass" or - * "terminateOnByte" parameters are enabled (in the normal case it would - * be terminated once per code-block, while "terminateOnByte" is specified - * it will be done almost 3 times per bit-plane in each code-block). - * The default value is "near_opt". - * Yes
methodForMQLengthCalc Specifies the algorithm to use in calculating the necessary MQ - * length for each decoding pass. The best one is "near_opt", which - * performs a rather sophisticated calculation and provides the best - * results. The "lazy_good" and "lazy" are very simple algorithms - * that provide rather conservative results. "lazy_good" performs - * slightly better. Please use the default unless the experiments - * show the benefits of different length calculation algorithms. - * The default value is "near_opt". - * Yes
precinctPartition Specifies precinct partition dimensions for tiles/components. They - * are stored from those applied to the highest resolution to those - * applied to the remaining resolutions in decreasing order. If less - * values than the number of decomposition levels are specified, then - * the last two values are used for the remaining resolutions. - * Yes
layers Explicitly specifies the codestream layer formation parameters. - * The rate (double) parameter specifies the bitrate to which the first - * layer should be optimized. The layers (int) parameter, if present, - * specifies the number of extra layers that should be added for - * scalability. These extra layers are not optimized. Any extra rate - * and layers parameters add more layers, in the same way. An - * additional layer is always added at the end, which is optimized - * to the overall target bitrate of the bit stream. Any layers - * (optimized or not) whose target bitrate is higher that the overall - * target bitrate are silently ignored. The bitrates of the extra layers - * that are added through the layers parameter are approximately - * log-spaced between the other target bitrates. If several (rate, layers) - * constructs appear the rate parameters must appear in increasing order. - * The rate allocation algorithm ensures that all coded layers have a - * minimal reasonable size, if not these layers are silently ignored. - * Default: 0.015 +20 2.0 +10. - * No
SOPSpecifies whether start of packet (SOP) markers should be used. - * true enables, false disables it. The default value is false. - * Yes
EPHSpecifies whether end of packet header (EPH) markers should be used. - * true enables, false disables it. The default value is false. - * Yes
- */ -public class J2KImageWriteParamJava extends ImageWriteParam { - /** - * Indicates that the packet headers are packed in the tiles' headers. - */ - private boolean packPacketHeaderInTile = false; - - /** - * Indicates that the packet headers are packed in the main header. - */ - private boolean packPacketHeaderInMain = false; - - /** - * Specifies the maximum number of packets to be put into one tile-part. - * Zero means include all packets in first tile-part of each tile. - */ - private int packetPerTilePart = 0; - - /** - * The bitrate in bits-per-pixel for encoding. Should be set when lossy - * compression scheme is used. The default is - * Double.MAX_VALUE. - */ - private double encodingRate = Double.MAX_VALUE; - - /** - * Indicates using the loseless scheme or not. It is equivalent to - * use reversible quantization and 5x3 integer wavelet filters. - */ - private boolean lossless = true; - - /** Specifies to utilize the component transformation with some tiles. - * If the wavelet transform is reversible (w5x3 filter), the - * Reversible Component Transformation (RCT) is applied. If not reversible - * (w9x7 filter), the Irreversible Component Transformation (ICT) - * is used. - */ - private ForwCompTransfSpec componentTransformation = null; - private boolean enableCT = true; - - /** Specifies which filters to use for the specified tile-components. - * JPEG 2000 part I only supports w5x3 and w9x7 filters. - */ - private AnWTFilterSpec filters = null; - - /** Specifies the number of wavelet decomposition levels to apply to - * the image. If it is 0, no wavelet transform is performed, in which - * case the original image data will be sent to the encoder and an - * example is the binary data. All components and all tiles have - * the same number of decomposition levels. Default: 5. - */ - private IntegerSpec decompositionLevel = null; // = 5; - - /** The number of bits used for each tile-component in - * the quantizer to avoid overflow. It takes values in the range 0 - * through 7. Default: 2. - */ - private GuardBitsSpec guardBits = null; - - /** This parameter specifies the base normalized quantization step - * size for the tiles/components. It is normalized to a dynamic range - * of 1 in the image domain. This parameter is ignored in reversible - * coding. Default: 0.0078125. - */ - private QuantStepSizeSpec quantizationStep = null; - - /** Specifies which quantization type to use for specified - * tiles/components. Not specified for lossless compression. By - * default , the quantization step size is "expounded". Supported - * quantization types specification are : "reversible" (no quantization), - * "derived" (derived quantization step size) and "expounded". - */ - private QuantTypeSpec quantizationType = null; - - /** This parameter defines the lowest resolution levels to belong to - * the ROI. By doing this, it is possible to avoid only getting - * information for the ROI at an early stage of transmission. - * startLevelROI = 0 means the lowest resolution level belongs to - * the ROI, 1 means the second lowest etc. The default values, -1, - * deactivates this parameter. - */ - private int startLevelROI = -1; - - /** By specifying this parameter, the ROI mask will be limited to - * covering only entire code-blocks. The ROI coding can then be - * performed without any actual scaling of the coefficients but - * by instead scaling the distortion estimates. - */ - private boolean alignROI = false; - - /** Specifies ROIs shape and location. The component index specifies - * which components contain the ROI. If this parameter is used, the - * codestream is layer progressive by default unless it is - * overridden by the progressionType. - */ - private MaxShiftSpec ROIs = null; - - /** Specifies the maximum code-block size to use for tile-component. - * The maximum width and height is 1024, however the image area - * (i.e. width x height) must not exceed 4096. The minimum - * width and height is 4. Default: 64 64. - */ - private CBlkSizeSpec codeBlockSize = null; - - /** Uses the lazy coding mode with the entropy coder. This will bypass - * the MQ coder for some of the coding passes, where the distribution - * is often close to uniform. Since the MQ codeword will be terminated - * at least once per lazy pass, it is important to use an efficient - * termination algorithm, methodForMQTermination. - * true enables, and false disables it. Default: false. - */ - private StringSpec bypass = null; - - /** If this is enabled the probability estimates of the MQ coder are - * reset after each arithmetically coded (i.e. non-lazy) coding pass. - * true enables, and false disables it. Default: false. - */ - private StringSpec resetMQ = null; - - /** If this is enabled the codeword (raw or MQ) is terminated on a byte - * boundary after each coding pass. In this case it is important to - * use an efficient termination algorithm, the "methodForMQTermination". - * true enables, and false disables it. Default: false. - */ - private StringSpec terminateOnByte = null; - - /** Uses vertically stripe causal context formation. If this is - * enabled the context formation process in one stripe is independant - * of the next stripe (i.e. the one below it). true enables, and - * false disables it. Default: false. - */ - private StringSpec causalCXInfo = null; - - /** Inserts an error resilience segmentation symbol in the MQ codeword - * at the end of each bit-plane (cleanup pass). Decoders can use this - * information to detect and conceal errors. true enables, - * and false disables it. Default: false. - */ - private StringSpec codeSegSymbol = null; - - /** Specifies the algorithm used to terminate the MQ codeword. The - * most efficient one is "near_opt", which delivers a codeword which - * in almost all cases is the shortest possible. The "easy" is a - * simpler algorithm that delivers a codeword length that is close - * to the previous one (in average 1 bit longer). The "predict" is - * almost the same as the "easy" but it leaves error resilient - * information on the spare least significant bits (in average - * 3.5 bits), which can be used by a decoder to detect errors. - * The "full" algorithm performs a full flush of the MQ coder and - * is highly inefficient. It is important to use a good termination - * policy since the MQ codeword can be terminated quite often, - * specially if the "bypass" or "terminateOnByte" parameters are - * enabled (in the normal case it would be terminated once per - * code-block, while "terminateOnByte" is specified it will be - * done almost 3 times per bit-plane in each code-block). - * Default: near_opt. - */ - private StringSpec methodForMQTermination = null; - - /** Specifies the algorithm to use in calculating the necessary MQ - * length for each decoding pass. The best one is "near_opt", which - * performs a rather sophisticated calculation and provides the best - * results. The "lazy_good" and "lazy" are very simple algorithms - * that provide rather conservative results. "lazy_good" performs - * slightly better. Please use the default unless the experiments - * show the benefits of different length calculation algorithms. - * Default: near_opt. - */ - private StringSpec methodForMQLengthCalc = null; - - /** Specifies precinct partition dimensions for tiles/components. They - * are stored from those applied to the highest resolution to those - * applied to the remaining resolutions in decreasing order. If less - * values than the number of decomposition levels are specified, then - * the last two values are used for the remaining resolutions. - */ - private PrecinctSizeSpec precinctPartition = null; - - /** Specifies which type of progression should be used when generating - * the codestream. The value "res" generates a resolution progressive - * codestream with the number of layers specified by "layers" parameter. - * The value "layer" generates a layer progressive codestream with - * multiple layers. In any case, the rate-allocation algorithm optimizes - * for best quality in each layer. The quality measure is mean squared - * error (MSE) or a weighted version of it (WMSE). If no progression - * type is specified or imposed by other modules, the default value - * is "layer". It is also possible to describe progression order - * changes. In this case, "res_start" is the index (from 0) of the - * first resolution level, "comp_start" is the index (from 0) of the - * first component, "ly_end" is the index (from 0) of the first layer - * not included, "res_end" is the index (from 0) of the first - * resolution level not included, "comp_end" is index (from 0) of - * the first component not included and "prog" is the progression type - * to be used for the rest of the tile/image. Several progression - * order changes can be specified, one after the other. - */ - private ProgressionSpec progressionType = null; - - /** - * The specified (tile-component) progression. Will be used to generate - * the progression type. - */ - private String progressionName = null; - - /** Explicitly specifies the codestream layer formation parameters. - * The rate (double) parameter specifies the bitrate to which the first - * layer should be optimized. The layers (int) parameter, if present, - * specifies the number of extra layers that should be added for - * scalability. These extra layers are not optimized. Any extra rate - * and layers parameters add more layers, in the same way. An - * additional layer is always added at the end, which is optimized - * to the overall target bitrate of the bit stream. Any layers - * (optimized or not) whose target bitrate is higher that the - * overall target bitrate are silently ignored. The bitrates of - * the extra layers that are added through the layers parameter - * are approximately log-spaced between the other target bitrates. - * If several (rate, layers) constructs appear the rate parameters - * must appear in increasing order. The rate allocation algorithm - * ensures that all coded layers have a minimal reasonable size, - * if not these layers are silently ignored. Default: 0.015 +20 2.0 +10. - */ - private String layers = "0.015 +20 2.0 +10"; - - /** Specifies whether end of packet header (EPH) markers should be used. - * true enables, false disables it. Default: false. - */ - private StringSpec EPH = null; - - /** Specifies whether start of packet (SOP) markers should be used. - * true enables, false disables it. Default: false. - */ - private StringSpec SOP = null; - - private int numTiles; - private int numComponents; - - private RenderedImage imgsrc; - private Raster raster; - - private int minX; - private int minY; - - /** Constructor to set locales. */ - public J2KImageWriteParamJava(RenderedImage imgsrc, Locale locale) { - super(locale); - setDefaults(imgsrc); - } - - /** Constructor to set locales. */ - public J2KImageWriteParamJava(IIOImage image, ImageWriteParam param) { - super(param.getLocale()); - if(image != null) { - if (image.hasRaster()) - setDefaults(image.getRaster()); - else - setDefaults(image.getRenderedImage()); - } - - setSourceRegion(param.getSourceRegion()); - setSourceBands(param.getSourceBands()); - try { - setTiling(param.getTileWidth(), param.getTileHeight(), - param.getTileGridXOffset(), param.getTileGridYOffset()); - } catch (IllegalStateException e) { - // tileing is not set do nothing. - } - - setDestinationOffset(param.getDestinationOffset()); - setSourceSubsampling(param.getSourceXSubsampling(), - param.getSourceYSubsampling(), - param.getSubsamplingXOffset(), - param.getSubsamplingYOffset()); - setDestinationType(param.getDestinationType()); - - J2KImageWriteParam j2kParam; - if(param instanceof J2KImageWriteParam) { - j2kParam = (J2KImageWriteParam)param; - } else { - j2kParam = new J2KImageWriteParam(); - } - - setDecompositionLevel(""+j2kParam.getNumDecompositionLevels()); - setEncodingRate(j2kParam.getEncodingRate()); - setLossless(j2kParam.getLossless()); - setFilters(j2kParam.getFilter()); - setEPH("" + j2kParam.getEPH()); - setSOP("" + j2kParam.getSOP()); - setProgressionName(j2kParam.getProgressionType()); - int[] size = j2kParam.getCodeBlockSize(); - setCodeBlockSize("" + size[0] +" " + size[1]); - enableCT = j2kParam.getComponentTransformation(); - setComponentTransformation("" + enableCT); - } - - - /** - * Constructs a J2KImageWriteParamJava object with default - * values for all parameters. - */ - public J2KImageWriteParamJava() { - super(); - setSuperProperties(); - } - - /** - * Constructs a J2KImageWriteParamJava object with default - * values for all parameters. - */ - public J2KImageWriteParamJava(RenderedImage imgsrc) { - super(); - setDefaults(imgsrc); - } - - /** - * Constructs a J2KImageWriteParamJava object with default - * values for all parameters. - */ - public J2KImageWriteParamJava(Raster raster) { - super(); - setDefaults(raster); - } - - private void setSuperProperties() { - canOffsetTiles = true; - canWriteTiles = true; - canOffsetTiles = true; - canWriteProgressive = true; - tilingMode = MODE_EXPLICIT; - } - - /** Set source */ - private void setDefaults(Raster raster) { - // override the params in the super class - setSuperProperties(); - - if (raster != null) { - this.raster = raster; - tileGridXOffset = raster.getMinX(); - tileGridYOffset = raster.getMinY(); - tileWidth = raster.getWidth(); - tileHeight = raster.getHeight(); - tilingSet = true; - - numTiles = 1; - numComponents = raster.getSampleModel().getNumBands(); - } - setDefaults(); - } - - /** Set source */ - private void setDefaults(RenderedImage imgsrc) { - // override the params in the super class - setSuperProperties(); - - tilingMode = MODE_EXPLICIT; - - if (imgsrc != null) { - this.imgsrc = imgsrc; - tileGridXOffset = imgsrc.getTileGridXOffset(); - tileGridYOffset = imgsrc.getTileGridYOffset(); - tileWidth = imgsrc.getTileWidth(); - tileHeight = imgsrc.getTileHeight(); - tilingSet = true; - - numTiles = imgsrc.getNumXTiles() * imgsrc.getNumYTiles(); - numComponents = imgsrc.getSampleModel().getNumBands(); - } - setDefaults(); - } - - private void setDefaults() { - setROIs(null); - setQuantizationType(null); - setQuantizationStep(null); - setGuardBits(null); - setFilters(null); - setDecompositionLevel(null); - setComponentTransformation(null); - setMethodForMQLengthCalc(null); - setMethodForMQTermination(null); - setCodeSegSymbol(null); - setCausalCXInfo(null); - setTerminateOnByte(null); - setResetMQ(null); - setBypass(null); - setCodeBlockSize(null); - setPrecinctPartition(null); - setSOP(null); - setEPH(null); - } - - /** Sets encodingRate */ - public void setEncodingRate(double rate) { - this.encodingRate = rate; - } - - /** Gets encodingRate */ - public double getEncodingRate() { - return encodingRate; - } - - /** Sets lossless */ - public void setLossless(boolean lossless) { - this.lossless = lossless; - } - - /** Gets encodingRate */ - public boolean getLossless() { - return lossless; - } - /** Sets packetPerTilePart */ - public void setPacketPerTilePart(int packetPerTilePart) { - if (packetPerTilePart < 0) - throw new IllegalArgumentException(I18N.getString("J2KImageWriteParamJava0")); - - this.packetPerTilePart = packetPerTilePart; - if (packetPerTilePart > 0) { - setSOP("true"); - setEPH("true"); - } - } - - /** Gets packetPerTilePart */ - public int getPacketPerTilePart() { - return packetPerTilePart; - } - - /** Sets packPacketHeaderInTile */ - public void setPackPacketHeaderInTile(boolean packPacketHeaderInTile) { - this.packPacketHeaderInTile = packPacketHeaderInTile; - if (packPacketHeaderInTile) { - setSOP("true"); - setEPH("true"); - } - } - - /** Gets packPacketHeaderInTile */ - public boolean getPackPacketHeaderInTile() { - return packPacketHeaderInTile; - } - - /** Sets packPacketHeaderInMain */ - public void setPackPacketHeaderInMain(boolean packPacketHeaderInMain) { - this.packPacketHeaderInMain = packPacketHeaderInMain; - if (packPacketHeaderInMain) { - setSOP("true"); - setEPH("true"); - } - } - - /** Gets packPacketHeaderInMain */ - public boolean getPackPacketHeaderInMain() { - return packPacketHeaderInMain; - } - - /** Sets alignROI */ - public void setAlignROI(boolean align) { - alignROI = align; - } - - /** Gets alignROI */ - public boolean getAlignROI() { - return alignROI; - } - - /** Sets ROIs */ - public void setROIs(String values) { - ROIs = new MaxShiftSpec(numTiles, numComponents, ModuleSpec.SPEC_TYPE_TILE_COMP, values); - } - - /** Gets ROIs */ - public MaxShiftSpec getROIs() { - return ROIs; - } - - /** Sets quantizationType */ - public void setQuantizationType(String values) { - quantizationType = new QuantTypeSpec(numTiles, numComponents, - ModuleSpec.SPEC_TYPE_TILE_COMP, this, values); - } - - /** Gets quantizationType */ - public QuantTypeSpec getQuantizationType() { - return quantizationType; - } - - /** Sets quantizationStep */ - public void setQuantizationStep(String values) { - quantizationStep = new QuantStepSizeSpec(numTiles, - numComponents, - ModuleSpec.SPEC_TYPE_TILE_COMP, - this, - values); - } - - /** Gets quantizationStep */ - public QuantStepSizeSpec getQuantizationStep() { - return quantizationStep; - } - - /** Sets guardBits */ - public void setGuardBits(String values) { - guardBits = new GuardBitsSpec(numTiles, - numComponents, - ModuleSpec.SPEC_TYPE_TILE_COMP, - this, - values); - } - - /** Gets guardBits */ - public GuardBitsSpec getGuardBits() { - return guardBits; - } - - /** Sets filters */ - // NOTE This also sets quantizationType and componentTransformation. - public void setFilters(String values) { - if (J2KImageWriteParam.FILTER_97.equals(values)) - setQuantizationType ("expounded"); - else - setQuantizationType("reversible"); - - filters = new AnWTFilterSpec(numTiles, - numComponents, - ModuleSpec.SPEC_TYPE_TILE_COMP, - (QuantTypeSpec)quantizationType, - this, - values); - setComponentTransformation(""+enableCT); - } - - /** Gets filters */ - public AnWTFilterSpec getFilters() { - return filters; - } - - /** Sets decompositionLevel */ - public void setDecompositionLevel(String values) { - decompositionLevel = new IntegerSpec(numTiles, - numComponents, - ModuleSpec.SPEC_TYPE_TILE_COMP, - this, - values, - "5"); - - // NOTE The precinctPartition depends upon decompositionLevel - // so it needs to be re-initialized. Note that the parameter of - // setPrecinctPartition() is not used in the current implementation. - setPrecinctPartition(null); - } - - /** Gets decompositionLevel */ - public IntegerSpec getDecompositionLevel() { - return decompositionLevel; - } - - /** Sets componentTransformation */ - // NOTE This requires filters having been set previously. - public void setComponentTransformation(String values) { - componentTransformation = - new ForwCompTransfSpec(numTiles, - numComponents, - ModuleSpec.SPEC_TYPE_TILE, - (AnWTFilterSpec)filters, - this, - values); - } - - /** Gets componentTransformation */ - public ForwCompTransfSpec getComponentTransformation() { - return componentTransformation; - } - /** Sets methodForMQLengthCalc */ - public void setMethodForMQLengthCalc(String values) { - String[] strLcs = {"near_opt","lazy_good","lazy"}; - methodForMQLengthCalc = - new StringSpec(numTiles, - numComponents, - ModuleSpec.SPEC_TYPE_TILE_COMP, - "near_opt", - strLcs, - this, - values); - } - - /** Gets methodForMQLengthCalc */ - public StringSpec getMethodForMQLengthCalc() { - return methodForMQLengthCalc; - } - - /** Sets methodForMQTermination */ - public void setMethodForMQTermination(String values) { - String[] strTerm = {"near_opt","easy","predict","full"}; - methodForMQTermination = - new StringSpec(numTiles, - numComponents, - ModuleSpec.SPEC_TYPE_TILE_COMP, - "near_opt", - strTerm, - this, - values); - } - - /** Gets methodForMQTermination */ - public StringSpec getMethodForMQTermination() { - return methodForMQTermination; - } - - /** Sets codeSegSymbol */ - public void setCodeSegSymbol(String values) { - String[] strBoolean = {"true","false"}; - codeSegSymbol = - new StringSpec(numTiles, - numComponents, - ModuleSpec.SPEC_TYPE_TILE_COMP, - "false", - strBoolean, - this, - values); - } - - /** Gets codeSegSymbol */ - public StringSpec getCodeSegSymbol() { - return codeSegSymbol; - } - - /** Sets causalCXInfo */ - public void setCausalCXInfo(String values) { - String[] strBoolean = {"true","false"}; - causalCXInfo = new StringSpec(numTiles, - numComponents, - ModuleSpec.SPEC_TYPE_TILE_COMP, - "false", - strBoolean, - this, - values); - } - - /** Gets causalCXInfo */ - public StringSpec getCausalCXInfo() { - return causalCXInfo; - } - - /** Sets terminateOnByte */ - public void setTerminateOnByte(String values) { - String[] strBoolean = {"true","false"}; - terminateOnByte = new StringSpec(numTiles, - numComponents, - ModuleSpec.SPEC_TYPE_TILE_COMP, - "false", - strBoolean, - this, - values); - } - - /** Gets terminateOnByte */ - public StringSpec getTerminateOnByte() { - return terminateOnByte; - } - - /** Sets resetMQ */ - public void setResetMQ(String values) { - String[] strBoolean = {"true","false"}; - resetMQ = new StringSpec(numTiles, - numComponents, - ModuleSpec.SPEC_TYPE_TILE_COMP, - "false", - strBoolean, - this, - values); - } - - /** Gets resetMQ */ - public StringSpec getResetMQ() { - return resetMQ; - } - - /** Sets bypass */ - public void setBypass(String values) { - String[] strBoolean = {"true","false"}; - bypass = new StringSpec(numTiles, - numComponents, - ModuleSpec.SPEC_TYPE_TILE_COMP, - "false", - strBoolean, - this, - values); - } - - /** Gets bypass */ - public StringSpec getBypass() { - return bypass; - } - - /** Sets codeBlockSize */ - public void setCodeBlockSize(String values) { - codeBlockSize = new CBlkSizeSpec(numTiles, - numComponents, - ModuleSpec.SPEC_TYPE_TILE_COMP, - this, - values); - } - - /** Gets codeBlockSize */ - public CBlkSizeSpec getCodeBlockSize() { - return codeBlockSize; - } - - /** Sets precinctPartition */ - public void setPrecinctPartition(String values) { - String[] strBoolean = {"true","false"}; - if (imgsrc != null) - precinctPartition = - new PrecinctSizeSpec(numTiles, - numComponents, - ModuleSpec.SPEC_TYPE_TILE_COMP, - new RenderedImageSrc(imgsrc, this, null), - decompositionLevel, - this, - values); - else if (raster != null) - precinctPartition = - new PrecinctSizeSpec(numTiles, - numComponents, - ModuleSpec.SPEC_TYPE_TILE_COMP, - new RenderedImageSrc(raster, this, null), - decompositionLevel, - this, - values); - } - - /** Gets precinctPartition */ - public PrecinctSizeSpec getPrecinctPartition() { - return precinctPartition; - } - - /** Sets SOP */ - public void setSOP(String values) { - String[] strBoolean = {"true","false"}; - SOP = new StringSpec(numTiles, - numComponents, - ModuleSpec.SPEC_TYPE_TILE_COMP, - "false", - strBoolean, - this, - values); - } - - /** Gets SOP */ - public StringSpec getSOP() { - return SOP; - } - - /** Sets EPH */ - public void setEPH(String values) { - String[] strBoolean = {"true","false"}; - EPH = new StringSpec(numTiles, - numComponents, - ModuleSpec.SPEC_TYPE_TILE_COMP, - "false", - strBoolean, - this, - values); - } - - /** Gets EPH */ - public StringSpec getEPH() { - return EPH; - } - - /** Sets progressionName */ - public void setProgressionName(String values) { - progressionName = values; - } - - /** Gets progressionType */ - public String getProgressionName() { - return progressionName; - } - - /** Sets progressionType */ - public void setProgressionType(LayersInfo lyrs, String values) { - String[] strBoolean = {"true","false"}; - progressionType = new ProgressionSpec(numTiles, - numComponents, - lyrs.getTotNumLayers(), - decompositionLevel, - ModuleSpec.SPEC_TYPE_TILE_COMP, - this, - values); - } - - /** Gets progressionType */ - public ProgressionSpec getProgressionType() { - return progressionType; - } - - /** Sets the startLevelROI */ - public void setStartLevelROI(int value) { - startLevelROI = value; - } - - /** Gets startLevel */ - public int getStartLevelROI() { - return startLevelROI; - } - - /** Sets the layers */ - public void setLayers(String value) { - layers = value; - } - - /** Gets layers */ - public String getLayers() { - return layers; - } - - /** Sets minX */ - public void setMinX(int minX) { - this.minX = minX; - } - - /** Gets minX */ - public int getMinX() { - return minX; - } - - /** Sets minY */ - public void setMinY(int minY) { - this.minY = minY; - } - - /** Gets minY */ - public int getMinY() { - return minY; - } - - /** Gets the number of tiles */ - public int getNumTiles() { - Rectangle sourceRegion = getSourceRegion(); - if (sourceRegion == null) { - if (imgsrc != null) - sourceRegion = new Rectangle(imgsrc.getMinX(), - imgsrc.getMinY(), - imgsrc.getWidth(), - imgsrc.getHeight()); - else sourceRegion = raster.getBounds(); - } else { - if (imgsrc != null) - sourceRegion = - sourceRegion.intersection(new Rectangle(imgsrc.getMinX(), - imgsrc.getMinY(), - imgsrc.getWidth(), - imgsrc.getHeight())); - else sourceRegion = sourceRegion.intersection(raster.getBounds()); - } - - int scaleX = getSourceXSubsampling(); - int scaleY = getSourceYSubsampling(); - int xOffset = getSubsamplingXOffset(); - int yOffset = getSubsamplingYOffset(); - - int w = (sourceRegion.width - xOffset + scaleX - 1) / scaleX; - int h = (sourceRegion.height - yOffset + scaleY - 1) / scaleY; - - minX = (sourceRegion.x + xOffset) / scaleX; - minY = (sourceRegion.y + yOffset) / scaleY; - - numTiles = (int)((Math.floor((minX + w + tileWidth - 1.0) / tileWidth) - - Math.floor((double)minX/tileWidth) ) * - (Math.floor((minY + h + tileHeight - 1.0) / tileHeight) - - Math.floor((double)minY/tileHeight) ) ); - tileGridXOffset += (minX - tileGridXOffset) / tileWidth * tileWidth; - tileGridYOffset += (minY - tileGridYOffset) / tileHeight * tileHeight; - - return numTiles; - } - - /** Gets the number of components */ - public int getNumComponents() { - return numComponents; - } - - /** Override the method setSourceBands in the super class. This method - * should be called before any tile-specific parameter setting method - * to be called. - */ - public void setSourceBands(int[] bands) { - super.setSourceBands(bands); - if (bands != null) { - numComponents = bands.length; - setDefaults(); - } - } - - /** Override the method setTiling in the super class. This method - * should be called before any tile-specific parameter setting method - * to be called. - */ - public void setTiling(int tw, int th, int xOff, int yOff) { - super.setTiling(tw, th, xOff, yOff); - getNumTiles(); - setDefaults(); - } - - /** Override the method setSourceSubsampling in the super class. This - * method should be called before any tile-specific parameter setting - * method to be called. - */ - public void setSourceSubsampling(int sx, int sy, int xOff, int yOff) { - super.setSourceSubsampling(sx, sy, xOff, yOff); - getNumTiles(); - setDefaults(); - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterCodecLib.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterCodecLib.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterCodecLib.java 2006-09-22 19:07:25.000000000 -0400 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterCodecLib.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,879 +0,0 @@ -/* - * $RCSfile: J2KImageWriterCodecLib.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.3 $ - * $Date: 2006/09/22 23:07:25 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.image.ColorModel; -import java.awt.image.DataBuffer; -import java.awt.image.DataBufferByte; -import java.awt.image.IndexColorModel; -import java.awt.image.Raster; -import java.awt.image.RenderedImage; -import java.awt.image.SampleModel; -import java.awt.image.WritableRaster; - -import java.io.IOException; - -import java.util.Arrays; -import java.util.List; - -import javax.imageio.IIOImage; -import javax.imageio.IIOException; -import javax.imageio.ImageTypeSpecifier; -import javax.imageio.ImageWriteParam; -import javax.imageio.ImageWriter; -import javax.imageio.metadata.IIOMetadata; -import javax.imageio.metadata.IIOMetadataFormatImpl; -import javax.imageio.metadata.IIOMetadataNode; -import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.spi.ImageWriterSpi; -import javax.imageio.stream.ImageOutputStream; - -import com.sun.media.imageio.plugins.jpeg2000.J2KImageWriteParam; -import com.sun.media.imageioimpl.common.ImageUtil; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import com.sun.medialib.codec.jp2k.CompParams; -import com.sun.medialib.codec.jp2k.Constants; -import com.sun.medialib.codec.jp2k.Encoder; -import com.sun.medialib.codec.jp2k.Params; -import com.sun.medialib.codec.jp2k.Size; -import com.sun.medialib.codec.jiio.*; - -public class J2KImageWriterCodecLib extends ImageWriter { - /** When the writing is aborted, RenderedImageSrc throws a - * RuntimeException. - */ - public static String WRITE_ABORTED = "Write aborted."; - - /** The output stream to write into */ - private ImageOutputStream stream = null; - - /** The metadata format object. */ - private J2KMetadataFormat format; - - /** medialib encoder. */ - private Encoder encoder; - - /** size parameters for medialib. */ - private Size size; - - /** The tile width for encoding */ - private int tileWidth; - - /** The tile height for encoding */ - private int tileHeight; - - /** The tile grid offset for encoding */ - private int tileXOffset, tileYOffset; - - /** The source -> destination transformation */ - private int scaleX, scaleY, xOffset, yOffset; - - /** The source bands to be encoded. */ - private int[] sourceBands = null; - - /** The number of components in the image */ - private int numComp; - - private RenderedImage input; - private J2KImageWriteParam param; - - /** The input source raster. */ - private Raster inputRaster; - - private Rectangle destinationRegion = null; - - private SampleModel sampleModel; - - /** Coordinate transform or sub selection is needed before encoding. */ - private boolean noTransform = true; - private boolean noSubband = true; - - /** Indicates a raster rather than a RenderedImage - * to be encoded. - */ - private boolean writeRaster = false; - - /** Constructs J2KImageWriter based on the provided - * ImageWriterSpi. - */ - public J2KImageWriterCodecLib(ImageWriterSpi originator) { - super(originator); - } - - public void setOutput(Object output) { - super.setOutput(output); // validates output - if (output != null) { - if (!(output instanceof ImageOutputStream)) - throw new IllegalArgumentException(I18N.getString("J2KImageWriter0")); - this.stream = (ImageOutputStream)output; - } else - this.stream = null; - } - - public ImageWriteParam getDefaultWriteParam() { - return new J2KImageWriteParam(); - } - - public IIOMetadata convertStreamMetadata(IIOMetadata inData, - ImageWriteParam param) { - return null; - } - - public void write(IIOMetadata streamMetadata, - IIOImage image, - ImageWriteParam param) throws java.io.IOException { - if (stream == null) { - throw new IllegalStateException(I18N.getString("J2KImageWriterMedialib1")); - } - if (image == null) { - throw new IllegalArgumentException(I18N.getString("J2KImageWriterMedialib2")); - } - clearAbortRequest(); - processImageStarted(0); - encoder = new Encoder(stream); - - writeRaster = image.hasRaster(); - ColorModel colorModel = null; - - if (writeRaster) { - inputRaster = image.getRaster(); - sampleModel = inputRaster.getSampleModel(); - } else { - input = image.getRenderedImage(); - sampleModel = input.getSampleModel(); - colorModel = input.getColorModel(); - } - - if (param == null) - param = new J2KImageWriteParam(); - - if(param instanceof J2KImageWriteParam) { - J2KImageWriteParam j2kParam = (J2KImageWriteParam)param; - if (!writeRaster && - input.getColorModel() instanceof IndexColorModel) { - j2kParam.setLossless(true); - j2kParam.setEncodingRate(Double.MAX_VALUE); - j2kParam.setFilter(J2KImageWriteParam.FILTER_53); - } else if (j2kParam.getEncodingRate() == - Double.MAX_VALUE) { - j2kParam.setLossless(true); - j2kParam.setFilter(J2KImageWriteParam.FILTER_53); - } - } - setParameters(param); - - Rectangle sourceRegion = param.getSourceRegion(); - if (sourceRegion == null) { - if (writeRaster) - sourceRegion = inputRaster.getBounds(); - else - sourceRegion = new Rectangle(input.getMinX(), input.getMinY(), - input.getWidth(), - input.getHeight()); - } else { - if (writeRaster) - sourceRegion = - sourceRegion.intersection(inputRaster.getBounds()); - else - sourceRegion = - sourceRegion.intersection(new Rectangle(input.getMinX(), - input.getMinY(), - input.getWidth(), - input.getHeight())); - } - - if (sourceRegion.isEmpty()) - throw new RuntimeException(I18N.getString("J2KImageWriterCodecLib0")); - - try { - tileWidth = param.getTileWidth(); - tileHeight = param.getTileHeight(); - tileXOffset = param.getTileGridXOffset(); - tileYOffset = param.getTileGridYOffset(); - } catch (IllegalStateException e) { - param.setTilingMode(ImageWriteParam.MODE_EXPLICIT); - if (writeRaster) { - param.setTiling(inputRaster.getWidth(), - inputRaster.getHeight(), - inputRaster.getMinX(), - inputRaster.getMinY()); - } else { - param.setTiling(input.getTileWidth(), - input.getTileHeight(), - input.getTileGridXOffset(), - input.getTileGridYOffset()); - } - tileWidth = param.getTileWidth(); - tileHeight = param.getTileHeight(); - tileXOffset = param.getTileGridXOffset(); - tileYOffset = param.getTileGridYOffset(); - } - - scaleX = param.getSourceXSubsampling(); - scaleY = param.getSourceYSubsampling(); - xOffset = param.getSubsamplingXOffset(); - yOffset = param.getSubsamplingYOffset(); - - sourceRegion.translate(xOffset, yOffset); - sourceRegion.width -= xOffset; - sourceRegion.height -= yOffset; - - xOffset = sourceRegion.x % scaleX; - yOffset = sourceRegion.y % scaleY; - - int minX = sourceRegion.x / scaleX; - int minY = sourceRegion.y / scaleY; - - int w = (sourceRegion.width + scaleX - 1) / scaleX; - int h = (sourceRegion.height + scaleY - 1) / scaleY; - - tileXOffset += (minX - tileXOffset)/tileWidth * tileWidth; - tileYOffset += (minY - tileYOffset)/tileHeight * tileHeight; - - destinationRegion = new Rectangle(minX, minY, w, h); - - if (!destinationRegion.equals(sourceRegion) || - tileWidth != sampleModel.getWidth() || - tileHeight != sampleModel.getHeight() || - (!writeRaster && - (tileXOffset != input.getTileGridXOffset() || - tileYOffset != input.getTileGridYOffset())) || - (writeRaster && - (tileXOffset != inputRaster.getMinX() || - tileYOffset != inputRaster.getMinY()))) - noTransform = false; - - numComp = sampleModel.getNumBands(); - sourceBands = param.getSourceBands(); - if (sourceBands != null) { - sampleModel = sampleModel.createSubsetSampleModel(sourceBands); - colorModel = null; - noSubband = false; - } else { - sourceBands = new int[numComp]; - for (int i = 0; i < numComp; i++) - sourceBands[i] = i; - } - - numComp = sourceBands.length; - - sampleModel = - sampleModel.createCompatibleSampleModel(tileWidth, tileHeight); - - setSize(); - - setCompParameters(colorModel, sampleModel, param); - - encoder.setMode(Constants.JP2K_COMPOSITE_TILE); - - /* XXX - J2KMetadata metadata = (J2KMetadata)image.getMetadata(); - ImageTypeSpecifier type = null; - if (colorModel != null) - type = new ImageTypeSpecifier(colorModel, sampleModel); - - J2KMetadata metadata1 = - new J2KMetadata(colorModel, sampleModel, destinationRegion.width, - destinationRegion.height, param, this); - - if (metadata == null) - metadata = metadata1; - else - metadata.mergeTree("com_sun_media_imageio_plugins_jpeg2000_image_1.0", - metadata1.getAsTree("com_sun_media_imageio_plugins_jpeg2000_image_1.0")); - */ - - //write the metadata - if (!((J2KImageWriteParam)param).getWriteCodeStreamOnly()) { - IIOMetadata inMetadata = image.getMetadata(); - - J2KMetadata metadata1 = new J2KMetadata(colorModel, - sampleModel, - destinationRegion.width, - destinationRegion.height, - param, - this); - - J2KMetadata metadata = null; - - if (inMetadata == null) { - metadata = metadata1; - } else { - // Convert the input metadata tree to a J2KMetadata. - if(colorModel != null) { - ImageTypeSpecifier imageType = - new ImageTypeSpecifier(colorModel, sampleModel); - metadata = - (J2KMetadata)convertImageMetadata(inMetadata, - imageType, - param); - } else { - String metaFormat = null; - List metaFormats = - Arrays.asList(inMetadata.getMetadataFormatNames()); - if(metaFormats.contains(J2KMetadata.nativeMetadataFormatName)) { - // Initialize from native image metadata format. - metaFormat = J2KMetadata.nativeMetadataFormatName; - } else if(inMetadata.isStandardMetadataFormatSupported()) { - // Initialize from standard metadata form of the - // input tree. - metaFormat = - IIOMetadataFormatImpl.standardMetadataFormatName; - } - - metadata = new J2KMetadata(); - if(metaFormat != null) { - metadata.setFromTree(metaFormat, - inMetadata.getAsTree(metaFormat)); - } - } - - metadata.mergeTree(J2KMetadata.nativeMetadataFormatName, - metadata1.getAsTree(J2KMetadata.nativeMetadataFormatName)); - } - - writeMetadata(metadata); - } else { - encoder.setEncodeCodeStreamOnly(); - } - - for (int y = getMinTileY(); y <= getMaxTileY(); y++) { - for (int x = getMinTileX(); x <= getMaxTileX(); x++) { - Raster currentTile = getTile(x, y); - int sourceFormatTag = - MediaLibAccessor.findCompatibleTag(currentTile); - - MediaLibAccessor accessor = - new MediaLibAccessor(currentTile, - currentTile.getBounds(), - sourceFormatTag, true); - mediaLibImage[] mlImage = accessor.getMediaLibImages(); - - encoder.encode(mlImage, x + y * size.nxtiles); - float percentage = - (x + y * size.nxtiles + 1.0F) / (size.nxtiles * size.nytiles); - processImageProgress(percentage * 100.0F); - } - } - } - - public IIOMetadata getDefaultImageMetadata(ImageTypeSpecifier imageType, - ImageWriteParam param) { - return new J2KMetadata(imageType, param, this); - } - - public IIOMetadata getDefaultStreamMetadata(ImageWriteParam param) { - return null; - } - - public IIOMetadata convertImageMetadata(IIOMetadata inData, - ImageTypeSpecifier imageType, - ImageWriteParam param) { - // Check arguments. - if(inData == null) { - throw new IllegalArgumentException("inData == null!"); - } - if(imageType == null) { - throw new IllegalArgumentException("imageType == null!"); - } - - // If it's one of ours, return a clone. - if (inData instanceof J2KMetadata) { - return (IIOMetadata)((J2KMetadata)inData).clone(); - } - - try { - J2KMetadata outData = new J2KMetadata(); - - List formats = Arrays.asList(inData.getMetadataFormatNames()); - - String format = null; - if(formats.contains(J2KMetadata.nativeMetadataFormatName)) { - // Initialize from native image metadata format. - format = J2KMetadata.nativeMetadataFormatName; - } else if(inData.isStandardMetadataFormatSupported()) { - // Initialize from standard metadata form of the input tree. - format = IIOMetadataFormatImpl.standardMetadataFormatName; - } - - if(format != null) { - outData.setFromTree(format, inData.getAsTree(format)); - return outData; - } - } catch(IIOInvalidTreeException e) { - return null; - } - - return null; - } - - public boolean canWriteRasters() { - return true; - } - - public synchronized void abort() { - super.abort(); - } - - public void reset() { - // reset local Java structures - super.reset(); - stream = null; - } - - /** This method wraps the protected method abortRequested - * to allow the abortions be monitored by J2KRenderedImage. - */ - public boolean getAbortRequest() { - return abortRequested(); - } - - private void checkSampleModel(SampleModel sm) { - int type = sm.getDataType(); - - if (type < DataBuffer.TYPE_BYTE || type > DataBuffer.TYPE_INT) - throw new IllegalArgumentException(I18N.getString("J2KImageWriter5")); - if (sm.getNumBands() > 16384) - throw new IllegalArgumentException(I18N.getString("J2KImageWriter6")); - } - - private void writeMetadata(J2KMetadata metadata) throws IOException { - if (metadata == null) - return; - - IIOMetadataNode root = - (IIOMetadataNode)metadata.getAsTree("com_sun_media_imageio_plugins_jpeg2000_image_1.0"); - if (root == null) - return; - format = - (J2KMetadataFormat)metadata.getMetadataFormat("com_sun_media_imageio_plugins_jpeg2000_image_1.0"); - writeSuperBox(root); - } - - private void writeSuperBox(IIOMetadataNode node) throws IOException { - NodeList list = node.getChildNodes(); - - String name = node.getNodeName(); - if (name.startsWith("JPEG2000")) { -/* - int length = computeLength(node); - byte[] data = new byte[length]; - generateSuperBoxContent(node, data, 0); - com.sun.medialib.codec.jp2k.Box box = - new com.sun.medialib.codec.jp2k.Box(); - box.data = data; - box.type = Box.getTypeInt((String)Box.getTypeByName(name)); - encoder.encodeSuperBox(box.type, new com.sun.medialib.codec.jp2k.Box[]{box}); - return; -*/ -/* - com.sun.medialib.codec.jp2k.Box box = - new com.sun.medialib.codec.jp2k.Box(); - box.type = Box.getTypeInt((String)Box.getTypeByName(name)); - encoder.encodeSuperBox(box.type, null); -*/ - } - - for (int i = 0; i < list.getLength(); i++) { - IIOMetadataNode child = (IIOMetadataNode)list.item(i); - - name = child.getNodeName(); - if (name.startsWith("JPEG2000") && format.isLeaf(name)) - writeBox(child); - else - writeSuperBox(child); - } - } - - private void writeBox(IIOMetadataNode node) throws IOException { - com.sun.medialib.codec.jp2k.Box mlibBox = - new com.sun.medialib.codec.jp2k.Box(); - mlibBox.type = Box.getTypeInt((String)Box.getAttribute(node, "Type")); - Box box = Box.createBox(mlibBox.type, node); - mlibBox.data = box.getContent(); - encoder.encodeBox(mlibBox); - } - - private int computeLength(IIOMetadataNode root) { - NodeList list = root.getChildNodes(); - int length = 0; - for (int i = 0; i < list.getLength(); i++) { - IIOMetadataNode node = (IIOMetadataNode)list.item(i); - String name = node.getNodeName(); - - if (format.isLeaf(name)) { - String s = (String)Box.getAttribute(node, "Length"); - length += new Integer(s).intValue(); - } else - length += computeLength(node); - - } - - return length + (root.getNodeName().startsWith("JPEG2000") ? 8 : 0) ; - } - - private int generateSuperBoxContent(IIOMetadataNode root, - byte[] data, - int pos) throws IOException { - String name = root.getNodeName(); - if (name.startsWith("JPEG2000")) { - int length = computeLength(root); - Box.copyInt(data, pos, length); - pos += 4; - int type = Box.getTypeInt((String)Box.getTypeByName(name)); - Box.copyInt(data, pos, type); - pos += 4; - } - - NodeList list = root.getChildNodes(); - for (int i = 0; i < list.getLength(); i++) { - IIOMetadataNode node = (IIOMetadataNode)list.item(i); - name = node.getNodeName(); - - if (format.isLeaf(name)) { - int type = - Box.getTypeInt((String)Box.getAttribute(node, "Type")); - Box box = Box.createBox(type, node); - byte[] data1 = box.getContent(); - Box.copyInt(data, pos, data1.length + 8); - pos += 4; - - Box.copyInt(data, pos, type); - pos += 4; - System.arraycopy(data1, 0, data, pos, data1.length); - pos += data1.length; - } else { - pos = generateSuperBoxContent(node, data, pos); - } - } - - return pos; - } - - private Raster getTile(int tileX, int tileY) { - int sx = tileXOffset + tileX * tileWidth; - int sy = tileYOffset + tileY * tileHeight; - Rectangle bounds = new Rectangle(sx, sy, tileWidth, tileHeight); - - if (writeRaster) { - bounds = bounds.intersection(destinationRegion); - if (noTransform) { - return inputRaster.createChild(bounds.x, bounds.y, - bounds.width, bounds.height, - bounds.x, bounds.y, sourceBands); - } - - sx = bounds.x; - sy = bounds.y; - WritableRaster ras = - Raster.createWritableRaster(sampleModel, new Point(sx, sy)); - - int x = mapToSourceX(sx); - int y = mapToSourceY(sy); - - int minY = inputRaster.getMinY(); - int maxY = inputRaster.getMinY() + inputRaster.getHeight(); - - int cTileWidth = bounds.width; - - int length = (cTileWidth - 1) * scaleX + 1; - - for (int j = 0; j < bounds.height; j++, sy++, y += scaleY) { - if (y < minY || y >= maxY) - continue; - Raster source = - inputRaster.createChild(x, y, length, 1, - x, y, null); - int tempX = sx; - for (int i = 0, offset = x; i < cTileWidth; - i++, tempX++, offset += scaleX) { - for (int k = 0; k < numComp; k++) { - int p = source.getSample(offset, y, sourceBands[k]); - ras.setSample(tempX, sy, k, p); - } - } - } - - return ras; - - } else { - if (noTransform) { - Raster ras = input.getTile(tileX, tileY); - if (destinationRegion.contains(bounds) && noSubband) - return ras; - else { - bounds = bounds.intersection(destinationRegion); - return ras.createChild(bounds.x, bounds.y, - bounds.width, bounds.height, - bounds.x, bounds.y, sourceBands); - } - } - - bounds = bounds.intersection(destinationRegion); - sx = bounds.x; - sy = bounds.y; - - WritableRaster ras = - Raster.createWritableRaster(sampleModel, new Point(sx, sy)); - - int x = mapToSourceX(sx); - int y = mapToSourceY(sy); - - int minY = input.getMinY(); - int maxY = input.getMinY() + input.getHeight(); - - int cTileWidth = bounds.width; - int length = (cTileWidth -1) * scaleX + 1; - - for (int j = 0; j < bounds.height; j++, sy++, y += scaleY) { - if (y < minY || y >= maxY) - continue; - - Raster source = - input.getData(new Rectangle(x, y, length, 1)); - - int tempX = sx; - for (int i = 0, offset = x; i < cTileWidth; - i++, tempX++, offset += scaleX) { - for (int k = 0; k < numComp; k++) { - int p = source.getSample(offset, y, sourceBands[k]); - ras.setSample(tempX, sy, k, p); - } - } - } - return ras; - } - } - - private int mapToSourceX(int x) { - return x * scaleX + xOffset; - } - - private int mapToSourceY(int y) { - return y * scaleY + yOffset; - } - - private int getMinTileX() { - return ToTile(destinationRegion.x, tileXOffset, tileWidth); - } - - private int getMaxTileX() { - return ToTile(destinationRegion.x + destinationRegion.width - 1, - tileXOffset, tileWidth); - } - - private int getMinTileY() { - return ToTile(destinationRegion.y, tileYOffset, tileHeight); - } - - private int getMaxTileY() { - return ToTile(destinationRegion.y + destinationRegion.height - 1, - tileYOffset, tileHeight); - } - - private static int ToTile(int pos, int tileOffset, int tileSize) { - pos -= tileOffset; - if (pos < 0) { - pos += 1 - tileSize; // force round to -infinity (ceiling) - } - return pos/tileSize; - } - - private void setSize() { - size = new Size(); - size.csize = numComp; - size.nxtiles = getMaxTileX() - getMinTileX() + 1; - size.nytiles = getMaxTileY() - getMinTileY() + 1; - - size.xosize = destinationRegion.x; - size.yosize = destinationRegion.y; - size.xsize = destinationRegion.width + destinationRegion.x; - size.ysize = destinationRegion.height + destinationRegion.y; - size.xtosize = tileXOffset; - size.ytosize = tileYOffset; - size.xtsize = tileWidth; - size.ytsize = tileHeight; - - encoder.setSize(size); - } - - private void setCompParameters(ColorModel colorModel, - SampleModel sampleModel, - ImageWriteParam compParamArg) { - // Check the parameters. - if (colorModel == null && sampleModel == null && - (compParamArg == null || - !(compParamArg instanceof J2KImageWriteParam))) { - return; - } - - // Get the bit depths. - int[] bitDepths = null; - boolean isSigned = false; - if(colorModel != null) { - bitDepths = colorModel.getComponentSize(); - isSigned = colorModel.getTransferType() == DataBuffer.TYPE_SHORT; - } else if(sampleModel != null) { - bitDepths = sampleModel.getSampleSize(); - isSigned = sampleModel.getDataType() == DataBuffer.TYPE_SHORT; - } - - // Get the number of decomposition levels. - int numDecompositionLevels = -1; - if(compParamArg != null) { - // Cast is safe due to parameter check above. - numDecompositionLevels = - ((J2KImageWriteParam)compParamArg).getNumDecompositionLevels(); - } - - // Return if nothing to set. - if(bitDepths == null && numDecompositionLevels == -1) return; - - // Check for unequal bit depths. - boolean bitDepthVaries = false; - if(bitDepths != null) { - for(int i = 1; i < bitDepths.length; i++) { - if(bitDepths[i] != bitDepths[0]) { - bitDepthVaries = true; - break; - } - } - } - - CompParams cp = encoder.getCompParams(null, -1); - - // Update the COD segment if needed. - if((numDecompositionLevels != -1 && - numDecompositionLevels != cp.maxlvls) || - (bitDepths != null && - ((isSigned ? 0x80 : 0x00) | (bitDepths[0] - 1)) != cp.depth)) { - - if(numDecompositionLevels != -1) { - cp.maxlvls = numDecompositionLevels; - } - - // Set the main COD bit depth to bitDepths[0]. - if(bitDepths != null) { - cp.depth = (isSigned ? 0x80 : 0x00) | (bitDepths[0] - 1); - } - - encoder.setCompParams(cp, -1); - } - - // Update COC segments if needed. - if(bitDepthVaries) { // only true if bitDepths != null - // Loop over component zero even though unnecessary. - for(int i = 0; i < numComp; i++) { - cp = encoder.getCompParams(null, i); - - if(numDecompositionLevels != -1) { - cp.maxlvls = numDecompositionLevels; - } - - cp.depth = (isSigned ? 0x80 : 0x00) | (bitDepths[i] - 1); - - encoder.setCompParams(cp, i); - } - } - } - - private void setParameters(ImageWriteParam paramArg) { - if (paramArg == null || - !(paramArg instanceof J2KImageWriteParam)) { - return; - } - - J2KImageWriteParam param = (J2KImageWriteParam)paramArg; - - // set the rate - double rate = param.getEncodingRate(); - if (rate != Double.MAX_VALUE) { - // convert the rate to the medialib definition - rate /= ImageUtil.getElementSize(sampleModel); - encoder.setRate(rate, 0); - } else - encoder.setRate(0.0, 0); - - Params params = new Params(); - - // set the component transformation flag - params.enablemct = param.getComponentTransformation() ? - Constants.JP2K_MCT_ENABLE : - Constants.JP2K_MCT_DISABLE; - - // set coding style - if (param.getEPH()) - params.cstyle |= Constants.JP2K_COD_EPH; - if (param.getSOP()) - params.cstyle |= Constants.JP2K_COD_SOP; - - // set the wavelet filter type - if (J2KImageWriteParam.FILTER_53.equals(param.getFilter())) - params.wavemode = Constants.JP2K_WAVEMODE_53; - else if (J2KImageWriteParam.FILTER_97.equals(param.getFilter())) - params.wavemode = Constants.JP2K_WAVEMODE_97; - - //Set the progressive mode - String progressiveType = param.getProgressionType(); - - if ("layer".equals(progressiveType)) - params.prgorder = Constants.JP2K_COD_LRCPPRG; - if ("res".equals(progressiveType)) - params.prgorder = Constants.JP2K_COD_RLCPPRG; - if ("res-pos".equals(progressiveType)) - params.prgorder = Constants.JP2K_COD_RPCLPRG; - if ("pos-comp".equals(progressiveType)) - params.prgorder = Constants.JP2K_COD_PCRLPRG; - if ("comp-pos".equals(progressiveType)) - params.prgorder = Constants.JP2K_COD_CPRLPRG; - - encoder.setParams(params); - } -} - diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterCodecLibSpi.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterCodecLibSpi.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterCodecLibSpi.java 2006-03-31 14:43:39.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterCodecLibSpi.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,144 +0,0 @@ -/* - * $RCSfile: J2KImageWriterCodecLibSpi.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.2 $ - * $Date: 2006/03/31 19:43:39 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.awt.image.DataBuffer; -import java.awt.image.SampleModel; - -import javax.imageio.spi.ImageWriterSpi; -import javax.imageio.spi.ServiceRegistry; -import javax.imageio.spi.IIORegistry; -import javax.imageio.ImageWriter; -import javax.imageio.ImageTypeSpecifier; -import javax.imageio.IIOException; - -import java.awt.image.ColorModel; -import java.awt.image.IndexColorModel; -import java.util.Locale; - -import com.sun.media.imageioimpl.common.PackageUtil; - -public class J2KImageWriterCodecLibSpi extends ImageWriterSpi { - private static String [] readerSpiNames = - {"com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderCodecLibSpi"}; - private static String[] formatNames = - {"jpeg 2000", "JPEG 2000", "jpeg2000", "JPEG2000"}; - private static String[] extensions = - {"jp2"}; // Should add jpx or jpm - private static String[] mimeTypes = {"image/jp2", "image/jpeg2000"}; - - private boolean registered = false; - - public J2KImageWriterCodecLibSpi() { - super(PackageUtil.getVendor(), - PackageUtil.getVersion(), - formatNames, - extensions, - mimeTypes, - "com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriterCodecLib", - STANDARD_OUTPUT_TYPE, - readerSpiNames, - false, - null, null, - null, null, - true, - "com_sun_media_imageio_plugins_jpeg2000_image_1.0", - "com.sun.media.imageioimpl.plugins.jpeg2000.J2KMetadataFormat", - null, null); - } - - public String getDescription(Locale locale) { - String desc = PackageUtil.getSpecificationTitle() + - " natively-accelerated JPEG 2000 Image Writer"; - return desc; - } - - public void onRegistration(ServiceRegistry registry, - Class category) { - if (registered) { - return; - } - - registered = true; - - // Branch based on codecLib availability. - if(!PackageUtil.isCodecLibAvailable()) { - // Deregister provider. - registry.deregisterServiceProvider(this); - } else { - // Set pairwise ordering to give codecLib writer precedence. - Class javaWriterSPIClass = null; - try { - javaWriterSPIClass = - Class.forName("com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriterSpi"); - } catch(Throwable t) { - // Ignore it. - } - - if(javaWriterSPIClass != null) { - Object javaWriterSPI = - registry.getServiceProviderByClass(javaWriterSPIClass); - if(javaWriterSPI != null) { - registry.setOrdering(category, this, javaWriterSPI); - } - } - } - } - - public boolean canEncodeImage(ImageTypeSpecifier type) { - SampleModel sm = type.getSampleModel(); - if (sm.getNumBands() > 16384) - return false; - if (sm.getDataType() < DataBuffer.TYPE_BYTE || - sm.getDataType() > DataBuffer.TYPE_INT) - return false; - return true; - } - - public ImageWriter createWriterInstance(Object extension) - throws IIOException { - return new J2KImageWriterCodecLib(this); - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriter.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriter.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriter.java 2005-02-11 00:01:34.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriter.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,514 +0,0 @@ -/* - * $RCSfile: J2KImageWriter.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:34 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.awt.image.ColorModel; -import java.awt.image.DataBuffer; -import java.awt.image.DataBufferByte; -import java.awt.image.IndexColorModel; -import java.awt.image.MultiPixelPackedSampleModel; -import java.awt.image.Raster; -import java.awt.image.RenderedImage; -import java.awt.image.SampleModel; - -import java.io.File; -import java.io.IOException; - -import java.util.Arrays; -import java.util.List; - -import javax.imageio.IIOImage; -import javax.imageio.IIOException; -import javax.imageio.ImageTypeSpecifier; -import javax.imageio.ImageWriteParam; -import javax.imageio.ImageWriter; -import javax.imageio.metadata.IIOMetadata; -import javax.imageio.metadata.IIOMetadataFormatImpl; -import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.spi.ImageWriterSpi; -import javax.imageio.stream.ImageOutputStream; - -import jj2000.j2k.codestream.writer.CodestreamWriter; -import jj2000.j2k.codestream.writer.FileCodestreamWriter; -import jj2000.j2k.codestream.writer.HeaderEncoder; -import jj2000.j2k.entropy.encoder.EntropyCoder; -import jj2000.j2k.entropy.encoder.PostCompRateAllocator; -import jj2000.j2k.fileformat.writer.FileFormatWriter; -import jj2000.j2k.image.ImgDataConverter; -import jj2000.j2k.image.Tiler; -import jj2000.j2k.image.forwcomptransf.ForwCompTransf; -import jj2000.j2k.quantization.quantizer.Quantizer; -import jj2000.j2k.roi.encoder.ROIScaler; -import jj2000.j2k.util.CodestreamManipulator; -import jj2000.j2k.wavelet.analysis.ForwardWT; - -import com.sun.media.imageioimpl.common.ImageUtil; -import com.sun.media.imageio.plugins.jpeg2000.J2KImageWriteParam; -import org.w3c.dom.Node; - -/** - * The Java Image IO plugin writer for encoding a RenderedImage into - * a JPEG 2000 part 1 file (JP2) format. - * - * This writer has the capability to (1) Losslessly encode - * RenderedImages with an IndexColorModel (for - * example, bi-level or color indexed images). (2) Losslessly or lossy encode - * RenderedImage with a byte, short, ushort or integer types with - * band number upto 16384. (3) Encode an image with alpha channel. - * (4) Write the provided metadata into the code stream. It also can encode - * a raster wrapped in the provided IIOImage. - * - * The encoding process may re-tile image, clip, subsample, and select bands - * using the parameters specified in the ImageWriteParam. - * - * @see com.sun.media.imageio.plugins.J2KImageWriteParam - */ -public class J2KImageWriter extends ImageWriter { - /** Wrapper for the protected method processImageProgress - * So it can be access from the classes which are not in - * ImageWriter hierachy. - */ - public void processImageProgressWrapper(float percentageDone) { - processImageProgress(percentageDone); - } - - - /** When the writing is aborted, RenderedImageSrc throws a - * RuntimeException. - */ - public static String WRITE_ABORTED = "Write aborted."; - - /** The output stream to write into */ - private ImageOutputStream stream = null; - - /** Constructs J2KImageWriter based on the provided - * ImageWriterSpi. - */ - public J2KImageWriter(ImageWriterSpi originator) { - super(originator); - } - - public void setOutput(Object output) { - super.setOutput(output); // validates output - if (output != null) { - if (!(output instanceof ImageOutputStream)) - throw new IllegalArgumentException(I18N.getString("J2KImageWriter0")); - this.stream = (ImageOutputStream)output; - } else - this.stream = null; - } - - public ImageWriteParam getDefaultWriteParam() { - return new J2KImageWriteParam(); - } - - public IIOMetadata getDefaultStreamMetadata(ImageWriteParam param) { - return null; - } - - public IIOMetadata getDefaultImageMetadata(ImageTypeSpecifier imageType, - ImageWriteParam param) { - return new J2KMetadata(imageType, param, this); - } - - public IIOMetadata convertStreamMetadata(IIOMetadata inData, - ImageWriteParam param) { - return null; - } - - public IIOMetadata convertImageMetadata(IIOMetadata inData, - ImageTypeSpecifier imageType, - ImageWriteParam param) { - // Check arguments. - if(inData == null) { - throw new IllegalArgumentException("inData == null!"); - } - if(imageType == null) { - throw new IllegalArgumentException("imageType == null!"); - } - - // If it's one of ours, return a clone. - if (inData instanceof J2KMetadata) { - return (IIOMetadata)((J2KMetadata)inData).clone(); - } - - try { - J2KMetadata outData = new J2KMetadata(); - - List formats = Arrays.asList(inData.getMetadataFormatNames()); - - String format = null; - if(formats.contains(J2KMetadata.nativeMetadataFormatName)) { - // Initialize from native image metadata format. - format = J2KMetadata.nativeMetadataFormatName; - } else if(inData.isStandardMetadataFormatSupported()) { - // Initialize from standard metadata form of the input tree. - format = IIOMetadataFormatImpl.standardMetadataFormatName; - } - - if(format != null) { - outData.setFromTree(format, inData.getAsTree(format)); - return outData; - } - } catch(IIOInvalidTreeException e) { - return null; - } - - return null; - } - - public boolean canWriteRasters() { - return true; - } - - public void write(IIOMetadata streamMetadata, - IIOImage image, - ImageWriteParam param) throws IOException { - if (stream == null) { - throw new IllegalStateException(I18N.getString("J2KImageWriter7")); - } - if (image == null) { - throw new IllegalArgumentException(I18N.getString("J2KImageWriter8")); - } - - clearAbortRequest(); - processImageStarted(0); - RenderedImage input = null; - - boolean writeRaster = image.hasRaster(); - Raster raster = null; - - SampleModel sampleModel = null; - if (writeRaster) { - raster = image.getRaster(); - sampleModel = raster.getSampleModel(); - } else { - input = image.getRenderedImage(); - sampleModel = input.getSampleModel(); - } - - checkSampleModel(sampleModel); - if (param == null) - param = getDefaultWriteParam(); - - J2KImageWriteParamJava j2kwparam = - new J2KImageWriteParamJava(image, param); - - // Packet header cannot exist in two places. - if (j2kwparam.getPackPacketHeaderInTile() && - j2kwparam.getPackPacketHeaderInMain()) - throw new IllegalArgumentException(I18N.getString("J2KImageWriter1")); - - // Lossless and encoding rate cannot be set at the same time - if (j2kwparam.getLossless() && - j2kwparam.getEncodingRate()!=Double.MAX_VALUE) - throw new IllegalArgumentException(I18N.getString("J2KImageWriter2")); - - // If the source image is bilevel or color-indexed, or, the - // encoding rate is Double.MAX_VALUE, use lossless - if ((!writeRaster && input.getColorModel() instanceof IndexColorModel) || - (writeRaster && - raster.getSampleModel() instanceof MultiPixelPackedSampleModel)) { - j2kwparam.setDecompositionLevel("0"); - j2kwparam.setLossless(true); - j2kwparam.setEncodingRate(Double.MAX_VALUE); - j2kwparam.setQuantizationType("reversible"); - j2kwparam.setFilters(J2KImageWriteParam.FILTER_53); - } else if (j2kwparam.getEncodingRate() == Double.MAX_VALUE) { - j2kwparam.setLossless(true); - j2kwparam.setQuantizationType("reversible"); - j2kwparam.setFilters(J2KImageWriteParam.FILTER_53); - } - - // Gets parameters from the write parameter - boolean pphTile = j2kwparam.getPackPacketHeaderInTile(); - boolean pphMain = j2kwparam.getPackPacketHeaderInMain(); - boolean tempSop = false; - boolean tempEph = false; - - int[] bands = param.getSourceBands(); - int ncomp = sampleModel.getNumBands(); - - if (bands != null) - ncomp = bands.length; - - // create the encoding source recognized by jj2000 packages - RenderedImageSrc imgsrc = null; - if (writeRaster) - imgsrc = new RenderedImageSrc(raster, j2kwparam, this); - else - imgsrc = new RenderedImageSrc(input, j2kwparam, this); - - // if the components signed - boolean[] imsigned = new boolean[ncomp]; - if (bands != null) { - for (int i=0; i refx || trefy > refy) - throw new IIOException(I18N.getString("J2KImageWriter4")); - - // Instantiate tiler - Tiler imgtiler = new Tiler(imgsrc,refx,refy,trefx,trefy,tw,th); - - // Creates the forward component transform - ForwCompTransf fctransf = new ForwCompTransf(imgtiler, j2kwparam); - - // Creates ImgDataConverter - ImgDataConverter converter = new ImgDataConverter(fctransf); - - // Creates ForwardWT (forward wavelet transform) - ForwardWT dwt = ForwardWT.createInstance(converter, j2kwparam); - - // Creates Quantizer - Quantizer quant = Quantizer.createInstance(dwt,j2kwparam); - - // Creates ROIScaler - ROIScaler rois = ROIScaler.createInstance(quant, j2kwparam); - - // Creates EntropyCoder - EntropyCoder ecoder = - EntropyCoder.createInstance(rois, j2kwparam, - j2kwparam.getCodeBlockSize(), - j2kwparam.getPrecinctPartition(), - j2kwparam.getBypass(), - j2kwparam.getResetMQ(), - j2kwparam.getTerminateOnByte(), - j2kwparam.getCausalCXInfo(), - j2kwparam.getCodeSegSymbol(), - j2kwparam.getMethodForMQLengthCalc(), - j2kwparam.getMethodForMQTermination()); - - // Rely on rate allocator to limit amount of data - File tmpFile = File.createTempFile("jiio-", ".tmp"); - tmpFile.deleteOnExit(); - - // Creates CodestreamWriter - FileCodestreamWriter bwriter = - new FileCodestreamWriter(tmpFile, Integer.MAX_VALUE); - - // Creates the rate allocator - float rate = (float)j2kwparam.getEncodingRate(); - PostCompRateAllocator ralloc = - PostCompRateAllocator.createInstance(ecoder, - rate, - bwriter, - j2kwparam); - - // Instantiates the HeaderEncoder - HeaderEncoder headenc = - new HeaderEncoder(imgsrc, imsigned, dwt, imgtiler, - j2kwparam, rois,ralloc); - - ralloc.setHeaderEncoder(headenc); - - // Writes header to be able to estimate header overhead - headenc.encodeMainHeader(); - - //Initializes rate allocator, with proper header - // overhead. This will also encode all the data - try { - ralloc.initialize(); - } catch (RuntimeException e) { - if (WRITE_ABORTED.equals(e.getMessage())) { - bwriter.close(); - tmpFile.delete(); - processWriteAborted(); - return; - } else throw e; - } - - // Write header (final) - headenc.reset(); - headenc.encodeMainHeader(); - - // Insert header into the codestream - bwriter.commitBitstreamHeader(headenc); - - // Now do the rate-allocation and write result - ralloc.runAndWrite(); - - //Done for data encoding - bwriter.close(); - - // Calculate file length - int fileLength = bwriter.getLength(); - - // Tile-parts and packed packet headers - int pktspertp = j2kwparam.getPacketPerTilePart(); - int ntiles = imgtiler.getNumTiles(); - if (pktspertp>0 || pphTile || pphMain){ - CodestreamManipulator cm = - new CodestreamManipulator(tmpFile, ntiles, pktspertp, - pphMain, pphTile, tempSop, - tempEph); - fileLength += cm.doCodestreamManipulation(); - } - - // File Format - int nc= imgsrc.getNumComps() ; - int[] bpc = new int[nc]; - for(int comp = 0; compabortRequested
- * to allow the abortions be monitored by J2KRenderedImage. - */ - public boolean getAbortRequest() { - return abortRequested(); - } - - private void checkSampleModel(SampleModel sm) { - int type = sm.getDataType(); - - if (type < DataBuffer.TYPE_BYTE || type > DataBuffer.TYPE_INT) - throw new IllegalArgumentException(I18N.getString("J2KImageWriter5")); - if (sm.getNumBands() > 16384) - throw new IllegalArgumentException(I18N.getString("J2KImageWriter6")); - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterResources.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterResources.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterResources.java 2005-02-11 00:01:35.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterResources.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,57 +0,0 @@ -/* - * $RCSfile: J2KImageWriterResources.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:35 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -public class J2KImageWriterResources { - static final Object[][] contents = { - }; - - public J2KImageWriterResources() {} - - public Object[][] getContents() { - return contents; - } -} - diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterSpi.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterSpi.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterSpi.java 2006-03-31 14:43:39.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KImageWriterSpi.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,139 +0,0 @@ -/* - * $RCSfile: J2KImageWriterSpi.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.2 $ - * $Date: 2006/03/31 19:43:39 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.awt.image.DataBuffer; -import java.awt.image.SampleModel; - -import javax.imageio.spi.ImageWriterSpi; -import javax.imageio.spi.ServiceRegistry; -import javax.imageio.spi.IIORegistry; -import javax.imageio.ImageWriter; -import javax.imageio.ImageTypeSpecifier; -import javax.imageio.IIOException; - -import java.awt.image.ColorModel; -import java.awt.image.IndexColorModel; -import java.util.Locale; - -import com.sun.media.imageioimpl.common.PackageUtil; - -import com.sun.medialib.codec.jiio.Util; - -public class J2KImageWriterSpi extends ImageWriterSpi { - private static String [] readerSpiNames = - {"com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderSpi"}; - private static String[] formatNames = - {"jpeg 2000", "JPEG 2000", "jpeg2000", "JPEG2000"}; - private static String[] extensions = - {"jp2"}; // Should add jpx or jpm - private static String[] mimeTypes = {"image/jp2", "image/jpeg2000"}; - private boolean registered = false; - - public J2KImageWriterSpi() { - super(PackageUtil.getVendor(), - PackageUtil.getVersion(), - formatNames, - extensions, - mimeTypes, - "com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriter", - STANDARD_OUTPUT_TYPE, - readerSpiNames, - false, - null, null, - null, null, - true, - "com_sun_media_imageio_plugins_jpeg2000_image_1.0", - "com.sun.media.imageioimpl.plugins.jpeg2000.J2KMetadataFormat", - null, null); - } - - public String getDescription(Locale locale) { - String desc = PackageUtil.getSpecificationTitle() + - " JPEG 2000 Image Writer"; - return desc; - } - - public void onRegistration(ServiceRegistry registry, - Class category) { - if (registered) { - return; - } - - registered = true; - - // Set pairwise ordering to give codecLib writer precedence. - Class codecLibWriterSPIClass = null; - try { - codecLibWriterSPIClass = - Class.forName("com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriterCodecLibSpi"); - } catch(Throwable t) { - // Ignore it. - } - - if(codecLibWriterSPIClass != null) { - Object codecLibWriterSPI = - registry.getServiceProviderByClass(codecLibWriterSPIClass); - if(codecLibWriterSPI != null) { - registry.setOrdering(category, codecLibWriterSPI, this); - } - } - } - - public boolean canEncodeImage(ImageTypeSpecifier type) { - SampleModel sm = type.getSampleModel(); - if (sm.getNumBands() > 16384) - return false; - if (sm.getDataType() < DataBuffer.TYPE_BYTE || - sm.getDataType() > DataBuffer.TYPE_INT) - return false; - return true; - } - - public ImageWriter createWriterInstance(Object extension) - throws IIOException { - return new J2KImageWriter(this); - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadataFormat.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadataFormat.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadataFormat.java 2005-04-27 14:23:01.000000000 -0400 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadataFormat.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,351 +0,0 @@ -/* - * $RCSfile: J2KMetadataFormat.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.2 $ - * $Date: 2005/04/27 18:23:01 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.awt.image.ColorModel; -import java.awt.image.IndexColorModel; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import javax.imageio.metadata.*; -import javax.imageio.ImageTypeSpecifier; - -public class J2KMetadataFormat extends IIOMetadataFormatImpl { - /** The table to link the child to its parent. - */ - private static Hashtable parents = new Hashtable(); - - static { - //children for the root - parents.put("JPEG2000SignatureBox", "com_sun_media_imageio_plugins_jpeg2000_image_1.0"); - parents.put("JPEG2000FileTypeBox", "com_sun_media_imageio_plugins_jpeg2000_image_1.0"); - parents.put("OtherBoxes", "com_sun_media_imageio_plugins_jpeg2000_image_1.0"); - - // children for the boxes other than - // JPEG2000SignatureBox/JPEG2000FileTypeBox - parents.put("JPEG2000HeaderSuperBox", "OtherBoxes"); - parents.put("JPEG2000CodeStreamBox", "OtherBoxes"); - - parents.put("JPEG2000IntellectualPropertyRightsBox", "OtherBoxes"); - parents.put("JPEG2000XMLBox", "OtherBoxes"); - parents.put("JPEG2000UUIDBox", "OtherBoxes"); - parents.put("JPEG2000UUIDInfoBox", "OtherBoxes"); - - // Children of JPEG2000HeaderSuperBox - parents.put("JPEG2000HeaderBox", "JPEG2000HeaderSuperBox"); - parents.put("OptionalBoxes", "JPEG2000HeaderSuperBox"); - - // Optional boxes in JPEG2000HeaderSuperBox - parents.put("JPEG2000BitsPerComponentBox", "OptionalBoxes"); - parents.put("JPEG2000ColorSpecificationBox", "OptionalBoxes"); - parents.put("JPEG2000PaletteBox", "OptionalBoxes"); - parents.put("JPEG2000ComponentMappingBox", "OptionalBoxes"); - parents.put("JPEG2000ChannelDefinitionBox", "OptionalBoxes"); - parents.put("JPEG2000ResolutionBox", "OptionalBoxes"); - - // Children of JPEG2000ResolutionBox - parents.put("JPEG2000CaptureResolutionBox", "JPEG2000ResolutionBox"); - parents.put("JPEG2000DefaultDisplayResolutionBox", - "JPEG2000ResolutionBox"); - - // Children of JPEG2000UUIDInfoBox - parents.put("JPEG2000UUIDListBox", "JPEG2000UUIDInfoBox"); - parents.put("JPEG2000DataEntryURLBox", "JPEG2000UUIDInfoBox"); - } - - private static J2KMetadataFormat instance; - - public static synchronized J2KMetadataFormat getInstance() { - if (instance == null) - instance = new J2KMetadataFormat(); - return instance; - } - - String resourceBaseName = this.getClass().getName() + "Resources"; - - /** Constructs J2KMetadataFormat. Calls the super - * class constructor. Sets the resource base name. Adds the elements - * into this format object based on the XML schema and DTD. - */ - J2KMetadataFormat() { - super("com_sun_media_imageio_plugins_jpeg2000_image_1.0", CHILD_POLICY_ALL); - setResourceBaseName(resourceBaseName); - addElements(); - } - - /** Adds the elements into this format object based on the XML - * schema and DTD. - */ - private void addElements() { - addElement("JPEG2000SignatureBox", - getParent("JPEG2000SignatureBox"), - CHILD_POLICY_EMPTY); - - addElement("JPEG2000FileTypeBox", - getParent("JPEG2000FileTypeBox"), - CHILD_POLICY_ALL); - addElement("OtherBoxes", - getParent("OtherBoxes"), - CHILD_POLICY_CHOICE); - - addElement("JPEG2000HeaderSuperBox", - getParent("JPEG2000HeaderSuperBox"), - CHILD_POLICY_CHOICE); - addElement("JPEG2000CodeStreamBox", - getParent("JPEG2000CodeStreamBox"), - CHILD_POLICY_EMPTY); - addElement("JPEG2000IntellectualPropertyRightsBox", - getParent("JPEG2000IntellectualPropertyRightsBox"), - CHILD_POLICY_ALL); - addElement("JPEG2000XMLBox", - getParent("JPEG2000XMLBox"), - CHILD_POLICY_ALL); - addElement("JPEG2000UUIDBox", - getParent("JPEG2000UUIDBox"), - CHILD_POLICY_ALL); - addElement("JPEG2000UUIDInfoBox", - getParent("JPEG2000UUIDInfoBox"), - CHILD_POLICY_ALL); - - addElement("JPEG2000HeaderBox", - "JPEG2000HeaderSuperBox", - CHILD_POLICY_ALL); - addElement("OptionalBoxes", - "JPEG2000HeaderSuperBox", - CHILD_POLICY_CHOICE); - addElement("JPEG2000BitsPerComponentBox", - "OptionalBoxes", - CHILD_POLICY_ALL); - addElement("JPEG2000ColorSpecificationBox", - "OptionalBoxes", - CHILD_POLICY_ALL); - addElement("JPEG2000PaletteBox", - "OptionalBoxes", - CHILD_POLICY_ALL); - addElement("JPEG2000ComponentMappingBox", - "OptionalBoxes", - CHILD_POLICY_ALL); - addElement("JPEG2000ChannelDefinitionBox", - "OptionalBoxes", - CHILD_POLICY_ALL); - addElement("JPEG2000ResolutionBox", - "OptionalBoxes", - CHILD_POLICY_ALL); - - addElement("JPEG2000CaptureResolutionBox", - "JPEG2000ResolutionBox", - CHILD_POLICY_ALL); - addElement("JPEG2000DefaultDisplayResolutionBox", - "JPEG2000ResolutionBox", - CHILD_POLICY_ALL); - - addElement("JPEG2000UUIDListBox", - "JPEG2000UUIDInfoBox", - CHILD_POLICY_ALL); - addElement("JPEG2000DataEntryURLBox", - "JPEG2000UUIDInfoBox", - CHILD_POLICY_ALL); - // Adds the default attributes "Length", "Type" and "ExtraLength" into - // the J2K box-related data elements - Enumeration keys = parents.keys(); - while (keys.hasMoreElements()) { - String s = (String)keys.nextElement(); - if (s.startsWith("JPEG2000")) { - addAttribute(s, "Length", DATATYPE_INTEGER, true, null); - addAttribute(s, "Type", DATATYPE_STRING, true, Box.getTypeByName(s)); - addAttribute(s, "ExtraLength", DATATYPE_STRING, false, null); - - // If it is a simple node, adds the data elements by using - // relection. - Class c = Box.getBoxClass(Box.getTypeInt(Box.getTypeByName(s))); - - try { - Method m = c.getMethod("getElementNames", (Class[])null); - String[] elementNames = (String[])m.invoke(null, - (Object[])null); - for (int i = 0; i < elementNames.length; i++) - addElement(elementNames[i], s, CHILD_POLICY_EMPTY); - } catch (Exception e) { - // no such method - } - } - } - - addAttribute("JPEG2000SignatureBox", - "Signature", - DATATYPE_STRING, - true, - "0D0A870A"); - - addElement("BitDepth", - "JPEG2000BitsPerComponentBox", - CHILD_POLICY_EMPTY); - - addElement("NumberEntries", - "JPEG2000PaletteBox", - CHILD_POLICY_EMPTY); - - addElement("NumberColors", - "JPEG2000PaletteBox", - CHILD_POLICY_EMPTY); - - addElement("BitDepth", - "JPEG2000PaletteBox", - CHILD_POLICY_EMPTY); - - addElement("LUT", - "JPEG2000PaletteBox", - 1, 1024); - - addElement("LUTRow", - "LUT", - CHILD_POLICY_EMPTY); - - addElement("Component", - "JPEG2000ComponentMappingBox", - CHILD_POLICY_EMPTY); - - addElement("ComponentType", - "JPEG2000ComponentMappingBox", - CHILD_POLICY_EMPTY); - - addElement("ComponentAssociation", - "JPEG2000ComponentMappingBox", - CHILD_POLICY_EMPTY); - - addElement("NumberOfDefinition", - "JPEG2000ChannelDefinitionBox", - CHILD_POLICY_EMPTY); - - addElement("Definitions", - "JPEG2000ChannelDefinitionBox", - 0, 9); - - addElement("ChannelNumber", - "Definitions", - CHILD_POLICY_EMPTY); - - addElement("ChannelType", - "Definitions", - CHILD_POLICY_EMPTY); - addElement("ChannelAssociation", - "Definitions", - CHILD_POLICY_EMPTY); - addElement("CodeStream", - "JPEG2000CodeStreamBox", - CHILD_POLICY_EMPTY); - addElement("Content", - "JPEG2000IntellectualPropertyRightsBox", - CHILD_POLICY_EMPTY); - addElement("Content", - "JPEG2000XMLBox", - CHILD_POLICY_EMPTY); - addElement("UUID", - "JPEG2000UUIDBox", - CHILD_POLICY_EMPTY); - addElement("Data", - "JPEG2000UUIDBox", - CHILD_POLICY_EMPTY); - addElement("NumberUUID", - "JPEG2000UUIDListBox", - CHILD_POLICY_EMPTY); - addElement("UUID", - "JPEG2000UUIDListBox", - CHILD_POLICY_EMPTY); - addElement("Version", - "JPEG2000DataEntryURLBox", - CHILD_POLICY_EMPTY); - addElement("Flags", - "JPEG2000DataEntryURLBox", - CHILD_POLICY_EMPTY); - addElement("URL", - "JPEG2000DataEntryURLBox", - CHILD_POLICY_EMPTY); - } - - public String getParent(String elementName) { - return (String)parents.get(elementName); - } - - public boolean canNodeAppear(String elementName, - ImageTypeSpecifier imageType) { - ColorModel cm = imageType.getColorModel(); - if (!(cm instanceof IndexColorModel)) - if ("JPEG2000PaletteBox".equals(elementName)) - return false; - if (!cm.hasAlpha()) - if ("JPEG2000ChannelDefinitionBox".equals(elementName)) - return false; - - if (getParent(elementName) != null) - return true; - return false; - } - - public boolean isLeaf(String name) { - Set keys = parents.keySet(); - Iterator iterator = keys.iterator(); - while(iterator.hasNext()) { - if (name.equals(parents.get(iterator.next()))) - return false; - } - - return true; - } - - public boolean singleInstance(String name) { - return !(name.equals("JPEG2000IntellectualPropertyRightsBox") || - name.equals("JPEG2000XMLBox") || - name.equals("JPEG2000UUIDBox") || - name.equals("JPEG2000UUIDInfoBox") || - name.equals("JPEG2000UUIDListBox") || - name.equals("JPEG2000DataEntryURLBox")); - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadataFormatResources.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadataFormatResources.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadataFormatResources.java 2005-02-11 00:01:35.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadataFormatResources.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,280 +0,0 @@ -/* - * $RCSfile: J2KMetadataFormatResources.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:35 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.util.*; - -public class J2KMetadataFormatResources extends ListResourceBundle { - static final Object[][] contents = { - // Node name, followed by description - {"JPEG2000SignatureBox", "The JPEG 2000 signature box."}, - {"JPEG2000FileTypeBox", "The JPEG 2000 file type box."}, - {"OtherBoxes", - "All the boxes other than the signature or file type box."}, - {"HeaderCStream", - "The super box conatins the header and code stream box."}, - {"JPEG2000IntellectualPropertyRightsBox", - "The JPEG 2000 intellectual property rights box."}, - {"JPEG2000XMLBox", "The JPEG 2000 XML box."}, - {"JPEG2000UUIDBox", "The JPEG 2000 UUID box."}, - {"JPEG2000UUIDInfoBox", "The JPEG 2000 UUID information box."}, - {"JPEG2000HeaderSuperBox", "The JPEG 2000 header super box."}, - {"JPEG2000CodeStreamBox", "The JPEG 2000 code stream box."}, - {"JPEG2000HeaderBox", "The JPEG 2000 header box."}, - {"OptionalBoxes", "The optional boxes in the header super box."}, - {"JPEG2000BitsPerComponentBox", "The JPEG2000 bits per component box."}, - {"JPEG2000ColorSpecificationBox", - "The JPEG 2000 color specification box."}, - {"JPEG2000PaletteBox", "The JPEG 2000 palette box."}, - {"JPEG2000ComponentMappingBox", "The JPEG 2000 component mapping box."}, - {"JPEG2000ChannelDefinitionBox", - "The JPEG 2000 channel definition box."}, - {"JPEG2000ResolutionBox", "The JPEG 2000 resolution box."}, - {"JPEG2000CaptureResolutionBox", - "The JPEG 2000 capture resolution box"}, - {"JPEG2000DefaultDisplayResolutionBox", - "The JPEG 2000 default display resolution box"}, - {"JPEG2000UUIDListBox", "The JPEG 2000 UUID list box."}, - {"JPEG2000DataEntryURLBox", "The JPEG 2000 data entry URL box."}, - - // Elements in JPEG2000FileTypeBox - {"Brand", "The brand of JPEG 2000 file. For JP2 file, it is \"jp2 \""}, - {"MinorVersion", - "The minor version of JPEG 2000 file. For JP2 file, it is 0"}, - {"CompatibilityList", - "The compatibility list. For non-JP2 file, at least one is \"jp2 \""}, - - // Elements of JPEG2000HeaderBox - {"Width", "The width of the image."}, - {"Height", "The height of the image."}, - {"NumComponents", "The number of image components in this image file."}, - {"BitDepth", - "Bit depths for all the image components or for each of the component if it is a array."}, - {"CompressionType", "The compression type. Always be 7 for JP2 file."}, - {"UnknownColorspace", "Whether the color space is known or not."}, - {"IntellectualProperty", - "Whether intellectual property in included in this image."}, - - - {"Method", - "The method to define the color space. 1 by ECS; 2 by profile."}, - {"Precedence", "Precedence. Be 0 for JP2 file."}, - {"ApproximationAccuracy", "Approximation accuracy. Be 0 for JP2 file"}, - {"EnumeratedColorSpace", "Enumerated color space. 16: sRGB. 17: Gray"}, - {"ICCProfile", "The ICC profile used to define the color space"}, - - {"NumberEntries", "The number of palette entries."}, - {"NumberColors", "The number of color components."}, - {"BitDepth", "The bit depths for the output components after LUT."}, - {"LUT", "The LUT for the palette."}, - {"LUTRow", " A row of the LUT."}, - - {"Component", "A component in the component mapping box."}, - {"ComponentType", "The type of one component: itself or lut column."}, - {"ComponentAssociation", - "The LUT column used to define this component."}, - - {"NumberOfDefinition", - "The number of definitions in channel definition box."}, - {"Definitions", "Defines one channel."}, - {"ChannelNumber", "The channel number."}, - {"ChannelType", "The channel type: color, alpha, premultiplied alpha."}, - {"ChannelAssociation", - "The association of this channel to the color space."}, - - {"VerticalResolutionNumerator", "The vertical resolution numerator."}, - {"VerticalResolutionDenominator", - "The vertical resolution denominator."}, - {"HorizontalResolutionNumerator", - "The horizontal resolution numerator."}, - {"HorizontalResolutionDenominator", - "The horizontal resolution denominator."}, - {"VerticalResolutionExponent", "The vertical resolution exponent."}, - {"HorizontalResolutionExponent", "The horizontal resolution exponent."}, - - {"CodeStream", "The data of the code stream."}, - {"Content", "The intellectual property rights or XML."}, - - {"UUID", "The UUID."}, - {"Data", "The data of the UUID."}, - {"NumberUUID", "The number of UUID in the UUID list box."}, - - {"Version", "The version. Always be 0 for JP2 file."}, - {"Flags", "The flags. Always be 0 for JP2 file."}, - {"URL", "The URL"}, - - // Node name + "/" + AttributeName, followed by description - {"JPEG2000SignatureBox/Length", - "The length of the signature box. Always be 12."}, - {"JPEG2000SignatureBox/Type", - "The type of the signature box. Always be \"jP \""}, - {"JPEG2000SignatureBox/Signature", - "The content of the signature box. Always be 0D0A870A."}, - - {"JPEG2000FileTypeBox/Length", "The length of the file type box."}, - {"JPEG2000FileTypeBox/Type", - "The type of the file type box. Always be \"ftpy\""}, - {"JPEG2000FileTypeBox/ExtraLength", - "The extra length of the file type box. Optional. Set when Length = 1"}, - - {"JPEG2000HeaderSuperBox/Length", - "The length of the header super box."}, - {"JPEG2000HeaderSuperBox/Type", - "The type of the header super box. Always be \"jp2h\""}, - {"JPEG2000HeaderSuperBox/ExtraLength", - "The extra length of the header super box. Optional. Set when Length = 1"}, - - {"JPEG2000HeaderBox/Length", "The length of the header box."}, - {"JPEG2000HeaderBox/Type", - "The type of the header box. Always be \"ihdr\""}, - {"JPEG2000HeaderBox/ExtraLength", - "The extra length of the header box. Optional. Set when Length = 1"}, - - {"JPEG2000BitsPerComponentBox/Length", - "The length of the bits per component box."}, - {"JPEG2000BitsPerComponentBox/Type", - "The type of the bits per component box. Always be \"bpcc\""}, - {"JPEG2000BitsPerComponentBox/ExtraLength", - "The extra length of the bits per component box. Optional. Set when Length = 1"}, - - {"JPEG2000ColorSpecificationBox/Length", - "The length of the bits per component box."}, - {"JPEG2000ColorSpecificationBox/Type", - "The type of the bits per component box. Always be \"colr\""}, - {"JPEG2000ColorSpecificationBox/ExtraLength", - "The extra length of the bits per component box. Optional. Set when Length = 1"}, - - {"JPEG2000PaletteBox/Length", "The length of the palette box."}, - {"JPEG2000PaletteBox/Type", - "The type of the palette box. Always be \"pclr\""}, - {"JPEG2000PaletteBox/ExtraLength", - "The extra length of the palette box. Optional. Set when Length = 1"}, - - {"JPEG2000ComponentMappingBox/Length", - "The length of the component mapping box."}, - {"JPEG2000ComponentMappingBox/Type", - "The type of the component mapping box. Always be \"cmap\""}, - {"JPEG2000ComponentMappingBox/ExtraLength", - "The extra length of the component mapping box. Optional. Set when Length = 1"}, - - {"JPEG2000ChannelDefinitionBox/Length", - "The length of the channel definition box."}, - {"JPEG2000ChannelDefinitionBox/Type", - "The type of the channel definition box. Always be \"cdef\""}, - {"JPEG2000ChannelDefinitionBox/ExtraLength", - "The extra length of the channel definition box. Optional. Set when Length = 1"}, - - {"JPEG2000ResolutionBox/Length", "The length of the resolution box."}, - {"JPEG2000ResolutionBox/Type", - "The type of the resolution box. Always be \"res \""}, - {"JPEG2000ResolutionBox/ExtraLength", - "The extra length of the resolution box. Optional. Set when Length = 1"}, - - {"JPEG2000CaptureResolutionBox/Length", - "The length of the capture resolution box."}, - {"JPEG2000CaptureResolutionBox/Type", - "The type of the capture resolution box. Always be \"resc\""}, - {"JPEG2000CaptureResolutionBox/ExtraLength", - "The extra length of the capture resolution box. Optional. Set when Length = 1"}, - - {"JPEG2000DefaultDisplayResolutionBox/Length", - "The length of the default display resolution box."}, - {"JPEG2000DefaultDisplayResolutionBox/Type", - "The type of the default display resolution box. Always be \"resd\""}, - {"JPEG2000DefaultDisplayResolutionBox/ExtraLength", - "The extra length of the default display resolution box. Optional. Set when Length = 1"}, - - {"JPEG2000CodeStreamBox/Length", "The length of the code stream box."}, - {"JPEG2000CodeStreamBox/Type", - "The type of the code stream box. Always be \"jp2c\""}, - {"JPEG2000CodeStreamBox/ExtraLength", - "The extra length of the code stream box. Optional. Set when Length = 1"}, - - {"JPEG2000IntellectualPropertyRightsBox/Length", - "The length of the intellectual property rights box."}, - {"JPEG2000IntellectualPropertyRightsBox/Type", - "The type of the intellectual property rights box. Always be \"jp2i\""}, - {"JPEG2000IntellectualPropertyRightsBox/ExtraLength", - "The extra length of the intellectual property rights box. Optional. Set when Length = 1"}, - - {"JPEG2000XMLBox/Length", "The length of the XML box."}, - {"JPEG2000XMLBox/Type", "The type of the XML box. Always be \"xml \""}, - {"JPEG2000XMLBox/ExtraLength", - "The extra length of the XML box. Optional. Set when Length = 1"}, - - {"JPEG2000UUIDBox/Length", "The length of the UUID box."}, - {"JPEG2000UUIDBox/Type", - "The type of the UUID box. Always be \"uuid\""}, - {"JPEG2000UUIDBox/ExtraLength", - "The extra length of the UUID box. Optional. Set when Length = 1"}, - - {"JPEG2000UUIDInfoBox/Length", "The length of the UUID information box."}, - {"JPEG2000UUIDInfoBox/Type", - "The type of the UUID information box. Always be \"uinf\""}, - {"JPEG2000UUIDInfoBox/ExtraLength", - "The extra length of the UUID information box. Optional. Set when Length = 1"}, - - {"JPEG2000UUIDListBox/Length", "The length of the UUID list box."}, - {"JPEG2000UUIDListBox/Type", - "The type of the UUID list box. Always be \"ulst\""}, - {"JPEG2000UUIDListBox/ExtraLength", - "The extra length of the UUID list box. Optional. Set when Length = 1"}, - - {"JPEG2000DataEntryURLBox/Length", - "The length of the data entry URL box."}, - {"JPEG2000DataEntryURLBox/Type", - "The type of the data entry URL box. Always be \"ulst\""}, - {"JPEG2000DataEntryURLBox/ExtraLength", - "The extra length of the data entry URL box. Optional. Set when Length = 1"}, - }; - - public J2KMetadataFormatResources() { - } - - protected Object[][] getContents() { - return contents; - } -} - diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadata.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadata.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadata.java 2006-09-22 19:07:25.000000000 -0400 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KMetadata.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,1051 +0,0 @@ -/* - * $RCSfile: J2KMetadata.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.4 $ - * $Date: 2006/09/22 23:07:25 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.io.InputStream; - -import javax.imageio.ImageTypeSpecifier; -import javax.imageio.ImageWriteParam; -import javax.imageio.ImageWriter; -import javax.imageio.IIOException; -import javax.imageio.stream.ImageInputStream; -import javax.imageio.stream.ImageOutputStream; -import javax.imageio.metadata.IIOMetadata; -import javax.imageio.metadata.IIOMetadataNode; -import javax.imageio.metadata.IIOMetadataFormat; -import javax.imageio.metadata.IIOMetadataFormatImpl; -import javax.imageio.metadata.IIOInvalidTreeException; - -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.NamedNodeMap; - -import java.util.List; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.ListIterator; -import java.io.IOException; -import java.awt.color.ICC_Profile; -import java.awt.color.ICC_ColorSpace; -import java.awt.color.ColorSpace; -import java.awt.image.ColorModel; -import java.awt.image.DataBuffer; -import java.awt.image.IndexColorModel; -import java.awt.image.SampleModel; -import java.awt.Point; - -import com.sun.media.imageio.plugins.jpeg2000.J2KImageReadParam; -import com.sun.media.imageio.plugins.jpeg2000.J2KImageWriteParam; - -import jj2000.j2k.fileformat.FileFormatBoxes; -import jj2000.j2k.fileformat.reader.FileFormatReader; -import jj2000.j2k.io.RandomAccessIO; - -/** - * Metadata for the J2K plug-in. - */ -public class J2KMetadata extends IIOMetadata implements Cloneable { - static final String nativeMetadataFormatName = - "com_sun_media_imageio_plugins_jpeg2000_image_1.0"; - - /** cache the metadata format */ - private J2KMetadataFormat format; - - /** The boxes of JP2 file used as meta data, i. e., all the boxes - * except the data stream box - */ - private ArrayList boxes = new ArrayList(); - - /** - * Constructor containing code shared by other constructors. - */ - public J2KMetadata() { - super(true, // Supports standard format - nativeMetadataFormatName, // and a native format - "com.sun.media.imageioimpl.plugins.jpeg2000.J2KMetadataFormat", - null, null); // No other formats - - format = (J2KMetadataFormat)getMetadataFormat(nativeMetadataFormatName); - } - - /* - * Constructs a J2KMetadata object by reading the - * contents of an ImageInputStream. Has package-only - * access. - * - * @param iis An ImageInputStream from which to read - * the metadata. - * @param reader The J2KImageReader calling this - * constructor, to which warnings should be sent. - */ - public J2KMetadata(ImageInputStream iis, - J2KImageReader reader) throws IOException { - this(); - RandomAccessIO in = new IISRandomAccessIO(iis); - - iis.mark(); - // **** File Format **** - // If the codestream is wrapped in the jp2 fileformat, Read the - // file format wrapper - FileFormatReader ff = new FileFormatReader(in, this); - ff.readFileFormat(); - iis.reset(); - } - - /** - * Constructs a default stream J2KMetadata object appropriate - * for the given write parameters. - */ - public J2KMetadata(ImageWriteParam param, ImageWriter writer) { - this(null, param, writer); - } - - /** - * Constructs a default image J2KMetadata object appropriate - * for the given image type and write parameters. - */ - public J2KMetadata(ImageTypeSpecifier imageType, - ImageWriteParam param, - ImageWriter writer) { - this(imageType != null ? imageType.getColorModel() : null, - imageType != null ? imageType.getSampleModel() : null, - 0, 0, - param, writer); - } - - /** - * Constructs a default image J2KMetadata object appropriate - * for the given image type and write parameters. - */ - public J2KMetadata(ColorModel colorModel, - SampleModel sampleModel, - int width, - int height, - ImageWriteParam param, - ImageWriter writer) { - this(); - addNode(new SignatureBox()); - addNode(new FileTypeBox(0x6A703220, 0, new int[]{0x6A703220})); - - ImageTypeSpecifier destType = null; - - if (param != null) { - destType = param.getDestinationType(); - if (colorModel == null && sampleModel == null) { - colorModel = destType == null ? null : destType.getColorModel(); - sampleModel = - destType == null ? null : destType.getSampleModel(); - } - } - - int[] bitDepths = null; - if(colorModel != null) { - bitDepths = colorModel.getComponentSize(); - } else if(sampleModel != null) { - bitDepths = sampleModel.getSampleSize(); - } - - int bitsPerComponent = 0xff; - if(bitDepths != null) { - bitsPerComponent = bitDepths[0]; - int numComponents = bitDepths.length; - for(int i = 1; i < numComponents; i++) { - /* XXX: This statement should be removed when BPC behavior - is corrected as derscribed below. */ - if(bitDepths[i] > bitsPerComponent) { - bitsPerComponent = bitDepths[i]; - } - /* XXX: When the number of bits per component is not the - same for all components the BPC parameter of the Image - Header box should be set to 0xff and the actual number of - bits per component written in the Bits Per Component box. - if(bitDepths[i] != bitsPerComponent) { - bitsPerComponent = 0xff; - break; - } - */ - } - } - - if (colorModel != null) { - ColorSpace cs = colorModel.getColorSpace(); - boolean iccColor = (cs instanceof ICC_ColorSpace); - int type = cs.getType(); - - if (type == ColorSpace.TYPE_RGB) { - addNode(new ColorSpecificationBox((byte)1, - (byte)0, (byte)0, - ColorSpecificationBox.ECS_sRGB, - null)); - } else if (type == ColorSpace.TYPE_GRAY) - addNode(new ColorSpecificationBox((byte)1, - (byte)0, (byte)0, - ColorSpecificationBox.ECS_GRAY, - null)); - else if (cs instanceof ICC_ColorSpace) - addNode(new ColorSpecificationBox((byte)2, - (byte)0, (byte)0, - 0, - ((ICC_ColorSpace)cs).getProfile())); - - if (colorModel.hasAlpha()) { - addNode(new ChannelDefinitionBox(colorModel)); - } - - if (colorModel instanceof IndexColorModel) { - addNode(new PaletteBox((IndexColorModel)colorModel)); - int numComp = colorModel.getComponentSize().length; - short[] channels = new short[numComp]; - byte[] types = new byte[numComp]; - byte[] maps = new byte[numComp]; - for (int i = 0; i < numComp; i++) { - channels[i] = 0; - types[i] = 1; - maps[i] = (byte)i; - } - addNode(new ComponentMappingBox(channels, types, maps)); - } - } - - if (sampleModel != null) { - if (width <= 0) - width = sampleModel.getWidth(); - if (height <= 0) - height = sampleModel.getHeight(); - int bpc = bitsPerComponent == 0xff ? - 0xff : ((bitsPerComponent - 1) | - (isOriginalSigned(sampleModel) ? 0x80 : 0)); - addNode(new HeaderBox(height, - width, - sampleModel.getNumBands(), - bpc, - 7, - colorModel == null ? 1 : 0, - getElement("JPEG2000IntellectualPropertyRightsBox")==null ? 0 : 1)); - } - } - - public Object clone() { - J2KMetadata theClone = null; - - try { - theClone = (J2KMetadata) super.clone(); - } catch (CloneNotSupportedException e) {} // won't happen - - if (boxes != null) { - int numBoxes = boxes.size(); - for(int i = 0; i < numBoxes; i++) { - theClone.addNode((Box)boxes.get(i)); - } - } - return theClone; - } - - public Node getAsTree(String formatName) { - if (formatName == null) { - throw new IllegalArgumentException(I18N.getString("J2KMetadata0")); - } - - if (formatName.equals(nativeMetadataFormatName)) { - return getNativeTree(); - } - - if (formatName.equals - (IIOMetadataFormatImpl.standardMetadataFormatName)) { - return getStandardTree(); - } - - throw new IllegalArgumentException(I18N.getString("J2KMetadata1") - + " " + formatName); - } - - IIOMetadataNode getNativeTree() { - IIOMetadataNode root = - new IIOMetadataNode(nativeMetadataFormatName); - - Box signatureBox = null, fileTypeBox = null, headerBox = null; - int signatureIndex = -1, fileTypeIndex = -1, headerIndex = -1; - - int numBoxes = boxes.size(); - - int found = 0; - for(int i = 0; i < numBoxes && found < 3; i++) { - Box box = (Box)boxes.get(i); - if(Box.getName(box.getType()).equals("JPEG2000SignatureBox")) { - signatureBox = box; - signatureIndex = i; - found++; - } else if(Box.getName(box.getType()).equals("JPEG2000FileTypeBox")) { - fileTypeBox = box; - fileTypeIndex = i; - found++; - } else if(Box.getName(box.getType()).equals("JPEG2000HeaderBox")) { - headerBox = box; - headerIndex = i; - found++; - } - } - - if(signatureBox != null) { - insertNodeIntoTree(root, signatureBox.getNativeNode()); - } - - if(fileTypeBox != null) { - insertNodeIntoTree(root, fileTypeBox.getNativeNode()); - } - - if(headerBox != null) { - insertNodeIntoTree(root, headerBox.getNativeNode()); - } - - for(int i = 0; i < numBoxes; i++) { - if(i == signatureIndex || - i == fileTypeIndex || - i == headerIndex) continue; - Box box = (Box)boxes.get(i); - IIOMetadataNode node = box.getNativeNode(); - insertNodeIntoTree(root, node); - } - return root; - } - - // Standard tree node methods - protected IIOMetadataNode getStandardChromaNode() { - HeaderBox header = (HeaderBox)getElement("JPEG2000HeaderBox"); - PaletteBox palette = (PaletteBox)getElement("JPEG2000PaletteBox"); - ColorSpecificationBox color = - (ColorSpecificationBox)getElement("JPEG2000ColorSpecificationBox"); - - IIOMetadataNode node = new IIOMetadataNode("Chroma"); - IIOMetadataNode subNode = null; - if (header != null) { - if (header.getUnknownColorspace() == 0) { - if (color != null && color.getMethod() == 1) { - subNode = new IIOMetadataNode("ColorSpaceType"); - int ecs = color.getEnumeratedColorSpace(); - if (ecs == FileFormatBoxes.CSB_ENUM_SRGB) - subNode.setAttribute("name", "RGB"); - if (ecs == FileFormatBoxes.CSB_ENUM_GREY) - subNode.setAttribute("name", "GRAY"); - node.appendChild(subNode); - } - } - - subNode = new IIOMetadataNode("NumChannels"); - subNode.setAttribute("value", "" + header.getNumComponents()); - node.appendChild(subNode); - - if (palette != null) { - subNode.setAttribute("value", "" + palette.getNumComp()); - subNode = new IIOMetadataNode("Palette"); - byte[][] lut = palette.getLUT(); - - int size = lut[0].length; - int numComp = lut.length; - - for (int i = 0; i < size; i++) { - IIOMetadataNode subNode1 = - new IIOMetadataNode("PaletteEntry"); - subNode1.setAttribute("index", ""+i); - subNode1.setAttribute("red", "" + (lut[0][i]&0xff)); - subNode1.setAttribute("green", "" + (lut[1][i]&0xff)); - subNode1.setAttribute("blue", "" + (lut[2][i]&0xff)); - if (numComp == 4) - subNode1.setAttribute("alpha", "" + (lut[3][i]&0xff)); - subNode.appendChild(subNode1); - } - node.appendChild(subNode); - } - } - return node; - } - - protected IIOMetadataNode getStandardCompressionNode() { - IIOMetadataNode node = new IIOMetadataNode("Compression"); - - // CompressionTypeName - IIOMetadataNode subNode = new IIOMetadataNode("CompressionTypeName"); - subNode.setAttribute("value", "JPEG2000"); - node.appendChild(subNode); - return node; - } - - protected IIOMetadataNode getStandardDataNode() { - IIOMetadataNode node = new IIOMetadataNode("Data"); - PaletteBox palette = (PaletteBox)getElement("JPEG2000PaletteBox"); - boolean sampleFormat = false; - - if (palette != null) { - IIOMetadataNode subNode = new IIOMetadataNode("SampleFormat"); - subNode.setAttribute("value", "Index"); - node.appendChild(subNode); - sampleFormat = true; - } - - BitsPerComponentBox bitDepth = - (BitsPerComponentBox)getElement("JPEG2000BitsPerComponentBox"); - String value = ""; - boolean signed = false; - boolean gotSampleInfo = false; - - // JPEG 2000 "B" parameter represents "bitDepth - 1" in the - // right 7 least significant bits with the most significant - // bit indicating signed if set and unsigned if not. - if (bitDepth != null) { - byte[] bits = bitDepth.getBitDepth(); - if ((bits[0] & 0x80) == 0x80) - signed = true; - - int numComp = bits.length; - for (int i = 0; i < numComp; i++) { - value += (bits[i] & 0x7f) + 1; - if(i != numComp - 1) value += " "; - } - - gotSampleInfo = true; - } else { - HeaderBox header = (HeaderBox)getElement("JPEG2000HeaderBox"); - if(header != null) { - int bits = header.getBitDepth(); - if ((bits & 0x80) == 0x80) - signed = true; - bits = (bits & 0x7f) + 1; - int numComp = header.getNumComponents(); - for (int i = 0; i < numComp; i++) { - value += bits; - if(i != numComp - 1) value += " "; - } - - gotSampleInfo = true; - } - } - - IIOMetadataNode subNode = null; - - if(gotSampleInfo) { - subNode = new IIOMetadataNode("BitsPerSample"); - subNode.setAttribute("value", value); - node.appendChild(subNode); - } - - subNode = new IIOMetadataNode("PlanarConfiguration"); - subNode.setAttribute("value", "TileInterleaved"); - node.appendChild(subNode); - - if (!sampleFormat && gotSampleInfo) { - subNode = new IIOMetadataNode("SampleFormat"); - subNode.setAttribute("value", - signed ? "SignedIntegral": "UnsignedIntegral"); - node.appendChild(subNode); - } - - return node; - } - - protected IIOMetadataNode getStandardDimensionNode() { - ResolutionBox box = - (ResolutionBox)getElement("JPEG2000CaptureResolutionBox"); - if (box != null) { - IIOMetadataNode node = new IIOMetadataNode("Dimension"); - float hRes = box.getHorizontalResolution(); - float vRes = box.getVerticalResolution(); - float ratio = vRes / hRes; - IIOMetadataNode subNode = new IIOMetadataNode("PixelAspectRatio"); - subNode.setAttribute("value", "" + ratio); - node.appendChild(subNode); - - subNode = new IIOMetadataNode("HorizontalPixelSize"); - subNode.setAttribute("value", "" + (1000 / hRes)); - node.appendChild(subNode); - - subNode = new IIOMetadataNode("VerticalPixelSize"); - subNode.setAttribute("value", "" + (1000 / vRes)); - node.appendChild(subNode); - - return node; - } - - return null; - } - - protected IIOMetadataNode getStandardTransparencyNode() { - ChannelDefinitionBox channel = - (ChannelDefinitionBox)getElement("JPEG2000ChannelDefinitionBox"); - if (channel != null) { - IIOMetadataNode node = new IIOMetadataNode("Transparency"); - - boolean hasAlpha = false; - boolean isPremultiplied = false; - short[] type = channel.getTypes(); - - for (int i = 0; i < type.length; i++) { - if (type[i] == 1) - hasAlpha = true; - if (type[i] == 2) - isPremultiplied = true; - } - - String value = "none"; - if (isPremultiplied) - value = "premultiplied"; - else if (hasAlpha) - value = "nonpremultiplied"; - - IIOMetadataNode subNode = new IIOMetadataNode("Alpha"); - subNode.setAttribute("value", value); - node.appendChild(subNode); - - return node; - } - - IIOMetadataNode node = new IIOMetadataNode("Transparency"); - IIOMetadataNode subNode = new IIOMetadataNode("Alpha"); - subNode.setAttribute("value", "none"); - node.appendChild(subNode); - - return null; - } - - protected IIOMetadataNode getStandardTextNode() { - if (boxes == null) - return null; - IIOMetadataNode text = null; - - Iterator iterator = boxes.iterator(); - - while(iterator.hasNext()) { - Box box = (Box)iterator.next(); - if (box instanceof XMLBox) { - if (text == null) - text = new IIOMetadataNode("Text"); - IIOMetadataNode subNode = new IIOMetadataNode("TextEntry"); - String content = new String(box.getContent()); - subNode.setAttribute("value", content); - text.appendChild(subNode); - } - } - return text; - } - - public boolean isReadOnly() { - return false; - } - - public void mergeTree(String formatName, Node root) - throws IIOInvalidTreeException { - if (formatName == null) { - throw new IllegalArgumentException(I18N.getString("J2KMetadata0")); - } - - if (root == null) { - throw new IllegalArgumentException(I18N.getString("J2KMetadata2")); - } - - if (formatName.equals(nativeMetadataFormatName) && - root.getNodeName().equals(nativeMetadataFormatName)) { - mergeNativeTree(root); - } else if (formatName.equals - (IIOMetadataFormatImpl.standardMetadataFormatName)) { - mergeStandardTree(root); - } else { - throw new IllegalArgumentException(I18N.getString("J2KMetadata1") - + " " + formatName); - } - } - - public void setFromTree(String formatName, Node root) - throws IIOInvalidTreeException { - if (formatName == null) { - throw new IllegalArgumentException(I18N.getString("J2KMetadata0")); - } - - if (root == null) { - throw new IllegalArgumentException(I18N.getString("J2KMetadata2")); - } - - if (formatName.equals(nativeMetadataFormatName) && - root.getNodeName().equals(nativeMetadataFormatName)) { - boxes = new ArrayList(); - mergeNativeTree(root); - } else if (formatName.equals - (IIOMetadataFormatImpl.standardMetadataFormatName)) { - boxes = new ArrayList(); - mergeStandardTree(root); - } else { - throw new IllegalArgumentException(I18N.getString("J2KMetadata1") - + " " + formatName); - } - } - - public void reset() { - boxes.clear(); - } - - public void addNode(Box node) { - if (boxes == null) - boxes = new ArrayList(); - replace(Box.getName(node.getType()), node); - } - - public Box getElement(String name) { - for (int i = boxes.size() - 1; i >= 0; i--) { - Box box = (Box)boxes.get(i); - if (name.equals(Box.getName(box.getType()))) - return box; - } - return null; - } - - private void mergeNativeTree(Node root) throws IIOInvalidTreeException { - NodeList list = root.getChildNodes(); - for (int i = list.getLength() - 1; i >= 0; i--) { - Node node = list.item(i); - String name = node.getNodeName(); - if (format.getParent(name) != null) { - if (format.isLeaf(name)) { - String s = (String)Box.getAttribute(node, "Type"); - Box box = Box.createBox(Box.getTypeInt(s), node); - if (format.singleInstance(name)&&getElement(name) != null) { - replace(name, box); - } else - boxes.add(box); - } else { - mergeNativeTree(node); - } - } - } - } - - private void mergeStandardTree(Node root) throws IIOInvalidTreeException { - NodeList children = root.getChildNodes(); - int numComps = 0; - - for (int i = 0; i < children.getLength(); i++) { - Node node = children.item(i); - String name = node.getNodeName(); - if (name.equals("Chroma")) { - NodeList children1 = node.getChildNodes(); - for (int j = 0; j < children1.getLength(); j++) { - Node child = children1.item(j); - String name1 = child.getNodeName(); - - if (name1.equals("NumChannels")) { - String s = (String)Box.getAttribute(child, "value"); - numComps = new Integer(s).intValue(); - } - - if (name1.equals("ColorSpaceType")) - createColorSpecificationBoxFromStandardNode(child); - - if (name1.equals("Palette")) { - createPaletteBoxFromStandardNode(child); - } - } - } else if (name.equals("Compression")) { - // Intentionally do nothing: just prevent entry into - // the default "else" block and an ensuing - // IIOInvalidTreeException; fixes 5110389. - } else if (name.equals("Data")) { - createBitsPerComponentBoxFromStandardNode(node); - createHeaderBoxFromStandardNode(node, numComps); - } else if (name.equals("Dimension")) { - createResolutionBoxFromStandardNode(node); - } else if (name.equals("Document")) { - createXMLBoxFromStandardNode(node); - } else if (name.equals("Text")) { - createXMLBoxFromStandardNode(node); - } else if (name.equals("Transparency")) { - createChannelDefinitionFromStandardNode(node); - } else { - throw new IIOInvalidTreeException(I18N.getString("J2KMetadata3") - + " " + name, node); - } - } - } - - private void createColorSpecificationBoxFromStandardNode(Node node) { - if (node.getNodeName() != "ColorSpaceType") - throw new IllegalArgumentException(I18N.getString("J2KMetadata4")); - String name = (String)Box.getAttribute(node, "name"); - int ecs = name.equals("RGB") ? ColorSpecificationBox.ECS_sRGB : - (name.equals("Gray") ? ColorSpecificationBox.ECS_GRAY : 0); - - if (ecs == ColorSpecificationBox.ECS_sRGB || - ecs ==ColorSpecificationBox.ECS_GRAY) { - replace ("JPEG2000ColorSpecificationBox", - new ColorSpecificationBox((byte)1, (byte)0, (byte)0, - ecs, null)); - } - } - - private void createPaletteBoxFromStandardNode(Node node) { - if (node.getNodeName() != "Palette") - throw new IllegalArgumentException(I18N.getString("J2KMetadata5")); - NodeList children = node.getChildNodes(); - int maxIndex = -1; - boolean hasAlpha = false; - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - String name = child.getNodeName(); - - if (name.equals("PaletteEntry")) { - String s = (String)Box.getAttribute(child, "index"); - int index = new Integer(s).intValue(); - if(index > maxIndex) { - maxIndex = index; - } - if(Box.getAttribute(child, "alpha") != null) { - hasAlpha = true; - } - } - } - - // Determine palette size. - int numBits = 32; - int mask = 0x80000000; - while(mask != 0 && (maxIndex & mask) == 0) { - numBits--; - mask >>>= 1; - } - int size = 1 << numBits; - - byte[] red = new byte[size]; - byte[] green = new byte[size]; - byte[] blue = new byte[size]; - byte[] alpha = hasAlpha ? new byte[size]: null; - - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - String name = child.getNodeName(); - - if (name.equals("PaletteEntry")) { - String s = (String)Box.getAttribute(child, "index"); - int index = new Integer(s).intValue(); - s = (String)Box.getAttribute(child, "red"); - red[index] = (byte)(new Integer(s).intValue()); - s = (String)Box.getAttribute(child, "green"); - green[index] = (byte)(new Integer(s).intValue()); - s = (String)Box.getAttribute(child, "blue"); - blue[index] = (byte)(new Integer(s).intValue()); - - byte t = (byte)255; - s = (String)Box.getAttribute(child, "alpha"); - if(s != null) { - t = (byte)(new Integer(s).intValue()); - } - - if(alpha != null) { - alpha[index] = t; - } - } - } - - IndexColorModel icm; - if (alpha == null) - icm = new IndexColorModel(numBits, size, red, green, blue); - else - icm = new IndexColorModel(numBits, size, red, green, blue, alpha); - - replace("JPEG2000PaletteBox", new PaletteBox(icm)); - } - - private void createBitsPerComponentBoxFromStandardNode(Node node) { - if (node.getNodeName() != "Data") - throw new IllegalArgumentException(I18N.getString("J2KMetadata6")); - - NodeList children = node.getChildNodes(); - - byte[] bits = null; - boolean isSigned = false; - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - String name = child.getNodeName(); - - if (name.equals("BitsPerSample")) { - String s = (String)Box.getAttribute(child, "value"); - bits = (byte[])Box.parseByteArray(s).clone(); - } else if(name.equals("SampleFormat")) { - String s = (String)Box.getAttribute(child, "value"); - isSigned = s.equals("SignedIntegral"); - } - } - - if(bits != null) { - // JPEG 2000 "B" parameter represents "bitDepth - 1" in the - // right 7 least significant bits with the most significant - // bit indicating signed if set and unsigned if not. - for (int i = 0; i < bits.length; i++) { - bits[i] = (byte)((bits[i]&0xff) - 1); - if(isSigned) { - bits[i] |= 0x80; - } - } - - replace("JPEG2000BitsPerComponent", - new BitsPerComponentBox(bits)); - } - } - - private void createResolutionBoxFromStandardNode(Node node) { - if (node.getNodeName() != "Dimension") - throw new IllegalArgumentException(I18N.getString("J2KMetadata7")); - NodeList children = node.getChildNodes(); - float hRes = 0.0f; - float vRes = 0.0f; - - boolean gotH = false, gotV = false; - - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - String name = child.getNodeName(); - - if (name.equals("HorizontalPixelSize")) { - String s = (String)Box.getAttribute(child, "value"); - hRes = new Float(s).floatValue(); - hRes = 1000 / hRes; - gotH = true; - } - - if (name.equals("VerticalPixelSize")) { - String s = (String)Box.getAttribute(child, "value"); - vRes = new Float(s).floatValue(); - vRes = 1000 / vRes; - gotV = true; - } - } - - if(gotH && !gotV) { - vRes = hRes; - } else if(gotV && !gotH) { - hRes = vRes; - } - - if(gotH || gotV) { - replace("JPEG2000CaptureResolutionBox", - new ResolutionBox(0x72657363, hRes, vRes)); - } - } - - private void createXMLBoxFromStandardNode(Node node) { - NodeList children = node.getChildNodes(); - String value = "<" + node.getNodeName() + ">"; - - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - String name = child.getNodeName(); - value += "<" + name + " "; - - NamedNodeMap map = child.getAttributes(); - - for (int j = 0; j < map.getLength(); j++) { - Node att = map.item(j); - value += att.getNodeName() + "=\"" + - att.getNodeValue() + "\" "; - } - - value += " />"; - } - - value += ""; - - boxes.add(new XMLBox(value.getBytes())); - } - - private void createHeaderBoxFromStandardNode(Node node, int numComps) { - HeaderBox header = (HeaderBox)getElement("JPEG2000HeaderBox"); - byte unknownColor = - (byte)(getElement("JPEG2000ColorSpecificationBox") == null ? 1: 0); - if (header != null) { - if (numComps ==0); - numComps = header.getNumComponents(); - - header = new HeaderBox(header.getHeight(), header.getWidth(), - numComps, - header.getBitDepth(), - header.getCompressionType(), - unknownColor, - header.getIntellectualProperty()); - } else { - header = new HeaderBox(0, 0, numComps, 0, 0, unknownColor, 0); - } - replace("JPEG2000HeaderBox", header); - } - - private void createChannelDefinitionFromStandardNode(Node node) { - if (node.getNodeName() != "Transparency") - throw new IllegalArgumentException(I18N.getString("J2KMetadata8")); - - HeaderBox header = (HeaderBox)getElement("JPEG2000HeaderBox"); - int numComps = 3; - - if (header != null) { - numComps = header.getNumComponents(); - } - - NodeList children = node.getChildNodes(); - boolean hasAlpha = false; - boolean isPremultiplied = false; - - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - String name = child.getNodeName(); - - if (name.equals("Alpha")) { - String value = (String)Box.getAttribute(child, "value"); - if (value.equals("premultiplied")) - isPremultiplied = true; - if (value.equals("nonpremultiplied")) - hasAlpha = true; - } - } - - if (!hasAlpha) - return; - - int num = (short)(numComps * (isPremultiplied ? 3 : 2)); - short[] channels = new short[num]; - short[] types = new short[num]; - short[] associations = new short[num]; - ChannelDefinitionBox.fillBasedOnBands(numComps, isPremultiplied, - channels, types, associations); - replace("JPEG2000ChannelDefinitionBox", - new ChannelDefinitionBox(channels, types, associations)); - } - - private void replace(String name, Box box) { - for (int i = boxes.size() - 1; i >= 0; i--) { - Box box1 = (Box)boxes.get(i); - if (name.equals(Box.getName(box1.getType()))) { - boxes.set(i, box); - return; - } - } - - boxes.add(box); - } - - private boolean insertNodeIntoTree(IIOMetadataNode root, - IIOMetadataNode node) { - String name = node.getNodeName(); - String parent = format.getParent(name); - if (parent == null) - return false; - - IIOMetadataNode parentNode = getNodeFromTree(root, parent, name); - if (parentNode == null) - parentNode = createNodeIntoTree(root, parent); - parentNode.appendChild(node); - return true; - } - - private IIOMetadataNode getNodeFromTree(IIOMetadataNode root, - String name, - String childName) { - if (name.equals(root.getNodeName())) - return root; - - NodeList list = root.getChildNodes(); - for (int i = 0; i < list.getLength(); i++) { - IIOMetadataNode node = (IIOMetadataNode)list.item(i); - if (node.getNodeName().equals(name)) { - if (name.equals("JPEG2000UUIDInfoBox") && - checkUUIDInfoBox(node, childName)) - continue; - else - return node; - } - node = getNodeFromTree(node, name, childName); - if (node != null) - return node; - } - - return null; - } - - private IIOMetadataNode createNodeIntoTree(IIOMetadataNode root, - String name) { - IIOMetadataNode node = getNodeFromTree(root, name, null); - if (node != null) - return node; - - node = new IIOMetadataNode(name); - - String parent = format.getParent(name); - IIOMetadataNode parentNode = createNodeIntoTree(root, parent); - parentNode.appendChild(node); - - return node; - } - - private boolean isOriginalSigned(SampleModel sampleModel) { - int type = sampleModel.getDataType(); - if (type == DataBuffer.TYPE_BYTE || type == DataBuffer.TYPE_USHORT) - return false; - return true; - } - - /** Check whether the child with a name childName exists. - * This method is designed because UUID info box may have many instances. - * So if one of its sub-box is inserted into the tree, an empty slut for - * this sub-box has to be find or created to avoid one UUID info box - * has duplicated sub-boxes. The users have to guarantee each UUID info - * box has all the sub-boxes. - */ - private boolean checkUUIDInfoBox(Node node, String childName) { - - NodeList list = node.getChildNodes(); - for (int i = 0; i < list.getLength(); i++) { - IIOMetadataNode child = (IIOMetadataNode)list.item(i); - String name = child.getNodeName(); - - if (name.equals(childName)) - return true; - } - - return false; - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KReadState.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KReadState.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KReadState.java 2006-10-03 19:40:14.000000000 -0400 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KReadState.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,1042 +0,0 @@ -/* - * $RCSfile: J2KReadState.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.8 $ - * $Date: 2006/10/03 23:40:14 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import javax.imageio.IIOException; -import javax.imageio.ImageReader; -import javax.imageio.ImageReadParam; -import javax.imageio.ImageTypeSpecifier; -import javax.imageio.metadata.IIOMetadata; -import javax.imageio.spi.ImageReaderSpi; -import javax.imageio.stream.ImageInputStream; - -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.Transparency; -import java.awt.color.ColorSpace; -import java.awt.image.BufferedImage; -import java.awt.image.DataBuffer; -import java.awt.image.DataBufferByte; -import java.awt.image.ColorModel; -import java.awt.image.ComponentColorModel; -import java.awt.image.ComponentSampleModel; -import java.awt.image.DirectColorModel; -import java.awt.image.IndexColorModel; -import java.awt.image.MultiPixelPackedSampleModel; -import java.awt.image.PixelInterleavedSampleModel; -import java.awt.image.Raster; -import java.awt.image.RenderedImage; -import java.awt.image.SampleModel; -import java.awt.image.SinglePixelPackedSampleModel; -import java.awt.image.WritableRaster; - -import java.io.*; -import java.util.ArrayList; -import java.util.List; -import java.util.Hashtable; -import java.util.Iterator; - -import jj2000.j2k.quantization.dequantizer.*; -import jj2000.j2k.wavelet.synthesis.*; -import jj2000.j2k.image.invcomptransf.*; -import jj2000.j2k.fileformat.reader.*; -import jj2000.j2k.codestream.reader.*; -import jj2000.j2k.entropy.decoder.*; -import jj2000.j2k.codestream.*; -import jj2000.j2k.decoder.*; -import jj2000.j2k.image.*; -import jj2000.j2k.util.*; -import jj2000.j2k.roi.*; -import jj2000.j2k.io.*; -import jj2000.j2k.*; - -import com.sun.media.imageioimpl.common.ImageUtil; - -public class J2KReadState { - /** The input stream we read from */ - private ImageInputStream iis = null; - - private FileFormatReader ff; - private HeaderInfo hi; - private HeaderDecoder hd; - private RandomAccessIO in; - private BitstreamReaderAgent breader; - private EntropyDecoder entdec; - private ROIDeScaler roids; - private Dequantizer deq; - private InverseWT invWT; - private InvCompTransf ictransf; - private ImgDataConverter converter,converter2; - private DecoderSpecs decSpec = null; - private J2KImageReadParamJava j2krparam = null; - private int[] destinationBands = null; - private int[] sourceBands = null; - - private int[] levelShift = null; // level shift for each component - private int[] minValues = null; // The min values - private int[] maxValues = null; // The max values - private int[] fracBits = null; // fractional bits for each component - private DataBlkInt[] dataBlocks = null; // data-blocks to request data from src - - private int[] bandOffsets = null; - private int maxDepth = 0; - private boolean isSigned = false; - - private ColorModel colorModel = null; - private SampleModel sampleModel = null; - private int nComp = 0; - private int tileWidth = 0; - private int tileHeight = 0; - - /** Source to destination transform */ - private int scaleX, scaleY, xOffset, yOffset; - private Rectangle destinationRegion = null; - private Point sourceOrigin; - - /** Tile grid offsets of the source, also used for destination. */ - private int tileXOffset, tileYOffset; - - private int width; - private int height; - private int[] pixbuf = null; - private byte[] bytebuf = null; - private int[] channelMap = null; - - private boolean noTransform = true; - - /** The resolution level requested. */ - private int resolution; - - /** The subsampling step sizes. */ - private int stepX, stepY; - - /** Tile step sizes. */ - private int tileStepX, tileStepY; - - private J2KMetadata metadata; - - private BufferedImage destImage; - - /** Cache the J2KImageReader which creates this object. This - * variable is used to monitor the abortion. - */ - private J2KImageReader reader; - - /** Constructs J2KReadState. - * @param iis The input stream. - * @param param The reading parameters. - * @param metadata The J2KMetadata to cache the metadata read - * from the input stream. - * @param reader The J2KImageReader which holds this state. - * It is necessary for processing abortion. - * @throw IllegalArgumentException If the provided iis, - * param or metadata is null. - */ - public J2KReadState(ImageInputStream iis, - J2KImageReadParamJava param, - J2KMetadata metadata, - J2KImageReader reader) { - if (iis == null || param == null || metadata == null) - throw new IllegalArgumentException(I18N.getString("J2KReadState0")); - - this.iis = iis; - this.j2krparam = param; - this.metadata = metadata; - this.reader = reader; - - initializeRead(0, param, metadata); - } - - /** Constructs J2KReadState. - * @param iis The input stream. - * @param param The reading parameters. - * @param reader The J2KImageReader which holds this state. - * It is necessary for processing abortion. - * @throw IllegalArgumentException If the provided iis, - * or param is null. - */ - public J2KReadState(ImageInputStream iis, - J2KImageReadParamJava param, - J2KImageReader reader) { - if (iis == null || param == null) - throw new IllegalArgumentException(I18N.getString("J2KReadState0")); - - this.iis = iis; - this.j2krparam = param; - this.reader = reader; - initializeRead(0, param, null); - } - - public int getWidth() throws IOException { - return width; - } - - public int getHeight() throws IOException { - return height; - } - - public HeaderDecoder getHeader() { - return hd; - } - - public Raster getTile(int tileX, int tileY, - WritableRaster raster) throws IOException { - Point nT = ictransf.getNumTiles(null); - - if (noTransform) { - if (tileX >= nT.x || tileY >= nT.y) - throw new IllegalArgumentException(I18N.getString("J2KImageReader0")); - - ictransf.setTile(tileX*tileStepX, tileY*tileStepY); - - // The offset of the active tiles is the same for all components, - // since we don't support different component dimensions. - int tOffx; - int tOffy; - int cTileWidth; - int cTileHeight; - if(raster != null && - (this.resolution < hd.getDecoderSpecs().dls.getMin()) || - stepX != 1 || stepY != 1) { - tOffx = raster.getMinX(); - tOffy = raster.getMinY(); - cTileWidth = Math.min(raster.getWidth(), - ictransf.getTileWidth()); - cTileHeight = Math.min(raster.getHeight(), - ictransf.getTileHeight()); - } else { - tOffx = ictransf.getCompULX(0) - - (ictransf.getImgULX() + ictransf.getCompSubsX(0) - 1) / - ictransf.getCompSubsX(0) + destinationRegion.x; - tOffy = ictransf.getCompULY(0)- - (ictransf.getImgULY() + ictransf.getCompSubsY(0) - 1) / - ictransf.getCompSubsY(0) + destinationRegion.y; - cTileWidth = ictransf.getTileWidth(); - cTileHeight = ictransf.getTileHeight(); - } - - if (raster == null) - raster = Raster.createWritableRaster(sampleModel, - new Point(tOffx, tOffy)); - - int numBands = sampleModel.getNumBands(); - - if (tOffx + cTileWidth >= - destinationRegion.width + destinationRegion.x) - cTileWidth = - destinationRegion.width + destinationRegion.x - tOffx; - - if (tOffy + cTileHeight >= - destinationRegion.height + destinationRegion.y) - cTileHeight = - destinationRegion.height + destinationRegion.y - tOffy; - - //create the line buffer for pixel data if it is not large enough - // or null - if (pixbuf == null || pixbuf.length < cTileWidth * numBands) - pixbuf = new int[cTileWidth * numBands]; - boolean prog = false; - - // Deliver in lines to reduce memory usage - for (int l=0; l < cTileHeight;l++) { - if (reader.getAbortRequest()) - break; - - // Request line data - for (int i = 0; i < numBands; i++) { - if (reader.getAbortRequest()) - break; - DataBlkInt db = dataBlocks[i]; - db.ulx = 0; - db.uly = l; - db.w = cTileWidth; - db.h = 1; - ictransf.getInternCompData(db, channelMap[sourceBands[i]]); - prog = prog || db.progressive; - - int[] data = db.data; - int k1 = db.offset + cTileWidth - 1; - - int fracBit = fracBits[i]; - int lS = levelShift[i]; - int min = minValues[i]; - int max = maxValues[i]; - - if (ImageUtil.isBinary(sampleModel)) { - // Force min max to 0 and 1. - min = 0; - max = 1; - if (bytebuf == null || bytebuf.length < cTileWidth * numBands) - bytebuf = new byte[cTileWidth * numBands]; - for (int j = cTileWidth - 1; - j >= 0; j--) { - int tmp = (data[k1--] >> fracBit) + lS; - bytebuf[j] = - (byte)((tmp < min) ? min : - ((tmp > max) ? max : tmp)); - } - - ImageUtil.setUnpackedBinaryData(bytebuf, - raster, - new Rectangle(tOffx, - tOffy + l, - cTileWidth, - 1)); - } else { - - for (int j = cTileWidth - 1; - j >= 0; j--) { - int tmp = (data[k1--] >> fracBit) + lS; - pixbuf[j] = (tmp < min) ? min : - ((tmp > max) ? max : tmp); - } - - raster.setSamples(tOffx, - tOffy + l, - cTileWidth, - 1, - destinationBands[i], - pixbuf); - } - } - } - } else { - readSubsampledRaster(raster); - } - - return raster; - } - - public Rectangle getDestinationRegion() { - return destinationRegion; - } - - public BufferedImage readBufferedImage() throws IOException { - colorModel = getColorModel(); - sampleModel = getSampleModel(); - WritableRaster raster = null; - BufferedImage image = j2krparam.getDestination(); - - int x = destinationRegion.x; - int y = destinationRegion.y; - destinationRegion.setLocation(j2krparam.getDestinationOffset()); - if (image == null) { - // If the destination type is specified, use the color model of it. - ImageTypeSpecifier type = j2krparam.getDestinationType(); - if (type != null) - colorModel = type.getColorModel(); - - raster = Raster.createWritableRaster( - sampleModel.createCompatibleSampleModel(destinationRegion.x + - destinationRegion.width, - destinationRegion.y + - destinationRegion.height), - new Point(0, 0)); - image = new BufferedImage(colorModel, raster, - colorModel.isAlphaPremultiplied(), - new Hashtable()); - } else - raster = image.getWritableTile(0, 0); - - destImage = image; - readSubsampledRaster(raster); - destinationRegion.setLocation(x, y); - destImage = null; - return image; - } - - public Raster readAsRaster() throws IOException { - BufferedImage image = j2krparam.getDestination(); - WritableRaster raster = null; - - if (image == null) { - raster = Raster.createWritableRaster( - sampleModel.createCompatibleSampleModel(destinationRegion.x + - destinationRegion.width, - destinationRegion.y + - destinationRegion.height), - new Point(0, 0)); - } else - raster = image.getWritableTile(0, 0); - - readSubsampledRaster(raster); - return raster; - } - - private void initializeRead(int imageIndex, J2KImageReadParamJava param, - J2KMetadata metadata) { - try { - iis.mark(); - in = new IISRandomAccessIO(iis); - - // **** File Format **** - // If the codestream is wrapped in the jp2 fileformat, Read the - // file format wrapper - ff = new FileFormatReader(in, metadata); - ff.readFileFormat(); - in.seek(ff.getFirstCodeStreamPos()); - - hi = new HeaderInfo(); - try{ - hd = new HeaderDecoder(in, j2krparam, hi); - } catch(EOFException e){ - throw new RuntimeException(I18N.getString("J2KReadState2")); - } catch (IOException ioe) { - throw new RuntimeException(ioe); - } - - this.width = hd.getImgWidth(); - this.height = hd.getImgHeight(); - - Rectangle sourceRegion = param.getSourceRegion(); - sourceOrigin = new Point(); - sourceRegion = - new Rectangle(hd.getImgULX(), hd.getImgULY(), - this.width, this.height); - - // if the subsample rate for components are not consistent - boolean compConsistent = true; - stepX = hd.getCompSubsX(0); - stepY = hd.getCompSubsY(0); - for (int i = 1; i < nComp; i++) { - if (stepX != hd.getCompSubsX(i) || stepY != hd.getCompSubsY(i)) - throw new RuntimeException(I18N.getString("J2KReadState12")); - } - - // Get minimum number of resolution levels available across - // all tile-components. - int minResLevels = hd.getDecoderSpecs().dls.getMin(); - - // Set current resolution level. - this.resolution = param != null ? - param.getResolution() : minResLevels; - if(resolution < 0 || resolution > minResLevels) { - resolution = minResLevels; - } - - // Convert source region to lower resolution level. - if(resolution != minResLevels || stepX != 1 || stepY != 1) { - sourceRegion = - J2KImageReader.getReducedRect(sourceRegion, minResLevels, - resolution, stepX, stepY); - } - - destinationRegion = (Rectangle)sourceRegion.clone(); - - J2KImageReader.computeRegionsWrapper(param, - false, - this.width, - this.height, - param.getDestination(), - sourceRegion, - destinationRegion); - - sourceOrigin = new Point(sourceRegion.x, sourceRegion.y); - scaleX = param.getSourceXSubsampling(); - scaleY = param.getSourceYSubsampling(); - xOffset = param.getSubsamplingXOffset(); - yOffset = param.getSubsamplingYOffset(); - - this.width = destinationRegion.width; - this.height = destinationRegion.height; - - Point tileOffset = hd.getTilingOrigin(null); - - this.tileWidth = hd.getNomTileWidth(); - this.tileHeight = hd.getNomTileHeight(); - - // Convert tile 0 to lower resolution level. - if(resolution != minResLevels || stepX != 1 || stepY != 1) { - Rectangle tileRect = new Rectangle(tileOffset); - tileRect.width = tileWidth; - tileRect.height = tileHeight; - tileRect = - J2KImageReader.getReducedRect(tileRect, minResLevels, - resolution, stepX, stepY); - tileOffset = tileRect.getLocation(); - tileWidth = tileRect.width; - tileHeight = tileRect.height; - } - - tileXOffset = tileOffset.x; - tileYOffset = tileOffset.y; - - - // Set the tile step sizes. These values are used because it - // is possible that tiles will be empty. In particular at lower - // resolution levels when subsampling is used this may be the - // case. This method of calculation will work at least for - // Profile-0 images. - if(tileWidth*(1 << (minResLevels - resolution))*stepX > - hd.getNomTileWidth()) { - tileStepX = - (tileWidth*(1 << (minResLevels - resolution))*stepX + - hd.getNomTileWidth() - 1)/hd.getNomTileWidth(); - } else { - tileStepX = 1; - } - - if(tileHeight*(1 << (minResLevels - resolution))*stepY > - hd.getNomTileHeight()) { - tileStepY = - (tileHeight*(1 << (minResLevels - resolution))*stepY + - hd.getNomTileHeight() - 1)/hd.getNomTileHeight(); - } else { - tileStepY = 1; - } - - if (!destinationRegion.equals(sourceRegion)) - noTransform = false; - - // **** Header decoder **** - // Instantiate header decoder and read main header - decSpec = hd.getDecoderSpecs(); - - // **** Instantiate decoding chain **** - // Get demixed bitdepths - nComp = hd.getNumComps(); - - int[] depth = new int[nComp]; - for (int i=0; i maxDepth) - maxDepth = depth[i]; - dataBlocks[i] = new DataBlkInt(); - - //XXX: may need to change if ChannelDefinition is used to - // define the color channels, such as BGR order - bandOffsets[i] = i; - if (hd.isOriginalSigned(sourceBands[i])) - isSigned = true; - else { - levelShift[i] = - 1<<(ictransf.getNomRangeBits(sourceBands[i])-1); - } - - // Get the number of bits in the image, and decide what the max - // value should be, depending on whether it is signed or not - int nomRangeBits = ictransf.getNomRangeBits(sourceBands[i]); - maxValues[i] = (1 << (isSigned == true ? (nomRangeBits-1) : - nomRangeBits)) - 1; - minValues[i] = isSigned ? -(maxValues[i]+1) : 0; - - fracBits[i] = ictransf.getFixedPoint(sourceBands[i]); - } - - iis.reset(); - } catch (IllegalArgumentException e){ - throw new RuntimeException(e.getMessage(), e); - } catch (Error e) { - if(e.getMessage()!=null) - throw new RuntimeException(e.getMessage(), e); - else { - throw new RuntimeException(I18N.getString("J2KReadState9"), e); - } - } catch (RuntimeException e) { - if(e.getMessage()!=null) - throw new RuntimeException(I18N.getString("J2KReadState10") + " " + - e.getMessage(), e); - else { - throw new RuntimeException(I18N.getString("J2KReadState10"), e); - } - } catch (Throwable e) { - throw new RuntimeException(I18N.getString("J2KReadState10"), e); - } - } - - private Raster readSubsampledRaster(WritableRaster raster) throws IOException { - if (raster == null) - raster = Raster.createWritableRaster( - sampleModel.createCompatibleSampleModel(destinationRegion.x + - destinationRegion.width, - destinationRegion.y + - destinationRegion.height), - new Point(destinationRegion.x, destinationRegion.y)); - - int pixbuf[] = null; // line buffer for pixel data - boolean prog = false; // Flag for progressive data - Point nT = ictransf.getNumTiles(null); - int numBands = sourceBands.length; - - Rectangle destRect = raster.getBounds().intersection(destinationRegion); - - int offx = destinationRegion.x; - int offy = destinationRegion.y; - - int sourceSX = (destRect.x - offx) * scaleX + sourceOrigin.x; - int sourceSY = (destRect.y - offy) * scaleY + sourceOrigin.y; - int sourceEX = (destRect.width - 1)* scaleX + sourceSX; - int sourceEY = (destRect.height - 1) * scaleY + sourceSY; - - int startXTile = (sourceSX - tileXOffset) / tileWidth; - int startYTile = (sourceSY - tileYOffset) / tileHeight; - int endXTile = (sourceEX - tileXOffset) / tileWidth; - int endYTile = (sourceEY - tileYOffset) / tileHeight; - - startXTile = clip(startXTile, 0, nT.x - 1); - startYTile = clip(startYTile, 0, nT.y - 1); - endXTile = clip(endXTile, 0, nT.x - 1); - endYTile = clip(endYTile, 0, nT.y - 1); - - int totalXTiles = endXTile - startXTile + 1; - int totalYTiles = endYTile - startYTile + 1; - int totalTiles = totalXTiles * totalYTiles; - - // Start the data delivery to the cached consumers tile by tile - for(int y=startYTile; y <= endYTile; y++){ - if (reader.getAbortRequest()) - break; - - // Loop on horizontal tiles - for(int x=startXTile; x <= endXTile; x++){ - if (reader.getAbortRequest()) - break; - - float initialFraction = - (x - startXTile + (y - startYTile)*totalXTiles)/totalTiles; - - ictransf.setTile(x*tileStepX,y*tileStepY); - - int sx = hd.getCompSubsX(0); - int cTileWidth = (ictransf.getTileWidth() + sx - 1)/sx; - int sy = hd.getCompSubsY(0); - int cTileHeight = (ictransf.getTileHeight() + sy - 1)/sy; - - // Offsets within the tile. - int tx = 0; - int ty = 0; - - // The region for this tile - int startX = tileXOffset + x * tileWidth; - int startY = tileYOffset + y * tileHeight; - - // sourceSX is guaranteed to be >= startX - if (sourceSX > startX) { - if(startX >= hd.getImgULX()) { - tx = sourceSX - startX; // Intra-tile offset. - cTileWidth -= tx; // Reduce effective width. - } - startX = sourceSX; // Absolute position. - } - - // sourceSY is guaranteed to be >= startY - if (sourceSY > startY) { - if(startY >= hd.getImgULY()) { - ty = sourceSY - startY; // Intra-tile offset. - cTileHeight -= ty; // Reduce effective width. - } - startY = sourceSY; // Absolute position. - } - - // Decrement dimensions if end position is within tile. - if (sourceEX < startX + cTileWidth - 1) { - cTileWidth += sourceEX - startX - cTileWidth + 1; - } - if (sourceEY < startY + cTileHeight - 1) { - cTileHeight += sourceEY - startY - cTileHeight + 1; - } - - // The start X in the destination - int x1 = (startX + scaleX - 1 - sourceOrigin.x) / scaleX; - int x2 = (startX + scaleX -1 + cTileWidth - sourceOrigin.x) / - scaleX; - int lineLength = x2 - x1; - if (pixbuf == null || pixbuf.length < lineLength) - pixbuf = new int[lineLength]; // line buffer for pixel data - x2 = (x2 - 1) * scaleX + sourceOrigin.x - startX; - - int y1 = (startY + scaleY -1 - sourceOrigin.y) /scaleY; - - x1 += offx; - y1 += offy; - - // Deliver in lines to reduce memory usage - for (int l = ty, m = y1; - l < ty + cTileHeight; - l += scaleY, m++) { - if (reader.getAbortRequest()) - break; - // Request line data - for (int i = 0; i < numBands; i++) { - DataBlkInt db = dataBlocks[i]; - db.ulx = tx; - db.uly = l; - db.w = cTileWidth; - db.h = 1; - ictransf.getInternCompData(db, channelMap[sourceBands[i]]); - prog = prog || db.progressive; - - int[] data = db.data; - int k1 = db.offset + x2; - - int fracBit = fracBits[i]; - int lS = levelShift[i]; - int min = minValues[i]; - int max = maxValues[i]; - - if (ImageUtil.isBinary(sampleModel)) { - // Force min max to 0 and 1. - min = 0; - max = 1; - if (bytebuf == null || bytebuf.length < cTileWidth * numBands) - bytebuf = new byte[cTileWidth * numBands]; - for (int j = lineLength - 1; j >= 0; j--, k1-=scaleX) { - int tmp = (data[k1] >> fracBit) + lS; - bytebuf[j] = - (byte)((tmp < min) ? min : - ((tmp > max) ? max : tmp)); - } - - ImageUtil.setUnpackedBinaryData(bytebuf, - raster, - new Rectangle(x1, - m, - lineLength, - 1)); - } else { - for (int j = lineLength - 1; j >= 0; j--, k1-=scaleX) { - int tmp = (data[k1] >> fracBit) + lS; - pixbuf[j] = (tmp < min) ? min : - ((tmp > max) ? max : tmp); - } - - // Send the line data to the BufferedImage - raster.setSamples(x1, - m, - lineLength, - 1, - destinationBands[i], - pixbuf); - } - } - - if (destImage != null) - reader.processImageUpdateWrapper(destImage, x1, m, - cTileWidth, 1, 1, 1, - destinationBands); - - float fraction = initialFraction + - (l - ty + 1.0F)/cTileHeight/totalTiles; - reader.processImageProgressWrapper(100.0f*fraction); - } - } // End loop on horizontal tiles - } // End loop on vertical tiles - - return raster; - } - - public ImageTypeSpecifier getImageType() - throws IOException { - - getSampleModel(); - getColorModel(); - - return new ImageTypeSpecifier(colorModel, sampleModel); - } - - public SampleModel getSampleModel() { - if (sampleModel != null) - return sampleModel; - - if (nComp == 1 && (maxDepth == 1 || maxDepth == 2 || maxDepth == 4)) - sampleModel = - new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, - tileWidth, - tileHeight, - maxDepth); - else if (maxDepth <= 8) - sampleModel = - new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, - tileWidth, - tileHeight, - nComp, - tileWidth * nComp, - bandOffsets); - else if (maxDepth <=16) - sampleModel = - new PixelInterleavedSampleModel(isSigned ? - DataBuffer.TYPE_SHORT : - DataBuffer.TYPE_USHORT, - tileWidth, tileHeight, - nComp, - tileWidth * nComp, - bandOffsets); - else if (maxDepth <= 32) - sampleModel = - new PixelInterleavedSampleModel(DataBuffer.TYPE_INT, - tileWidth, - tileHeight, - nComp, - tileWidth * nComp, - bandOffsets); - else - throw new IllegalArgumentException(I18N.getString("J2KReadState11") + " " + - + maxDepth); - return sampleModel; - } - - public ColorModel getColorModel() { - - if (colorModel != null) - return colorModel; - - // Attempt to get the ColorModel from the JP2 boxes. - colorModel = ff.getColorModel(); - if (colorModel != null) - return colorModel; - - if(hi.siz.csiz <= 4) { - // XXX: Code essentially duplicated from FileFormatReader.getColorModel(). - // Create the ColorModel from the SIZ marker segment parameters. - ColorSpace cs; - if(hi.siz.csiz > 2) { - cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); - } else { - cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); - } - - int[] bitsPerComponent = new int[hi.siz.csiz]; - boolean isSigned = false; - int maxBitDepth = -1; - for(int i = 0; i < hi.siz.csiz; i++) { - bitsPerComponent[i] = hi.siz.getOrigBitDepth(i); - if(maxBitDepth < bitsPerComponent[i]) { - maxBitDepth = bitsPerComponent[i]; - } - isSigned |= hi.siz.isOrigSigned(i); - } - - boolean hasAlpha = hi.siz.csiz % 2 == 0; - - int type = -1; - - if (maxBitDepth <= 8) { - type = DataBuffer.TYPE_BYTE; - } else if (maxBitDepth <= 16) { - type = isSigned ? DataBuffer.TYPE_SHORT : DataBuffer.TYPE_USHORT; - } else if (maxBitDepth <= 32) { - type = DataBuffer.TYPE_INT; - } - - if (type != -1) { - if(hi.siz.csiz == 1 && - (maxBitDepth == 1 || maxBitDepth == 2 || maxBitDepth == 4)) { - colorModel = ImageUtil.createColorModel(getSampleModel()); - } else { - colorModel = new ComponentColorModel(cs, - bitsPerComponent, - hasAlpha, - false, - hasAlpha ? - Transparency.TRANSLUCENT : - Transparency.OPAQUE , - type); - } - - return colorModel; - } - } - - if(sampleModel == null) { - sampleModel = getSampleModel(); - } - - if (sampleModel == null) - return null; - - return ImageUtil.createColorModel(null, sampleModel); - } - - /** - * Returns the bounding rectangle of the upper left tile at - * the current resolution level. - */ - Rectangle getTile0Rect() { - return new Rectangle(tileXOffset, tileYOffset, tileWidth, tileHeight); - } - - private int clip(int value, int min, int max) { - if (value < min) - value = min; - if (value > max) - value = max; - return value; - } - - private void clipDestination(Rectangle dest) { - Point offset = j2krparam.getDestinationOffset(); - if (dest.x < offset.x) { - dest.width += dest.x - offset.x; - dest.x = offset.x ; - } - if (dest.y < offset.y) { - dest.height += dest.y - offset.y; - dest.y = offset.y ; - } - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KRenderedImageCodecLib.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KRenderedImageCodecLib.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KRenderedImageCodecLib.java 2006-10-03 19:40:14.000000000 -0400 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KRenderedImageCodecLib.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,1020 +0,0 @@ -/* - * $RCSfile: J2KRenderedImageCodecLib.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.4 $ - * $Date: 2006/10/03 23:40:14 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import javax.imageio.IIOException; -import javax.imageio.ImageReadParam; -import javax.imageio.stream.ImageInputStream; - -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.Transparency; -import java.awt.color.ColorSpace; -import java.awt.color.ICC_ColorSpace; -import java.awt.color.ICC_Profile; -import java.awt.image.BufferedImage; -import java.awt.image.ColorModel; -import java.awt.image.ComponentColorModel; -import java.awt.image.ComponentSampleModel; -import java.awt.image.DataBuffer; -import java.awt.image.DirectColorModel; -import java.awt.image.IndexColorModel; -import java.awt.image.MultiPixelPackedSampleModel; -import java.awt.image.PixelInterleavedSampleModel; -import java.awt.image.SinglePixelPackedSampleModel; -import java.awt.image.Raster; -import java.awt.image.RenderedImage; -import java.awt.image.SampleModel; -import java.awt.image.WritableRaster; - -import java.io.IOException; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.lang.reflect.InvocationTargetException; - -import com.sun.medialib.codec.jp2k.CompParams; -import com.sun.medialib.codec.jp2k.Constants; -import com.sun.medialib.codec.jp2k.Decoder; -import com.sun.medialib.codec.jp2k.Size; -import com.sun.medialib.codec.jiio.mediaLibImage; - -import com.sun.media.imageio.plugins.jpeg2000.J2KImageReadParam; -import com.sun.media.imageioimpl.common.SimpleRenderedImage; -import com.sun.media.imageioimpl.common.ImageUtil; - -// XXX Overall documentation - -public class J2KRenderedImageCodecLib extends SimpleRenderedImage { - /** The sample model for the original image. */ - private SampleModel originalSampleModel; - - private Raster currentTile; - private Point currentTileGrid; - private J2KMetadata metadata; - - /** The input stream we read from */ - private ImageInputStream iis = null; - - /** Caches the J2KImageReader which creates this object. This - * variable is used to monitor the abortion. - */ - private J2KImageReaderCodecLib reader; - - /** The J2KImageReadParam to create this - * renderedImage. - */ - private J2KImageReadParam param = null; - - /** Caches the medialib decoder. */ - private Decoder decoder; - private Size size; - private CompParams compParam; - private int xStep, yStep; // JPEG 2000 internal subsampling parameters - - /** The destination bounds. */ - Rectangle destinationRegion; - Rectangle originalRegion; - Point sourceOrigin; - - /** The subsampling parameters. */ - private int scaleX, scaleY, xOffset, yOffset; - private int[] destinationBands = null; - private int[] sourceBands = null; - private int nComp; - private int[] channelMap; - - /** Coordinate transform is not needed from the source (image stream) - * to the destination. - */ - private boolean noTransform = true; - - /** The raster for medialib tiles to share. */ - private WritableRaster rasForATile; - - private BufferedImage destImage; - - public J2KRenderedImageCodecLib(ImageInputStream iis, - J2KImageReaderCodecLib reader, - ImageReadParam param) throws IOException { - this.iis = iis; - this.reader = reader; - - // Ensure the ImageReadParam is a J2KImageReadParam - boolean allowZeroDestOffset = true; - if(param == null) { - // Use the default - param = (J2KImageReadParam)reader.getDefaultReadParam(); - allowZeroDestOffset = false; - } else if(!(param instanceof J2KImageReadParam)) { - // Create a new one - param = new J2KImageReadParamJava(param); - allowZeroDestOffset = false; - } - this.param = (J2KImageReadParam)param; - - decoder = new Decoder(iis); - - decoder.setMode(Constants.JP2K_COMPOSITE_TILE); - - //set resolution before any calling of any calling for decode/decodeSize - int resolution = ((J2KImageReadParam)param).getResolution(); - if (resolution != -1) - decoder.setMaxLevels(resolution); - - size = decoder.decodeSize(null); - - compParam = new CompParams(); - for (int i = 0; i < size.csize; i++) { - decoder.decodeCompParams(compParam, i); - if(i == 0) { - xStep = compParam.xstep; - yStep = compParam.ystep; - } else if(compParam.xstep != xStep || compParam.ystep != yStep) { - // All components must have same subsampling along each axis. - throw new IIOException - ("All components must have the same subsampling factors!"); - } - } - - // Set source sub-banding. - sourceBands = param.getSourceBands(); - if (sourceBands == null) { - nComp = size.csize; - sourceBands = new int[nComp]; - for (int i = 0; i < nComp; i++) - sourceBands[i] = i; - } else { - for(int i = 0; i < sourceBands.length; i++) { - if(sourceBands[i] < 0 || - sourceBands[i] >= size.csize) { - throw new IIOException - ("Source band out of range!"); - } - } - } - - // Cache number of components. - nComp = sourceBands.length; - - // Set destination sub-banding. - destinationBands = param.getDestinationBands(); - if (destinationBands == null) { - destinationBands = new int[nComp]; - for (int i = 0; i < nComp; i++) - destinationBands[i] = i; - } else { - for(int i = 0; i < destinationBands.length; i++) { - if(destinationBands[i] < 0 || - destinationBands[i] >= size.csize) { - throw new IIOException - ("Destination band out of range!"); - } - } - } - - // Check number of source and dest bands. - if(destinationBands.length != sourceBands.length) { - throw new IIOException - ("Number of source and destination bands must be equal!"); - } - - this.width = (size.xosize + size.xsize + xStep - 1)/xStep; - this.height = (size.yosize + size.ysize + yStep - 1)/yStep; - - Rectangle sourceRegion = - new Rectangle(0, 0, this.width, this.height); - - originalRegion = (Rectangle)sourceRegion.clone(); - - destinationRegion = (Rectangle)sourceRegion.clone(); - - J2KImageReader.computeRegionsWrapper(param, - allowZeroDestOffset, - this.width, this.height, - param.getDestination(), - sourceRegion, - destinationRegion); - scaleX = param.getSourceXSubsampling(); - scaleY = param.getSourceYSubsampling(); - xOffset = param.getSubsamplingXOffset(); - yOffset = param.getSubsamplingYOffset(); - - sourceOrigin = new Point(sourceRegion.x, sourceRegion.y); - if (!destinationRegion.equals(originalRegion)) - noTransform = false; - - this.tileWidth = (size.xtsize + xStep - 1)/xStep; - this.tileHeight = (size.ytsize + yStep - 1)/yStep; - this.tileGridXOffset = - (size.xtosize + xStep - 1)/xStep - (size.xosize + xStep - 1)/xStep; - this.tileGridYOffset = - (size.ytosize + yStep - 1)/yStep - (size.yosize + yStep - 1)/yStep; - - this.width = destinationRegion.width; - this.height = destinationRegion.height; - this.minX = destinationRegion.x; - this.minY = destinationRegion.y; - - originalSampleModel = createOriginalSampleModel(); - sampleModel = createSampleModel(); - colorModel = createColorModel(); - tileGridXOffset += - (XToTileX(minX) - XToTileX(tileGridXOffset)) * tileWidth; - tileGridYOffset += - (YToTileY(minY) - YToTileY(tileGridYOffset)) * tileHeight; - - // sets the resolution and decoding rate to the medialib decoder - // Java decoding rate is in bit-per-pixel; the medialib rate is in - // percentage; so convert first. - double rate = ((J2KImageReadParam)param).getDecodingRate(); - if (rate != Double.MAX_VALUE) { - // XXX Obtain bits per sample from elsewhere, e.g., ColorModel. - rate /= ImageUtil.getElementSize(sampleModel); - decoder.setRate(rate, 0); - } - } - - public synchronized Raster getTile(int tileX, int tileY) { - if (currentTile != null && - currentTileGrid.x == tileX && - currentTileGrid.y == tileY) - return currentTile; - - if (tileX < getMinTileX() || tileY < getMinTileY() || - tileX > getMaxTileX() || tileY > getMaxTileY()) - throw new IllegalArgumentException(I18N.getString("J2KReadState1")); - - int x = tileXToX(tileX); - int y = tileYToY(tileY); - currentTile = Raster.createWritableRaster(sampleModel, - new Point(x, y)); - - try { - readAsRaster((WritableRaster)currentTile); - } catch(IOException ioe) { - throw new RuntimeException(ioe); - } - - if (currentTileGrid == null) - currentTileGrid = new Point(tileX, tileY); - else { - currentTileGrid.x = tileX; - currentTileGrid.y = tileY; - } - - return currentTile; - } - - synchronized WritableRaster readAsRaster(WritableRaster raster) - throws IOException { - int x = raster.getMinX(); - int y = raster.getMinY(); - - try { - if (noTransform) { - int E2c = (size.xosize + xStep - 1)/xStep; - int E1c = (size.yosize + yStep - 1)/yStep; - - int tXStart = - ((x + E2c)*xStep - size.xtosize)/size.xtsize; - int tXEnd = - ((x + raster.getWidth() - 1 + E2c)*xStep - size.xtosize)/ - size.xtsize; - int tYStart = - ((y + E2c)*yStep - size.ytosize)/size.ytsize; - int tYEnd = - ((y + raster.getHeight() - 1 + E2c)*yStep - size.ytosize)/ - size.ytsize; - - int sourceFormatTag = - MediaLibAccessor.findCompatibleTag(raster); - - if(tXStart == tXEnd && tYStart == tYEnd) { - MediaLibAccessor accessor = - new MediaLibAccessor(raster, - raster.getBounds().intersection(originalRegion), - sourceFormatTag, true); - - mediaLibImage[] mlImage = accessor.getMediaLibImages(); - - //this image may be a subregion of the image in the stream - // So use the original tile number. - int tileNo = tXStart + tYStart*size.nxtiles; - decoder.decode(mlImage, tileNo); - accessor.copyDataToRaster(channelMap); - } else { - for(int ty = tYStart; ty <= tYEnd; ty++) { - for(int tx = tXStart; tx <= tXEnd; tx++) { - int sx = (size.xtosize + tx*size.xtsize + - xStep - 1)/xStep - E2c; - int sy = (size.ytosize + ty*size.ytsize + - yStep - 1)/yStep - E1c; - int ex = (size.xtosize + (tx + 1)*size.xtsize + - xStep - 1)/xStep - E2c; - int ey = (size.ytosize + (ty + 1)*size.ytsize + - yStep - 1)/yStep - E1c; - Rectangle subRect = - new Rectangle(sx, sy, ex - sx, ey - sy); - if(subRect.isEmpty()) { - continue; - } - if (rasForATile == null) { - rasForATile = - Raster.createWritableRaster - (originalSampleModel, null); - } - WritableRaster subRaster = - rasForATile.createWritableChild - (rasForATile.getMinX(), - rasForATile.getMinY(), - subRect.width, subRect.height, - subRect.x, subRect.y, null); - MediaLibAccessor accessor = - new MediaLibAccessor(subRaster, - subRect, - sourceFormatTag, true); - - mediaLibImage[] mlImage = - accessor.getMediaLibImages(); - - int tileNo = tx + ty*size.nxtiles; - decoder.decode(mlImage, tileNo); - accessor.copyDataToRaster(channelMap); - - Rectangle rasBounds = raster.getBounds(); - Rectangle childRect = - rasBounds.intersection(subRect); - if(childRect.isEmpty()) { - continue; - } - - Raster childRaster = - subRaster.createChild(childRect.x, childRect.y, - childRect.width, - childRect.height, - childRect.x, childRect.y, - null); - ((WritableRaster)raster).setRect(childRaster); - } - } - } - } else { - readSubsampledRaster(raster); - } - } catch (IOException e) { - throw new RuntimeException(e); - } - - return raster; - } - - private void readSubsampledRaster(WritableRaster raster) - throws IOException { - - int numBands = sourceBands.length; - - Rectangle destRect = raster.getBounds().intersection(destinationRegion); - - int offx = destinationRegion.x; - int offy = destinationRegion.y; - - int sourceSX = (destRect.x - offx) * scaleX + sourceOrigin.x; - int sourceSY = (destRect.y - offy) * scaleY + sourceOrigin.y; - int sourceEX = (destRect.width - 1) * scaleX + sourceSX; - int sourceEY = (destRect.height - 1)* scaleY + sourceSY; - - int E2c = (size.xosize + xStep - 1)/xStep; - int E1c = (size.yosize + yStep - 1)/yStep; - - int startXTile = - ((sourceSX + E2c)*xStep - size.xtosize)/size.xtsize; - int endXTile = - ((sourceEX + E2c)*xStep - size.xtosize)/size.xtsize; - int startYTile = - ((sourceSY + E1c)*yStep - size.ytosize)/size.ytsize; - int endYTile = - ((sourceEY + E1c)*yStep - size.ytosize)/size.ytsize; - - startXTile = clip(startXTile, 0, size.nxtiles - 1); - startYTile = clip(startYTile, 0, size.nytiles - 1); - endXTile = clip(endXTile, 0, size.nxtiles - 1); - endYTile = clip(endYTile, 0, size.nytiles - 1); - - int totalXTiles = endXTile - startXTile + 1; - int totalYTiles = endYTile - startYTile + 1; - int totalTiles = totalXTiles * totalYTiles; - - int[] pixbuf = null; // integer buffer for the decoded pixels. - - // Start the data delivery to the cached consumers tile by tile - for(int y=startYTile; y <= endYTile; y++){ - if (reader.getAbortRequest()) - break; - - // Loop on horizontal tiles - for(int x=startXTile; x <= endXTile; x++){ - if (reader.getAbortRequest()) - break; - - float percentage = // XXX Incorrect? - (x - startXTile + 1.0F + y * totalXTiles) / totalTiles; - - int startX = - (x * size.xtsize + size.xtosize + xStep - 1)/xStep - E2c; - int startY = - (y * size.ytsize + size.ytosize + yStep - 1)/yStep - E1c; - int endX = - ((x + 1)*size.xtsize + size.xtosize + xStep - 1)/ - xStep - E2c; - int endY = - ((y + 1)*size.ytsize + size.ytosize + yStep - 1)/ - yStep - E1c; - - if (rasForATile == null) { - rasForATile = - Raster.createWritableRaster(originalSampleModel, - new Point(startX, startY)); - } else { - rasForATile = - rasForATile.createWritableTranslatedChild(startX, startY); - } - - int tw = endX - startX; - int th = endY - startY; - WritableRaster targetRas; - if(tw != tileWidth || th != tileHeight) { - targetRas = rasForATile.createWritableChild - (startX, startY, tw, th, startX, startY, null); - } else { - targetRas = rasForATile; - } - - int sourceFormatTag = - MediaLibAccessor.findCompatibleTag(targetRas); - - MediaLibAccessor accessor = - new MediaLibAccessor(targetRas, -// targetRas.getBounds(), - targetRas.getBounds().intersection(originalRegion), - sourceFormatTag, true); - - mediaLibImage[] mlImage = accessor.getMediaLibImages(); - decoder.decode(mlImage, x + y * size.nxtiles); - accessor.copyDataToRaster(channelMap); - - int cTileHeight = th; - int cTileWidth = tw; - - if (startY + cTileHeight >= originalRegion.height) - cTileHeight = originalRegion.height - startY; - - if (startX + cTileWidth >= originalRegion.width) - cTileWidth = originalRegion.width - startX; - - int tx = startX; - int ty = startY; - - if (sourceSX > startX) { - cTileWidth += startX - sourceSX; - tx = sourceSX; - startX = sourceSX; - } - - if (sourceSY > startY) { - cTileHeight += startY - sourceSY; - ty = sourceSY; - startY = sourceSY; - } - - if (sourceEX < startX + cTileWidth - 1) { - cTileWidth += sourceEX - startX - cTileWidth + 1; - } - - if (sourceEY < startY + cTileHeight - 1) { - cTileHeight += sourceEY - startY - cTileHeight + 1; - } - - // The start X in the destination - int x1 = (startX + scaleX - 1 - sourceOrigin.x) / scaleX; - int x2 = (startX + scaleX -1 + cTileWidth - sourceOrigin.x) / scaleX; - int lineLength = x2 - x1; - // Suppress further processing if lineLength is non-positive - // XXX (which it should never be). - if(lineLength <= 0) continue; - x2 = (x2 - 1) * scaleX + sourceOrigin.x; - - int y1 = (startY + scaleY -1 - sourceOrigin.y) /scaleY; - startY = y1 * scaleY + sourceOrigin.y; - startX = x1 * scaleX + sourceOrigin.x; - - x1 += offx; - y1 += offy; - - if (pixbuf == null || pixbuf.length < lineLength) - pixbuf = new int[lineLength]; // line buffer for pixel data - - // Deliver in lines to reduce memory usage - for (int l = startY, m = y1; l < ty + cTileHeight; l += scaleY, m++) { - if (reader.getAbortRequest()) - break; - - // Request line data - for (int i = 0; i < numBands; i++) { - for (int j = lineLength - 1, k1 = x2; j >= 0; j--, k1-=scaleX) { - pixbuf[j] = targetRas.getSample(k1, l, i); - } - - // Send the line data to the BufferedImage - raster.setSamples(x1, m, lineLength, 1, destinationBands[i], pixbuf); - } - - if (destImage != null) - reader.processImageUpdateWrapper(destImage, x1, m, - cTileWidth, 1, 1, 1, - destinationBands); - - reader.processImageProgressWrapper(percentage + - (l - startY + 1.0F) / - cTileHeight / totalTiles); - } - } // End loop on horizontal tiles - } // End loop on vertical tiles - } - - public void setDestImage(BufferedImage image) { - destImage = image; - } - - public void clearDestImage() { - destImage = null; - } - - private int getTileNum(int x, int y) { - int num = (y - getMinTileY()) * getNumXTiles() + x - getMinTileX(); - - if (num < 0 || num >= getNumXTiles() * getNumYTiles()) - throw new IllegalArgumentException(I18N.getString("J2KReadState1")); - - return num; - } - - private int clip(int value, int min, int max) { - if (value < min) - value = min; - if (value > max) - value = max; - return value; - } - - private SampleModel createSampleModel() throws IOException { - if (sampleModel != null) - return sampleModel; - - if (metadata == null) - readImageMetadata(); - - HeaderBox header = (HeaderBox)metadata.getElement("JPEG2000HeaderBox"); - int maxDepth = 0; - boolean isSigned = false; - if (header != null) { - maxDepth = header.getBitDepth(); - isSigned = (maxDepth & 0x80) > 0; - maxDepth = (maxDepth & 0x7F) + 1; - } else { - CompParams compParam = new CompParams(); - for (int i = 0; i < size.csize; i++) { - decoder.decodeCompParams(compParam, i); - maxDepth = (compParam.depth & 0x7F) + 1; - isSigned = (compParam.depth & 0x80) > 0 ? true : false; - } - } - - BitsPerComponentBox bits = - (BitsPerComponentBox)metadata.getElement("JPEG2000BitsPerComponentBox"); - - if (bits != null) { - byte[] depths = bits.getBitDepth(); - maxDepth = (depths[0] & 0x7F) + 1; - isSigned = (depths[0] & 0x80) > 0; - for (int i = 1; i < nComp; i++) - if (maxDepth > depths[sourceBands[i]]) - maxDepth = (depths[sourceBands[i]] & 0x7F) + 1; - } - - int[] bandOffsets = new int[nComp]; - for (int i = 0; i < nComp; i++) - bandOffsets[i] = i; - - ChannelDefinitionBox cdb= - (ChannelDefinitionBox)metadata.getElement("JPEG2000ChannelDefinitionBox"); - - if (cdb != null && - metadata.getElement("JPEG2000PaletteBox") == null) { - short[] assoc = cdb.getAssociation(); - short[] types = cdb.getTypes(); - short[] channels = cdb.getChannel(); - - for (int i = 0; i < types.length; i++) - if (types[i] == 0) - bandOffsets[sourceBands[channels[i]]] = assoc[i] - 1; - else if (types[i] == 1 || types[i] == 2) - bandOffsets[sourceBands[channels[i]]] = channels[i]; - } - - return createSampleModel(nComp, maxDepth, bandOffsets, - isSigned, tileWidth, tileHeight); - } - - private SampleModel createOriginalSampleModel() throws IOException { - if (metadata == null) - readImageMetadata(); - - HeaderBox header = (HeaderBox)metadata.getElement("JPEG2000HeaderBox"); - int maxDepth = 0; - boolean isSigned = false; - int nc = size.csize; - if (header != null) { - maxDepth = header.getBitDepth(); - isSigned = (maxDepth & 0x80) > 0; - maxDepth = (maxDepth & 0x7F) + 1; - } else { - CompParams compParam = new CompParams(); - for (int i = 0; i < size.csize; i++) { - decoder.decodeCompParams(compParam, i); - maxDepth = (compParam.depth & 0x7F) + 1; - isSigned = (compParam.depth & 0x80) > 0 ? true : false; - } - } - - BitsPerComponentBox bits = - (BitsPerComponentBox)metadata.getElement("JPEG2000BitsPerComponentBox"); - - if (bits != null) { - byte[] depths = bits.getBitDepth(); - maxDepth = (depths[0] & 0x7F) + 1; - isSigned = (depths[0] & 0x80) > 0; - for (int i = 1; i < nc; i++) - if (maxDepth > depths[i]) - maxDepth = (depths[i] & 0x7F) + 1; - } - - int[] bandOffsets = new int[nc]; - for (int i = 0; i < nc; i++) - bandOffsets[i] = i; - - ChannelDefinitionBox cdb= - (ChannelDefinitionBox)metadata.getElement("JPEG2000ChannelDefinitionBox"); - if (cdb != null && - metadata.getElement("JPEG2000PaletteBox") == null) { - short[] assoc = cdb.getAssociation(); - short[] types = cdb.getTypes(); - short[] channels = cdb.getChannel(); - - channelMap = new int[nc]; - - for (int i = 0; i < types.length; i++) - if (types[i] == 0) { - bandOffsets[channels[i]] = assoc[i] - 1; - channelMap[assoc[i] - 1] = channels[i]; - } - else if (types[i] == 1 || types[i] == 2) { - bandOffsets[channels[i]] = channels[i]; - channelMap[channels[i]] = channels[i]; - } - } - - return createSampleModel(nc, maxDepth, bandOffsets, isSigned, - tileWidth, tileHeight); - } - - private SampleModel createSampleModel(int nc, int maxDepth, - int[] bandOffsets, boolean isSigned, - int tw, int th) { - SampleModel sm = null; - if (nc == 1 && (maxDepth == 1 || maxDepth == 2 || maxDepth == 4)) - sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, - tw, th, maxDepth); - else if (maxDepth <= 8) - sm = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, - tw, th, nc, tw * nc, bandOffsets); - else if (maxDepth <=16) - sm = new PixelInterleavedSampleModel(isSigned ? DataBuffer.TYPE_SHORT : DataBuffer.TYPE_USHORT, - tw, th, nc, tw * nc, bandOffsets); - else if (maxDepth <= 32) - sm = new PixelInterleavedSampleModel(DataBuffer.TYPE_INT, - tw, th, nComp, tw * nComp, - bandOffsets); - else - throw new IllegalArgumentException(I18N.getString("J2KReadState11") + " " + - + maxDepth); - - return sm; - } - - private ColorModel createColorModel() throws IOException { - if (colorModel != null) - return colorModel; - - PaletteBox pBox = (PaletteBox)metadata.getElement("JPEG2000PaletteBox"); - ChannelDefinitionBox cdef = - (ChannelDefinitionBox)metadata.getElement("JPEG2000ChannelDefinitionBox"); - - // Check 'nComp' instance variable here in case there is an - // embedded palette such as in the pngsuite images pp0n2c16.png - // and pp0n6a08.png. - if (pBox != null && nComp == 1) { - byte[][] lut = pBox.getLUT(); - int numComp = pBox.getNumComp(); - - int[] mapping = new int[numComp]; - - for (int i = 0; i < numComp; i++) - mapping[i] = i; - - ComponentMappingBox cmap = - (ComponentMappingBox)metadata.getElement("JPEG2000ComponentMappingBox"); - - short[] comps = null; - byte[] type = null; - byte[] maps = null; - - if (cmap != null) { - comps = cmap.getComponent(); - type = cmap.getComponentType(); - maps = cmap.getComponentAssociation(); - } - - if (comps != null) - for (int i = 0; i < numComp; i++) - if (type[i] == 1) - mapping[i] = maps[i]; - - if (numComp == 3) - colorModel = new IndexColorModel(sampleModel.getSampleSize(0), lut[0].length, - lut[mapping[0]], - lut[mapping[1]], - lut[mapping[2]]); - else if (numComp == 4) - colorModel = new IndexColorModel(sampleModel.getSampleSize(0), lut[0].length, - lut[mapping[0]], - lut[mapping[1]], - lut[mapping[2]], - lut[mapping[3]]); - } else if (cdef != null){ - HeaderBox header = - (HeaderBox)metadata.getElement("JPEG2000HeaderBox"); - int numComp = header.getNumComponents(); - int bitDepth = header.getBitDepth(); - - boolean hasAlpha = false; - int alphaChannel = numComp - 1; - - short[] channels = cdef.getChannel(); - short[] cType = cdef.getTypes(); - short[] associations = cdef.getAssociation(); - - for (int i = 0; i < channels.length; i++) { - if (cType[i] == 1 && channels[i] == alphaChannel) - hasAlpha = true; - } - - boolean[] isPremultiplied = new boolean[] {false}; - - if (hasAlpha) { - isPremultiplied = new boolean[alphaChannel]; - - for (int i = 0; i < alphaChannel; i++) - isPremultiplied[i] = false; - - for (int i = 0; i < channels.length; i++) { - if (cType[i] == 2) - isPremultiplied[associations[i] - 1] = true; - } - - for (int i = 1; i < alphaChannel; i++) - isPremultiplied[0] &= isPremultiplied[i]; - } - - ColorSpecificationBox cBox = - (ColorSpecificationBox)metadata.getElement("JPEG2000ColorSpecificationBox"); - ICC_Profile profile = null; - int colorSpaceType = 0; - - if (cBox != null) { - profile = cBox.getICCProfile(); - colorSpaceType = cBox.getEnumeratedColorSpace(); - } - - ColorSpace cs = null; - if (profile != null) - cs = new ICC_ColorSpace(profile); - else if (colorSpaceType == ColorSpecificationBox.ECS_sRGB) - cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); - else if (colorSpaceType == ColorSpecificationBox.ECS_GRAY) - cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); - else if (colorSpaceType == ColorSpecificationBox.ECS_YCC) - cs = ColorSpace.getInstance(ColorSpace.CS_PYCC); - - byte[] bitDepths = null; - boolean isSigned = ((bitDepth & 0x80) == 0x80) ? true : false; - - BitsPerComponentBox bitBox = - (BitsPerComponentBox)metadata.getElement("JPEG2000BitsPerComponentBox"); - if (bitBox != null) - bitDepths = bitBox.getBitDepth(); - - int[] bits = new int[numComp]; - for (int i = 0; i < numComp; i++) - if (bitDepths != null) - bits[i] = (bitDepths[i] & 0x7F) + 1; - else - bits[i] = (bitDepth &0x7F) + 1; - - int maxBitDepth = 1 + (bitDepth & 0x7F); - if (bitDepths != null) - for (int i = 0; i < numComp; i++) - if (bits[i] > maxBitDepth) - maxBitDepth = bits[i]; - - int type = -1; - - if (maxBitDepth <= 8) - type = DataBuffer.TYPE_BYTE; - else if (maxBitDepth <= 16) - type = isSigned ? DataBuffer.TYPE_SHORT : DataBuffer.TYPE_USHORT; - else if (maxBitDepth <= 32) - type = DataBuffer.TYPE_INT; - - if (type == -1) - return null; - - if (cs != null) { - colorModel = new ComponentColorModel(cs, - bits, - hasAlpha, - isPremultiplied[0], - hasAlpha ? Transparency.TRANSLUCENT : Transparency.OPAQUE , - type); - } - } - - if (colorModel != null) - return colorModel; - - if(nComp <= 4) { - // XXX: Code essentially duplicated from FileFormatReader.getColorModel(). - // Create the ColorModel from the SIZ marker segment parameters. - ColorSpace cs; - if(nComp > 2) { - cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); - } else { - cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); - } - - int[] bitsPerComponent = new int[nComp]; - boolean isSigned = false; - int maxBitDepth = -1; - for(int i = 0; i < nComp; i++) { - bitsPerComponent[i] = (compParam.depth & 0x7f) + 1; - if(maxBitDepth < bitsPerComponent[i]) { - maxBitDepth = bitsPerComponent[i]; - } - isSigned |= (compParam.depth & 0x80) != 0; - } - - boolean hasAlpha = nComp % 2 == 0; - - int type = -1; - - if (maxBitDepth <= 8) { - type = DataBuffer.TYPE_BYTE; - } else if (maxBitDepth <= 16) { - type = isSigned ? DataBuffer.TYPE_SHORT : DataBuffer.TYPE_USHORT; - } else if (maxBitDepth <= 32) { - type = DataBuffer.TYPE_INT; - } - - if (type != -1) { - if (nComp == 1 && - (maxBitDepth == 1 || maxBitDepth == 2 || - maxBitDepth == 4)) { - colorModel = ImageUtil.createColorModel(getSampleModel()); - } else { - colorModel = new ComponentColorModel(cs, - bitsPerComponent, - hasAlpha, - false, - hasAlpha ? - Transparency.TRANSLUCENT : - Transparency.OPAQUE , - type); - } - - return colorModel; - } - } - - return ImageUtil.createColorModel(null, getSampleModel()); - } - - public J2KMetadata readImageMetadata() throws IOException { - if (metadata == null) { - metadata = new J2KMetadata(); - com.sun.medialib.codec.jp2k.Box mlibBox = null; - com.sun.media.imageioimpl.plugins.jpeg2000.Box box = null; - - while ((mlibBox = decoder.decodeBox()) != null) { - box = null; - Class c = com.sun.media.imageioimpl.plugins.jpeg2000.Box.getBoxClass(mlibBox.type); - if (c != null) { - try { - Constructor cons = c.getConstructor(new Class[]{byte[].class}); - if (cons != null) { - box = (Box)cons.newInstance(new Object[]{mlibBox.data}); - } - } catch(NoSuchMethodException e) { - try { - Constructor cons = c.getConstructor(new Class[]{int.class, byte[].class}); - if (cons != null) { - box = (com.sun.media.imageioimpl.plugins.jpeg2000.Box) - cons.newInstance(new Object[]{new Integer(mlibBox.type), mlibBox.data}); - } - } catch (NoSuchMethodException e1) { - box = createUnknowBox(mlibBox); - } catch(InvocationTargetException e1) { - box = createUnknowBox(mlibBox); - } catch (IllegalAccessException e1) { - box = createUnknowBox(mlibBox); - } catch (InstantiationException e1) { - box = createUnknowBox(mlibBox); - } - } catch(InvocationTargetException e) { - box = createUnknowBox(mlibBox); - } catch (IllegalAccessException e) { - box = createUnknowBox(mlibBox); - } catch (InstantiationException e) { - box = createUnknowBox(mlibBox); - } - } else { - if (mlibBox.data != null) - box = createUnknowBox(mlibBox); - } - if (box != null) - metadata.addNode(box); - } - } - - return metadata; - } - - private com.sun.media.imageioimpl.plugins.jpeg2000.Box - createUnknowBox(com.sun.medialib.codec.jp2k.Box mlibBox) { - return - new com.sun.media.imageioimpl.plugins.jpeg2000.Box(8 + mlibBox.data.length, - mlibBox.type, - mlibBox.data); - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KRenderedImage.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KRenderedImage.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KRenderedImage.java 2006-09-27 20:57:57.000000000 -0400 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/J2KRenderedImage.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,129 +0,0 @@ -/* - * $RCSfile: J2KRenderedImage.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.2 $ - * $Date: 2006/09/28 00:57:57 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.image.Raster; -import java.awt.image.WritableRaster; -import java.io.*; -import javax.imageio.stream.ImageInputStream; -import jj2000.j2k.codestream.reader.*; - -import com.sun.media.imageioimpl.common.SimpleRenderedImage; - -public class J2KRenderedImage extends SimpleRenderedImage { - private Raster currentTile; - private Point currentTileGrid; - - private J2KReadState readState; - - public J2KRenderedImage(ImageInputStream iis, - J2KImageReadParamJava param, - J2KMetadata metadata, - J2KImageReader reader) throws IOException { - this(new J2KReadState(iis, param, metadata, reader)); - } - - public J2KRenderedImage(ImageInputStream iis, - J2KImageReadParamJava param, - J2KImageReader reader) throws IOException { - this(new J2KReadState(iis, param, reader)); - } - - public J2KRenderedImage(J2KReadState readState) { - this.readState = readState; - - HeaderDecoder hd = readState.getHeader(); - - //determnined by destination - Rectangle destinationRegion = readState.getDestinationRegion(); - width = destinationRegion.width; - height = destinationRegion.height; - minX = destinationRegion.x; - minY = destinationRegion.y; - - Rectangle tile0Rect = readState.getTile0Rect(); - tileWidth = tile0Rect.width; - tileHeight = tile0Rect.height; - tileGridXOffset = tile0Rect.x; - tileGridYOffset = tile0Rect.y; - - sampleModel = readState.getSampleModel(); - colorModel = readState.getColorModel(); - } - - public synchronized Raster getTile(int tileX, int tileY) { - if (currentTile != null && - currentTileGrid.x == tileX && - currentTileGrid.y == tileY) - return currentTile; - - if (tileX >= getNumXTiles() || tileY >= getNumYTiles()) - throw new IllegalArgumentException(I18N.getString("J2KReadState1")); - - try { - int x = tileXToX(tileX); - int y = tileYToY(tileY); - currentTile = - Raster.createWritableRaster(sampleModel, - new Point(x, y)); - currentTile = readState.getTile(tileX, - tileY, - (WritableRaster)currentTile); - } catch (IOException e) { - throw new RuntimeException(e); - } - - if (currentTileGrid == null) - currentTileGrid = new Point(tileX, tileY); - else { - currentTileGrid.x = tileX; - currentTileGrid.y = tileY; - } - - return currentTile; - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/MediaLibAccessor.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/MediaLibAccessor.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/MediaLibAccessor.java 2005-02-11 00:01:36.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/MediaLibAccessor.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,1222 +0,0 @@ -/* - * $RCSfile: MediaLibAccessor.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:36 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; -import java.awt.Rectangle; -import java.awt.image.ColorModel; -import java.awt.image.ComponentSampleModel; -import java.awt.image.ComponentColorModel; -import java.awt.image.DataBuffer; -import java.awt.image.DataBufferByte; -import java.awt.image.DataBufferDouble; -import java.awt.image.DataBufferFloat; -import java.awt.image.DataBufferInt; -import java.awt.image.DataBufferShort; -import java.awt.image.DataBufferUShort; -import java.awt.image.MultiPixelPackedSampleModel; -import java.awt.image.Raster; -import java.awt.image.SampleModel; -import java.awt.image.WritableRaster; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.ParameterBlock; -import java.io.FileNotFoundException; -import java.io.FilePermission; -import java.io.InputStream; -import java.io.IOException; -import java.lang.NoClassDefFoundError; -import java.security.AccessControlException; -import java.security.AccessController; -import java.security.PrivilegedAction; - -import com.sun.media.imageioimpl.common.ImageUtil; -import com.sun.medialib.codec.jiio.Util; -import com.sun.medialib.codec.jiio.Constants; -import com.sun.medialib.codec.jiio.mediaLibImage; - -/** - * An adapter class for presenting image data in a mediaLibImage - * format, even if the data isn't stored that way. MediaLibAccessor - * is meant to make the common case (ComponentRasters) and allow - * them to be accelerated via medialib. Note that unlike RasterAccessor, - * MediaLibAccessor does not work with all cases. In the event that - * MediaLibAccessor can not deal with a give collection of Rasters, - * findCompatibleTag will return the value MediaLibAccessor.TAG_INCOMPATIBLE. - * OpImages that use MediaLibAccessor should be paired with RIF's - * which check that findCompatibleTag returns a valid tag before - * actually constructing the Mlib OpImage. - */ - -public class MediaLibAccessor { - /** - * Value indicating how far COPY_MASK info is shifted to avoid - * interfering with the data type info - */ - private static final int COPY_MASK_SHIFT = 7; - - /* Value indicating how many bits the COPY_MASK is */ - private static final int COPY_MASK_SIZE = 1; - - /** The bits of a FormatTag associated with how dataArrays are obtained. */ - public static final int COPY_MASK = 0x1 << COPY_MASK_SHIFT; - - /** Flag indicating data is raster's data. */ - public static final int UNCOPIED = 0x0 << COPY_MASK_SHIFT; - - /** Flag indicating data is a copy of the raster's data. */ - public static final int COPIED = 0x01 << COPY_MASK_SHIFT; - - /** The bits of a FormatTag associated with pixel datatype. */ - public static final int DATATYPE_MASK = (0x1 << COPY_MASK_SHIFT) - 1; - - /** - * Value indicating how far BINARY_MASK info is shifted to avoid - * interfering with the data type and copying info. - */ - private static final int BINARY_MASK_SHIFT = - COPY_MASK_SHIFT+COPY_MASK_SIZE; - - /** Value indicating how many bits the BINARY_MASK is */ - private static final int BINARY_MASK_SIZE = 1; - - /** The bits of a FormatTag associated with binary data. */ - public static final int BINARY_MASK = - ((1 << BINARY_MASK_SIZE) - 1) << BINARY_MASK_SHIFT; - - /** Flag indicating data are not binary. */ - public static final int NONBINARY = 0x0 << BINARY_MASK_SHIFT; - - /** Flag indicating data are binary. */ - public static final int BINARY = 0x1 << BINARY_MASK_SHIFT; - - /** FormatTag indicating data in byte arrays and uncopied. */ - public static final int - TAG_BYTE_UNCOPIED = DataBuffer.TYPE_BYTE | UNCOPIED; - - /** FormatTag indicating data in unsigned short arrays and uncopied. */ - public static final int - TAG_USHORT_UNCOPIED = DataBuffer.TYPE_USHORT | UNCOPIED; - - /** FormatTag indicating data in short arrays and uncopied. */ - public static final int - TAG_SHORT_UNCOPIED = DataBuffer.TYPE_SHORT | UNCOPIED; - - /** FormatTag indicating data in integer arrays and uncopied. */ - public static final int - TAG_INT_UNCOPIED = DataBuffer.TYPE_INT | UNCOPIED; - - /** FormatTag indicating data in float arrays and uncopied. */ - public static final int - TAG_FLOAT_UNCOPIED = DataBuffer.TYPE_FLOAT | UNCOPIED; - - /** FormatTag indicating data in double arrays and uncopied. */ - public static final int - TAG_DOUBLE_UNCOPIED = DataBuffer.TYPE_DOUBLE | UNCOPIED; - - /** FormatTag indicating data in byte arrays and uncopied. */ - public static final int - TAG_BYTE_COPIED = DataBuffer.TYPE_BYTE | COPIED; - - /** FormatTag indicating data in unsigned short arrays and copied. */ - public static final int - TAG_USHORT_COPIED = DataBuffer.TYPE_USHORT | COPIED; - - /** FormatTag indicating data in short arrays and copied. */ - public static final int - TAG_SHORT_COPIED = DataBuffer.TYPE_SHORT | COPIED; - - /** FormatTag indicating data in short arrays and copied. */ - public static final int - TAG_INT_COPIED = DataBuffer.TYPE_INT | COPIED; - - /** FormatTag indicating data in float arrays and copied. */ - public static final int - TAG_FLOAT_COPIED = DataBuffer.TYPE_FLOAT | COPIED; - - /** FormatTag indicating data in double arrays and copied. */ - public static final int - TAG_DOUBLE_COPIED = DataBuffer.TYPE_DOUBLE | COPIED; - - /** The raster that is the source of pixel data. */ - protected Raster raster; - - /** The rectangle of the raster that MediaLibAccessor addresses. */ - protected Rectangle rect; - - /** The number of bands per pixel in the data array. */ - protected int numBands; - - /** The offsets of each band in the src image */ - protected int bandOffsets[]; - - /** Tag indicating the data type of the data and whether its copied */ - protected int formatTag; - - /** Area of mediaLib images that represent image data */ - protected mediaLibImage mlimages[] = null; - - /** - * Whether packed data are preferred when processing binary images. - * This tag is ignored if the data are not binary. - */ - private boolean areBinaryDataPacked = false; - - /** - * Returns the most efficient FormatTag that is compatible with - * the destination raster and all source rasters. - * - * @param srcs the source Raster; may be null. - * @param dst the destination Raster. - */ - public static int findCompatibleTag(Raster src) { - SampleModel dstSM = src.getSampleModel(); - int dstDT = dstSM.getDataType(); - - int defaultDataType = dstSM.getDataType(); - - boolean allComponentSampleModel = - dstSM instanceof ComponentSampleModel; - boolean allBinary = ImageUtil.isBinary(dstSM); - - if(allBinary) { - // The copy flag is not set until the mediaLibImage is - // created as knowing this information requires too much - // processing to determine here. - return DataBuffer.TYPE_BYTE | BINARY; - } - - if (!allComponentSampleModel) { - if ((defaultDataType == DataBuffer.TYPE_BYTE) || - (defaultDataType == DataBuffer.TYPE_USHORT) || - (defaultDataType == DataBuffer.TYPE_SHORT)) { - defaultDataType = DataBuffer.TYPE_INT; - } - } - - int tag = defaultDataType | COPIED; - - if (!allComponentSampleModel) { - return tag; - } - - if (isPixelSequential(dstSM)) - return dstDT | UNCOPIED; - return tag; - } - - /** - * Determines if the SampleModel stores data in a way that can - * be represented by a mediaLibImage without copying - */ - public static boolean isPixelSequential(SampleModel sm) { - ComponentSampleModel csm = null; - if (sm instanceof ComponentSampleModel) { - csm = (ComponentSampleModel)sm; - } else { - return false; - } - int pixelStride = csm.getPixelStride(); - int bandOffsets[] = csm.getBandOffsets(); - int bankIndices[] = csm.getBankIndices(); - if (pixelStride != bandOffsets.length) { - return false; - } - - //XXX: for band-selection result - if (pixelStride != sm.getNumBands()) - return false; - - for (int i = 0; i < bandOffsets.length; i++) { - if (bandOffsets[i] >= pixelStride || - bankIndices[i] != bankIndices[0]) { - return false; - } - for (int j = i+1; j < bandOffsets.length; j++) { - if (bandOffsets[i] == bandOffsets[j]) { - return false; - } - - //XXX: for BGR images - if (bandOffsets[i] != i) - return false; - } - } - return true; - } - - public static int getMediaLibDataType(int formatTag) { - int dataType = formatTag & DATATYPE_MASK; - switch (dataType) { - case DataBuffer.TYPE_BYTE: - return Constants.MLIB_BYTE; - case DataBuffer.TYPE_USHORT: - return Constants.MLIB_USHORT; - case DataBuffer.TYPE_SHORT: - return Constants.MLIB_SHORT; - case DataBuffer.TYPE_INT: - return Constants.MLIB_INT; - case DataBuffer.TYPE_DOUBLE: - return Constants.MLIB_DOUBLE; - case DataBuffer.TYPE_FLOAT: - return Constants.MLIB_FLOAT; - } - return -1; - } - - /** - * Constructs a MediaLibAccessor object out of a Raster, Rectangle - * and formatTag returned from MediaLibAccessor.findCompatibleTag(). - * - * In the case of binary data the copy mask bits of the formatTag - * will be reset within the constructor according to whether the - * data are in fact copied. This cannot be easily determined before - * the data are actually copied. - */ - public MediaLibAccessor(Raster raster, Rectangle rect, int formatTag, - boolean preferPacked) { - areBinaryDataPacked = preferPacked; - - this.raster = raster; - this.rect = new Rectangle(rect); - this.formatTag = formatTag; - - if(isBinary()) { - // Set binary-specific fields and return. - numBands = 1; - bandOffsets = new int[] {0}; - - int mlibType; - int scanlineStride; - byte[] bdata; - mlimages = new mediaLibImage[1]; - - if(areBinaryDataPacked) { - mlibType = Constants.MLIB_BIT; - scanlineStride = (rect.width+7)/8; - bdata = ImageUtil.getPackedBinaryData(raster, rect); - - // Update format tag depending on whether the data were copied. - if(bdata == - ((DataBufferByte)raster.getDataBuffer()).getData()) { - this.formatTag |= UNCOPIED; - } else { - this.formatTag |= COPIED; - } - } else { // unpacked - mlibType = Constants.MLIB_BYTE; - scanlineStride = rect.width; - bdata = ImageUtil.getUnpackedBinaryData(raster, rect); - this.formatTag |= COPIED; - } - - mlimages[0] = new mediaLibImage(mlibType, - 1, - rect.width, - rect.height, - scanlineStride, - 0, - bdata); - - return; - } - - if ((formatTag & COPY_MASK) == UNCOPIED) { - ComponentSampleModel csm = - (ComponentSampleModel)raster.getSampleModel(); - - numBands = csm.getNumBands(); - bandOffsets = csm.getBandOffsets(); - int dataOffset = raster.getDataBuffer().getOffset(); - dataOffset += - (rect.y-raster.getSampleModelTranslateY())*csm.getScanlineStride()+ - (rect.x-raster.getSampleModelTranslateX())*csm.getPixelStride(); - - // dataoffset should and is in terms of dataElements - - // scanline stride should be in terms of dataElements - int scanlineStride = csm.getScanlineStride(); - - switch (formatTag & DATATYPE_MASK) { - case DataBuffer.TYPE_BYTE: - DataBufferByte dbb = (DataBufferByte)raster.getDataBuffer(); - mlimages = new mediaLibImage[1]; - mlimages[0] = - new mediaLibImage(Constants.MLIB_BYTE, - numBands, - rect.width, - rect.height, - scanlineStride, - dataOffset, - dbb.getData()); - break; - - case DataBuffer.TYPE_USHORT: - DataBufferUShort dbus = - (DataBufferUShort)raster.getDataBuffer(); - mlimages = new mediaLibImage[1]; - mlimages[0] = - new mediaLibImage(Constants.MLIB_USHORT, - numBands, - rect.width, - rect.height, - scanlineStride, - dataOffset, - dbus.getData()); - break; - case DataBuffer.TYPE_SHORT: - DataBufferShort dbs = (DataBufferShort)raster.getDataBuffer(); - mlimages = new mediaLibImage[1]; - mlimages[0] = - new mediaLibImage(Constants.MLIB_SHORT, - numBands, - rect.width, - rect.height, - scanlineStride, - dataOffset, - dbs.getData()); - break; - case DataBuffer.TYPE_INT: - DataBufferInt dbi = (DataBufferInt)raster.getDataBuffer(); - mlimages = new mediaLibImage[1]; - mlimages[0] = - new mediaLibImage(Constants.MLIB_INT, - numBands, - rect.width, - rect.height, - scanlineStride, - dataOffset, - dbi.getData()); - break; - case DataBuffer.TYPE_FLOAT: - DataBufferFloat dbf = (DataBufferFloat)raster.getDataBuffer(); - mlimages = new mediaLibImage[1]; - mlimages[0] = - new mediaLibImage(Constants.MLIB_FLOAT, - numBands, - rect.width, - rect.height, - scanlineStride, - dataOffset, - dbf.getData()); - break; - case DataBuffer.TYPE_DOUBLE: - DataBufferDouble dbd = (DataBufferDouble)raster.getDataBuffer(); - mlimages = new mediaLibImage[1]; - mlimages[0] = - new mediaLibImage(Constants.MLIB_DOUBLE, - numBands, - rect.width, - rect.height, - scanlineStride, - dataOffset, - dbd.getData()); - break; - default: - throw new IllegalArgumentException((formatTag & DATATYPE_MASK) + - "MediaLibAccessor does not recognize this datatype."); - } - } else { - // Copying the data because we can't deal with it - numBands = raster.getNumBands(); - bandOffsets = new int[numBands]; - for (int i = 0; i < numBands; i++) { - bandOffsets[i] = i; - } - int scanlineStride = rect.width*numBands; - - switch (formatTag & DATATYPE_MASK) { - case DataBuffer.TYPE_BYTE: - byte bdata[] = new byte[rect.width*rect.height*numBands]; - mlimages = new mediaLibImage[1]; - mlimages[0] = - new mediaLibImage(Constants.MLIB_BYTE, - numBands, - rect.width, - rect.height, - scanlineStride, - 0, - bdata); - break; - case DataBuffer.TYPE_USHORT: - short usdata[] = new short[rect.width*rect.height*numBands]; - mlimages = new mediaLibImage[1]; - mlimages[0] = - new mediaLibImage(Constants.MLIB_USHORT, - numBands, - rect.width, - rect.height, - scanlineStride, - 0, - usdata); - break; - case DataBuffer.TYPE_SHORT: - short sdata[] = new short[rect.width*rect.height*numBands]; - mlimages = new mediaLibImage[1]; - mlimages[0] = - new mediaLibImage(Constants.MLIB_SHORT, - numBands, - rect.width, - rect.height, - scanlineStride, - 0, - sdata); - break; - case DataBuffer.TYPE_INT: - int idata[] = new int[rect.width*rect.height*numBands]; - mlimages = new mediaLibImage[1]; - mlimages[0] = - new mediaLibImage(Constants.MLIB_INT, - numBands, - rect.width, - rect.height, - scanlineStride, - 0, - idata); - break; - case DataBuffer.TYPE_FLOAT: - float fdata[] = new float[rect.width*rect.height*numBands]; - mlimages = new mediaLibImage[1]; - mlimages[0] = - new mediaLibImage(Constants.MLIB_FLOAT, - numBands, - rect.width, - rect.height, - scanlineStride, - 0, - fdata); - break; - case DataBuffer.TYPE_DOUBLE: - double ddata[] = new double[rect.width*rect.height*numBands]; - mlimages = new mediaLibImage[1]; - mlimages[0] = - new mediaLibImage(Constants.MLIB_DOUBLE, - numBands, - rect.width, - rect.height, - scanlineStride, - 0, - ddata); - break; - default: - throw new IllegalArgumentException((formatTag & DATATYPE_MASK) + - "MediaLibAccessor does not recognize this datatype."); - } - copyDataFromRaster(); - } - } - - /** - * Returns true if the MediaLibAccessor - * represents binary data. - */ - public boolean isBinary() { - return ((formatTag & BINARY_MASK) == BINARY); - } - - /** - * Returns an array of mediaLibImages which represents the input raster. - * An array is returned instead of a single mediaLibImage because - * in some cases, an input Raster can't be represented by one - * mediaLibImage (unless copying is done) but can be represented - * by several mediaLibImages without copying. - */ - public mediaLibImage[] getMediaLibImages() { - return mlimages; - } - - /** - * Returns the data type of the RasterAccessor object. Note that - * this datatype is not necessarily the same data type as the - * underlying raster. - */ - public int getDataType() { - return formatTag & DATATYPE_MASK; - } - - /** - * Returns true if the MediaLibAccessors's data is copied from it's - * raster. - */ - public boolean isDataCopy() { - return ((formatTag & COPY_MASK) == COPIED); - } - - /** Returns the bandOffsets. */ - public int[] getBandOffsets() { - return bandOffsets; - } - - /** - * Returns parameters in the appropriate order if MediaLibAccessor - * has reordered the bands or is attempting to make a - * BandSequential image look like multiple PixelSequentialImages - */ - public int[] getIntParameters(int band, int params[]) { - int returnParams[] = new int[numBands]; - for (int i = 0; i < numBands; i++) { - returnParams[i] = params[bandOffsets[i+band]]; - } - return returnParams; - } - - /** - * Returns parameters in the appropriate order if MediaLibAccessor - * has reordered the bands or is attempting to make a - * BandSequential image look like multiple PixelSequentialImages - */ - public int[][] getIntArrayParameters(int band, int[][] params) { - int returnParams[][] = new int[numBands][]; - for (int i = 0; i < numBands; i++) { - returnParams[i] = params[bandOffsets[i+band]]; - } - return returnParams; - } - - /** - * Returns parameters in the appropriate order if MediaLibAccessor - * has reordered the bands or is attempting to make a - * BandSequential image look like multiple PixelSequentialImages - */ - public double[] getDoubleParameters(int band, double params[]) { - double returnParams[] = new double[numBands]; - for (int i = 0; i < numBands; i++) { - returnParams[i] = params[bandOffsets[i+band]]; - } - return returnParams; - } - - - /** - * Copy data from Raster to MediaLib image - */ - private void copyDataFromRaster() { - // Writeback should only be necessary on destRasters which - // should be writable so this cast should succeed. - - if (raster.getSampleModel() instanceof ComponentSampleModel) { - ComponentSampleModel csm = - (ComponentSampleModel)raster.getSampleModel(); - int rasScanlineStride = csm.getScanlineStride(); - int rasPixelStride = csm.getPixelStride(); - - int subRasterOffset = - (rect.y-raster.getSampleModelTranslateY())*rasScanlineStride+ - (rect.x-raster.getSampleModelTranslateX())*rasPixelStride; - - int rasBankIndices[] = csm.getBankIndices(); - int rasBandOffsets[] = csm.getBandOffsets(); - int rasDataOffsets[] = raster.getDataBuffer().getOffsets(); - - if (rasDataOffsets.length == 1) { - for (int i = 0; i < numBands; i++) { - rasBandOffsets[i] += rasDataOffsets[0] + - subRasterOffset; - } - } else if (rasDataOffsets.length == rasBandOffsets.length) { - for (int i = 0; i < numBands; i++) { - rasBandOffsets[i] += rasDataOffsets[i] + - subRasterOffset; - } - } - - Object mlibDataArray = null; - switch (getDataType()) { - case DataBuffer.TYPE_BYTE: - byte bArray[][] = new byte[numBands][]; - for (int i = 0; i < numBands; i++) { - bArray[i] = mlimages[0].getByteData(); - } - mlibDataArray = bArray; - break; - case DataBuffer.TYPE_USHORT: - short usArray[][] = new short[numBands][]; - for (int i = 0; i < numBands; i++) { - usArray[i] = mlimages[0].getUShortData(); - } - mlibDataArray = usArray; - break; - case DataBuffer.TYPE_SHORT: - short sArray[][] = new short[numBands][]; - for (int i = 0; i < numBands; i++) { - sArray[i] = mlimages[0].getShortData(); - } - mlibDataArray = sArray; - break; - case DataBuffer.TYPE_INT: - int iArray[][] = new int[numBands][]; - for (int i = 0; i < numBands; i++) { - iArray[i] = mlimages[0].getIntData(); - } - mlibDataArray = iArray; - break; - case DataBuffer.TYPE_FLOAT: - float fArray[][] = new float[numBands][]; - for (int i = 0; i < numBands; i++) { - fArray[i] = mlimages[0].getFloatData(); - } - mlibDataArray = fArray; - break; - case DataBuffer.TYPE_DOUBLE: - double dArray[][] = new double[numBands][]; - for (int i = 0; i < numBands; i++) { - dArray[i] = mlimages[0].getDoubleData(); - } - mlibDataArray = dArray; - break; - } - - - - Object rasDataArray = null; - switch (csm.getDataType()) { - case DataBuffer.TYPE_BYTE: { - DataBufferByte dbb = - (DataBufferByte)raster.getDataBuffer(); - byte rasByteDataArray[][] = new byte[numBands][]; - for (int i = 0; i < numBands; i++) { - rasByteDataArray[i] = - dbb.getData(rasBankIndices[i]); - } - rasDataArray = rasByteDataArray; - } - break; - case DataBuffer.TYPE_USHORT: { - DataBufferUShort dbus = - (DataBufferUShort)raster.getDataBuffer(); - short rasUShortDataArray[][] = new short[numBands][]; - for (int i = 0; i < numBands; i++) { - rasUShortDataArray[i] = - dbus.getData(rasBankIndices[i]); - } - rasDataArray = rasUShortDataArray; - } - break; - case DataBuffer.TYPE_SHORT: { - DataBufferShort dbs = - (DataBufferShort)raster.getDataBuffer(); - short rasShortDataArray[][] = new short[numBands][]; - for (int i = 0; i < numBands; i++) { - rasShortDataArray[i] = - dbs.getData(rasBankIndices[i]); - } - rasDataArray = rasShortDataArray; - } - break; - case DataBuffer.TYPE_INT: { - DataBufferInt dbi = - (DataBufferInt)raster.getDataBuffer(); - int rasIntDataArray[][] = new int[numBands][]; - for (int i = 0; i < numBands; i++) { - rasIntDataArray[i] = - dbi.getData(rasBankIndices[i]); - } - rasDataArray = rasIntDataArray; - } - break; - case DataBuffer.TYPE_FLOAT: { - DataBufferFloat dbf = - (DataBufferFloat)raster.getDataBuffer(); - float rasFloatDataArray[][] = new float[numBands][]; - for (int i = 0; i < numBands; i++) { - rasFloatDataArray[i] = - dbf.getData(rasBankIndices[i]); - } - rasDataArray = rasFloatDataArray; - } - break; - case DataBuffer.TYPE_DOUBLE: { - DataBufferDouble dbd = - (DataBufferDouble)raster.getDataBuffer(); - double rasDoubleDataArray[][] = new double[numBands][]; - for (int i = 0; i < numBands; i++) { - rasDoubleDataArray[i] = - dbd.getData(rasBankIndices[i]); - } - rasDataArray = rasDoubleDataArray; - } - break; - } - - - // dst = mlib && src = ras - Util.Reformat( - mlibDataArray, - rasDataArray, - numBands, - rect.width,rect.height, - getMediaLibDataType(this.getDataType()), - bandOffsets, - rect.width*numBands, - numBands, - getMediaLibDataType(csm.getDataType()), - rasBandOffsets, - rasScanlineStride, - rasPixelStride); - } else { - // If COPIED and the raster doesn't have ComponentSampleModel - // data is moved with getPixel/setPixel (even byte/short) - switch (getDataType()) { - case DataBuffer.TYPE_INT: - raster.getPixels(rect.x,rect.y, - rect.width,rect.height, - mlimages[0].getIntData()); - break; - case DataBuffer.TYPE_FLOAT: - raster.getPixels(rect.x,rect.y, - rect.width,rect.height, - mlimages[0].getFloatData()); - break; - case DataBuffer.TYPE_DOUBLE: - raster.getPixels(rect.x,rect.y, - rect.width,rect.height, - mlimages[0].getDoubleData()); - break; - } - } - } - - - /** - * Copies data back into the MediaLibAccessor's raster. Note that - * the data is casted from the intermediate data format to - * the raster's format. If clamping is needed, the call - * clampDataArrays() method needs to be called before - * calling the copyDataToRaster() method. - */ - public void copyDataToRaster(int[] channelMap) { - if (isDataCopy()) { - - if(isBinary()) { - if(areBinaryDataPacked) { - ImageUtil.setPackedBinaryData(mlimages[0].getBitData(), - (WritableRaster)raster, - rect); - } else { // unpacked - ImageUtil.setUnpackedBinaryData(mlimages[0].getByteData(), - (WritableRaster)raster, - rect); - } - return; - } - - // Writeback should only be necessary on destRasters which - // should be writable so this cast should succeed. - WritableRaster wr = (WritableRaster)raster; - - if (wr.getSampleModel() instanceof ComponentSampleModel) { - ComponentSampleModel csm = - (ComponentSampleModel)wr.getSampleModel(); - int rasScanlineStride = csm.getScanlineStride(); - int rasPixelStride = csm.getPixelStride(); - - int subRasterOffset = - (rect.y-raster.getSampleModelTranslateY())*rasScanlineStride+ - (rect.x-raster.getSampleModelTranslateX())*rasPixelStride; - - int rasBankIndices[] = csm.getBankIndices(); - int rasBandOffsets[] = csm.getBandOffsets(); - int rasDataOffsets[] = raster.getDataBuffer().getOffsets(); - - if (rasDataOffsets.length == 1) { - for (int i = 0; i < numBands; i++) { - rasBandOffsets[i] += rasDataOffsets[0] + - subRasterOffset; - } - } else if (rasDataOffsets.length == rasBandOffsets.length) { - for (int i = 0; i < numBands; i++) { - rasBandOffsets[i] += rasDataOffsets[i] + - subRasterOffset; - } - } - - Object mlibDataArray = null; - switch (getDataType()) { - case DataBuffer.TYPE_BYTE: - byte bArray[][] = new byte[numBands][]; - for (int i = 0; i < numBands; i++) { - bArray[i] = mlimages[0].getByteData(); - } - mlibDataArray = bArray; - break; - case DataBuffer.TYPE_USHORT: - short usArray[][] = new short[numBands][]; - for (int i = 0; i < numBands; i++) { - usArray[i] = mlimages[0].getUShortData(); - } - mlibDataArray = usArray; - break; - case DataBuffer.TYPE_SHORT: - short sArray[][] = new short[numBands][]; - for (int i = 0; i < numBands; i++) { - sArray[i] = mlimages[0].getShortData(); - } - mlibDataArray = sArray; - break; - case DataBuffer.TYPE_INT: - int iArray[][] = new int[numBands][]; - for (int i = 0; i < numBands; i++) { - iArray[i] = mlimages[0].getIntData(); - } - mlibDataArray = iArray; - break; - case DataBuffer.TYPE_FLOAT: - float fArray[][] = new float[numBands][]; - for (int i = 0; i < numBands; i++) { - fArray[i] = mlimages[0].getFloatData(); - } - mlibDataArray = fArray; - break; - case DataBuffer.TYPE_DOUBLE: - double dArray[][] = new double[numBands][]; - for (int i = 0; i < numBands; i++) { - dArray[i] = mlimages[0].getDoubleData(); - } - mlibDataArray = dArray; - break; - } - - - byte tmpDataArray[] = null; - Object rasDataArray = null; - switch (csm.getDataType()) { - case DataBuffer.TYPE_BYTE: { - DataBufferByte dbb = - (DataBufferByte)raster.getDataBuffer(); - byte rasByteDataArray[][] = new byte[numBands][]; - for (int i = 0; i < numBands; i++) { - rasByteDataArray[i] = - dbb.getData(rasBankIndices[i]); - } - tmpDataArray = rasByteDataArray[0]; - rasDataArray = rasByteDataArray; - } - break; - case DataBuffer.TYPE_USHORT: { - DataBufferUShort dbus = - (DataBufferUShort)raster.getDataBuffer(); - short rasUShortDataArray[][] = new short[numBands][]; - for (int i = 0; i < numBands; i++) { - rasUShortDataArray[i] = - dbus.getData(rasBankIndices[i]); - } - rasDataArray = rasUShortDataArray; - } - break; - case DataBuffer.TYPE_SHORT: { - DataBufferShort dbs = - (DataBufferShort)raster.getDataBuffer(); - short rasShortDataArray[][] = new short[numBands][]; - for (int i = 0; i < numBands; i++) { - rasShortDataArray[i] = - dbs.getData(rasBankIndices[i]); - } - rasDataArray = rasShortDataArray; - } - break; - case DataBuffer.TYPE_INT: { - DataBufferInt dbi = - (DataBufferInt)raster.getDataBuffer(); - int rasIntDataArray[][] = new int[numBands][]; - for (int i = 0; i < numBands; i++) { - rasIntDataArray[i] = - dbi.getData(rasBankIndices[i]); - } - rasDataArray = rasIntDataArray; - } - break; - case DataBuffer.TYPE_FLOAT: { - DataBufferFloat dbf = - (DataBufferFloat)raster.getDataBuffer(); - float rasFloatDataArray[][] = new float[numBands][]; - for (int i = 0; i < numBands; i++) { - rasFloatDataArray[i] = - dbf.getData(rasBankIndices[i]); - } - rasDataArray = rasFloatDataArray; - } - break; - case DataBuffer.TYPE_DOUBLE: { - DataBufferDouble dbd = - (DataBufferDouble)raster.getDataBuffer(); - double rasDoubleDataArray[][] = new double[numBands][]; - for (int i = 0; i < numBands; i++) { - rasDoubleDataArray[i] = - dbd.getData(rasBankIndices[i]); - } - rasDataArray = rasDoubleDataArray; - } - break; - } - - int[] bandOffsetCopy = (int[])bandOffsets.clone(); - if (channelMap != null) { - for (int i = 0; i < bandOffsetCopy.length; i++) - bandOffsetCopy[i] = channelMap[bandOffsetCopy[i]]; - } - - // src = mlib && dst = ras - Util.Reformat( - rasDataArray, - mlibDataArray, - numBands, - rect.width,rect.height, - getMediaLibDataType(csm.getDataType()), - rasBandOffsets, - rasScanlineStride, - rasPixelStride, - getMediaLibDataType(this.getDataType()), - bandOffsetCopy, - rect.width*numBands, - numBands); - } else { - // If COPIED and the raster doesn't have ComponentSampleModel - // data is moved with getPixel/setPixel (even byte/short) - switch (getDataType()) { - case DataBuffer.TYPE_INT: - wr.setPixels(rect.x,rect.y, - rect.width,rect.height, - mlimages[0].getIntData()); - break; - case DataBuffer.TYPE_FLOAT: - wr.setPixels(rect.x,rect.y, - rect.width,rect.height, - mlimages[0].getFloatData()); - break; - case DataBuffer.TYPE_DOUBLE: - wr.setPixels(rect.x,rect.y, - rect.width,rect.height, - mlimages[0].getDoubleData()); - break; - } - } - } - } - - /** - * Clamps data array values to a range that the underlying raster - * can deal with. For example, if the underlying raster stores - * data as bytes, but the samples ares unpacked into integer arrays by - * the RasterAccessor object for an operation, the operation will - * need to call clampDataArrays() so that the data in the int - * arrays is restricted to the range 0..255 before a setPixels() - * call is made on the underlying raster. Note that some - * operations (for example, lookup) can guarantee that their - * results don't need clamping so they can call - * RasterAccessor.copyDataToRaster() without first calling this - * function. - */ - public void clampDataArrays () { - if (!isDataCopy()) { - return; - } - - // additonal medialib check: If it's a componentSampleModel - // we get a free cast when we call medialibWrapper.Reformat - // to copy the data to the source. So we don't need to cast - // here. - if (raster.getSampleModel() instanceof ComponentSampleModel) { - return; - } - - int bits[] = raster.getSampleModel().getSampleSize(); - - // Do we even need a clamp? We do if there's any band - // of the source image stored in that's less than 32 bits - // and is stored in a byte, short or int format. (The automatic - // cast's between floats/doubles and 32-bit ints in setPixel() - // generall do what we want.) - - boolean needClamp = false; - boolean uniformBitSize = true; - for (int i = 0; i < bits.length; i++) { - int bitSize = bits[0]; - if (bits[i] < 32) { - needClamp = true; - } - if (bits[i] != bitSize) { - uniformBitSize = false; - } - } - - if (!needClamp) { - return; - } - - int dataType = raster.getDataBuffer().getDataType(); - double hiVals[] = new double[bits.length]; - double loVals[] = new double[bits.length]; - - if (dataType == DataBuffer.TYPE_USHORT && - uniformBitSize && bits[0] == 16) { - for (int i = 0; i < bits.length; i++) { - hiVals[i] = (double)0xFFFF; - loVals[i] = (double)0; - } - } else if (dataType == DataBuffer.TYPE_SHORT && - uniformBitSize && bits[0] == 16) { - for (int i = 0; i < bits.length; i++) { - hiVals[i] = (double)Short.MAX_VALUE; - loVals[i] = (double)Short.MIN_VALUE; - } - } else if (dataType == DataBuffer.TYPE_INT && - uniformBitSize && bits[0] == 32) { - for (int i = 0; i < bits.length; i++) { - hiVals[i] = (double)Integer.MAX_VALUE; - loVals[i] = (double)Integer.MIN_VALUE; - } - } else { - for (int i = 0; i < bits.length; i++) { - hiVals[i] = (double)((1 << bits[i]) - 1); - loVals[i] = (double)0; - } - } - clampDataArray(hiVals,loVals); - } - - private void clampDataArray(double hiVals[], double loVals[]) { - switch (getDataType()) { - case DataBuffer.TYPE_INT: - clampIntArrays(toIntArray(hiVals),toIntArray(loVals)); - break; - case DataBuffer.TYPE_FLOAT: - clampFloatArrays(toFloatArray(hiVals),toFloatArray(loVals)); - break; - case DataBuffer.TYPE_DOUBLE: - clampDoubleArrays(hiVals,loVals); - break; - } - } - - private int[] toIntArray(double vals[]) { - int returnVals[] = new int[vals.length]; - for (int i = 0; i < vals.length; i++) { - returnVals[i] = (int)vals[i]; - } - return returnVals; - } - - private float[] toFloatArray(double vals[]) { - float returnVals[] = new float[vals.length]; - for (int i = 0; i < vals.length; i++) { - returnVals[i] = (float)vals[i]; - } - return returnVals; - } - - private void clampIntArrays(int hiVals[], int loVals[]) { - int width = rect.width; - int height = rect.height; - int scanlineStride = numBands*width; - for (int k = 0; k < numBands; k++) { - int data[] = mlimages[0].getIntData(); - int scanlineOffset = k; - int hiVal = hiVals[k]; - int loVal = loVals[k]; - for (int j = 0; j < height; j++) { - int pixelOffset = scanlineOffset; - for (int i = 0; i < width; i++) { - int tmp = data[pixelOffset]; - if (tmp < loVal) { - data[pixelOffset] = loVal; - } else if (tmp > hiVal) { - data[pixelOffset] = hiVal; - } - pixelOffset += numBands; - } - scanlineOffset += scanlineStride; - } - } - } - - private void clampFloatArrays(float hiVals[], float loVals[]) { - int width = rect.width; - int height = rect.height; - int scanlineStride = numBands*width; - for (int k = 0; k < numBands; k++) { - float data[] = mlimages[0].getFloatData(); - int scanlineOffset = k; - float hiVal = hiVals[k]; - float loVal = loVals[k]; - for (int j = 0; j < height; j++) { - int pixelOffset = scanlineOffset; - for (int i = 0; i < width; i++) { - float tmp = data[pixelOffset]; - if (tmp < loVal) { - data[pixelOffset] = loVal; - } else if (tmp > hiVal) { - data[pixelOffset] = hiVal; - } - pixelOffset += numBands; - } - scanlineOffset += scanlineStride; - } - } - } - - private void clampDoubleArrays(double hiVals[], double loVals[]) { - int width = rect.width; - int height = rect.height; - int scanlineStride = numBands*width; - for (int k = 0; k < numBands; k++) { - double data[] = mlimages[0].getDoubleData(); - int scanlineOffset = k; - double hiVal = hiVals[k]; - double loVal = loVals[k]; - for (int j = 0; j < height; j++) { - int pixelOffset = scanlineOffset; - for (int i = 0; i < width; i++) { - double tmp = data[pixelOffset]; - if (tmp < loVal) { - data[pixelOffset] = loVal; - } else if (tmp > hiVal) { - data[pixelOffset] = hiVal; - } - pixelOffset += numBands; - } - scanlineOffset += scanlineStride; - } - } - } - -} - diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/PaletteBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/PaletteBox.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/PaletteBox.java 2005-02-11 00:01:36.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/PaletteBox.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,267 +0,0 @@ -/* - * $RCSfile: PaletteBox.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:36 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.awt.image.IndexColorModel; -import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.metadata.IIOMetadataNode; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import com.sun.media.imageioimpl.common.ImageUtil; - -/** This class is designed to represent a palette box for JPEG 2000 JP2 file - * format. A palette box has a length, and a fixed type of "pclr". - * - * Its content contains the number of palette entry, the number of color - * components, the bit depths of the output components, the LUT. - * - * Currently, only 8-bit color index is supported. - */ -public class PaletteBox extends Box { - /** The value of the data elements. - */ - private int numEntries; - private int numComps; - private byte[] bitDepth; - private byte[][] lut; - - /** Compute the length of this box. */ - private static int computeLength(IndexColorModel icm) { - int size = icm.getMapSize(); - int[] comp = icm.getComponentSize(); - return 11 + comp.length + size * comp.length; - } - - /** Gets the size of the components or the bit depth for all the color - * coomponents. - */ - private static byte[] getCompSize(IndexColorModel icm) { - int[] comp = icm.getComponentSize(); - int size = comp.length; - byte[] buf = new byte[size]; - for (int i = 0; i < size; i++) - buf[i] = (byte)(comp[i] - 1); - return buf; - } - - /** Gets the LUT from the IndexColorModel as an two-dimensional - * byte array. - */ - private static byte[][] getLUT(IndexColorModel icm) { - int[] comp = icm.getComponentSize(); - int size = icm.getMapSize(); - byte[][] lut = new byte[comp.length][size]; - icm.getReds(lut[0]); - icm.getGreens(lut[1]); - icm.getBlues(lut[2]); - if (comp.length == 4) - icm.getAlphas(lut[3]); - return lut; - } - - /** Constructs a PlatteBox from an - * IndexColorModel. - */ - public PaletteBox(IndexColorModel icm) { - this(computeLength(icm), getCompSize(icm), getLUT(icm)); - } - - /** Constructs a PlatteBox from an - * org.w3c.dom.Node. - */ - public PaletteBox(Node node) throws IIOInvalidTreeException { - super(node); - byte[][] tlut = null; - int index = 0; - - NodeList children = node.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - String name = child.getNodeName(); - - if ("NumberEntries".equals(name)) { - numEntries = Box.getIntElementValue(child); - } - - if ("NumberColors".equals(name)) { - numComps = Box.getIntElementValue(child); - } - - if ("BitDepth".equals(name)) { - bitDepth = Box.getByteArrayElementValue(child); - } - - if ("LUT".equals(name)) { - tlut = new byte[numEntries][]; - - NodeList children1 = child.getChildNodes(); - - for (int j = 0; j PlatteBox from the provided length, bit - * depths of the color components and the LUT. - */ - public PaletteBox(int length, byte[] comp, byte[][] lut) { - super(length, 0x70636C72, null); - this.bitDepth = comp; - this.lut = lut; - this.numEntries = lut[0].length; - this.numComps = lut.length; - } - - /** Constructs a PlatteBox from the provided byte array. - */ - public PaletteBox(byte[] data) { - super(8 + data.length, 0x70636C72, data); - } - - /** Return the number of palette entries. */ - public int getNumEntries() { - return numEntries; - } - - /** Return the number of color components. */ - public int getNumComp() { - return numComps; - } - - /** Return the bit depths for all the color components. */ - public byte[] getBitDepths() { - return bitDepth; - } - - /** Return the LUT. */ - public byte[][] getLUT() { - return lut; - } - - /** creates an IIOMetadataNode from this palette box. - * The format of this node is defined in the XML dtd and xsd - * for the JP2 image file. - */ - public IIOMetadataNode getNativeNode() { - IIOMetadataNode node = new IIOMetadataNode(Box.getName(getType())); - setDefaultAttributes(node); - - IIOMetadataNode child = new IIOMetadataNode("NumberEntries"); - child.setUserObject(new Integer(numEntries)); - child.setNodeValue("" + numEntries); - node.appendChild(child); - - child = new IIOMetadataNode("NumberColors"); - child.setUserObject(new Integer(numComps)); - child.setNodeValue("" + numComps); - node.appendChild(child); - - child = new IIOMetadataNode("BitDepth"); - child.setUserObject(bitDepth); - child.setNodeValue(ImageUtil.convertObjectToString(bitDepth)); - node.appendChild(child); - - child = new IIOMetadataNode("LUT"); - for (int i = 0; i < numEntries; i++) { - IIOMetadataNode child1 = new IIOMetadataNode("LUTRow"); - byte[] row = new byte[numComps]; - for (int j = 0; j < numComps; j++) - row[j] = lut[j][i]; - - child1.setUserObject(row); - child1.setNodeValue(ImageUtil.convertObjectToString(row)); - child.appendChild(child1); - } - node.appendChild(child); - - return node; - } - - protected void parse(byte[] data) { - if (data == null) - return; - numEntries = (short)(((data[0] & 0xFF) << 8) | (data[1] & 0xFF)); - - numComps = data[2]; - bitDepth = new byte[numComps]; - System.arraycopy(data, 3, bitDepth, 0, numComps); - - lut = new byte[numComps][numEntries]; - for (int i = 0, k = 3 + numComps; i < numEntries; i++) - for (int j = 0; j < numComps; j++) - lut[j][i] = data[k++]; - } - - protected void compose() { - if (data != null) - return; - data = new byte[3 + numComps + numEntries * numComps]; - data[0] = (byte)(numEntries >> 8); - data[1] = (byte)(numEntries & 0xFF); - - data[2] = (byte)numComps; - System.arraycopy(bitDepth, 0, data, 3, numComps); - - for (int i = 0, k = 3 + numComps; i < numEntries; i++) - for (int j = 0; j < numComps; j++) - data[k++] = lut[j][i]; - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/properties zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/properties --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/properties 2005-02-11 00:01:38.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/properties 1969-12-31 19:00:00.000000000 -0500 @@ -1,59 +0,0 @@ -# -# $RCSfile: properties,v $ -# -# Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved. -# -# Use is subject to license terms. -# -# $Revision: 1.1 $ -# $Date: 2005/02/11 05:01:38 $ -# $State: Exp $ -# -# Internationalization file for com.sun.media.imageioimpl.plugins.jpeg2000 - -Box0=A simple box should have a static methos getElementNames. -Box1=Length should be 1 when set extra length. -Box2=Content length should be length - 8 or extraLength - 16. -J2KImageReader0=The source region is null. -J2KImageReader1=The destination region is null. -J2KImageReader2=The destination region is empty. -J2KImageReader3=The destination or source region is empty. -J2KImageReader4=Only support to decode the first image in JP2 stream. -J2KImageReader5=The provided ImageReadParam isn't a J2KImageReadParam. -J2KImageReader6=The input source has not been set. -J2KImageReader7=seekForwardOnly == true! -J2KImageWriteParamJava0=Packet per tile part cannot be negative. -J2KImageWriter0=The provided output is not an ImageOutputStream. -J2KImageWriter1=Packet headers cannot be in both main and tile headers. -J2KImageWriter2=Cannot set lossless and encoding rate at the same time. -J2KImageWriter3=The image origin coordinates should not be negative. -J2KImageWriter4=Invalid tile grid settings. -J2KImageWriter5=Only byte/short/ushort/int types are supported. -J2KImageWriter6=Only up to 16384 bands are supported. -J2KImageWriter7=output == null! -J2KImageWriter8=image == null! -J2KImageWriterMedialib0=The source region is empty. -J2KImageWriterMedialib1=output == null! -J2KImageWriterMedialib2=image == null! -J2KMetadata0=The provided metadata format is null. -J2KMetadata1=The provided metadata format isn't recognized. -J2KMetadata2=The tree to be merged is null. -J2KMetadata3=Invalid node -J2KMetadata4=Input node should be ColorSpaceType. -J2KMetadata5=Input node should be Palette. -J2KMetadata6=Input node should be Data. -J2KMetadata7=Input node should be Dimension. -J2KMetadata8=Input node should be Transparency. -J2KReadState0=Null ImageInputStream/ImageReadParam/Metadata is provided. -J2KReadState1=The provided tile grid position is out of range. -J2KReadState2=Codestream too short or bad header. -J2KReadState3=Error while reading bit stream header or parsing packets -J2KReadState4=Could not instantiate bit stream reader -J2KReadState5=Could not instantiate entropy decoder -J2KReadState6=Could not instantiate roi de-scaler -J2KReadState7=Could not instantiate dequantizer -J2KReadState8=Could not instantiate inverse wavelet transform -J2KReadState9=An error has occured during decoding. -J2KReadState10=An uncaught runtime exception has occurred -J2KReadState11=Cannot supported for this depth : -J2KReadState12=Cannot decode a code stream with different component subsample rates. diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/RenderedImageSrc.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/RenderedImageSrc.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/RenderedImageSrc.java 2006-09-22 19:07:25.000000000 -0400 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/RenderedImageSrc.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,1035 +0,0 @@ -/* - * $RCSfile: RenderedImageSrc.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.2 $ - * $Date: 2006/09/22 23:07:25 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.image.ColorModel; -import java.awt.image.ComponentSampleModel; -import java.awt.image.DataBuffer; -import java.awt.image.DataBufferByte; -import java.awt.image.RenderedImage; -import java.awt.image.Raster; -import java.awt.image.MultiPixelPackedSampleModel; -import java.awt.image.SampleModel; -import java.awt.image.WritableRaster; -import java.awt.image.renderable.ParameterBlock; - -import jj2000.j2k.image.*; -import jj2000.j2k.*; -import java.io.*; - -import com.sun.media.imageioimpl.common.ImageUtil; - -public class RenderedImageSrc implements BlkImgDataSrc { - /** The width of the image */ - private int w; - - /** The height of the image */ - private int h; - - /** The tile width for encoding */ - int tileWidth; - - /** The tile height for encoding */ - int tileHeight; - - /** The tile grid offset for encoding */ - int tileXOffset, tileYOffset; - - /** The source -> destination transformation */ - int scaleX, scaleY, xOffset, yOffset; - - /** The source bands to be encoded. */ - int[] sourceBands = null; - - /** The destination upper-left corner */ - int minX, minY; - - /** The number of components in the image */ - private int nc; - - /** The number of bits that determine the nominal dynamic range */ - // XXX: Should be an int[] of length 'nc'. - private int rb; - - /** Buffer for the 3 components of each pixel(in the current block) */ - private int[][] barr = null; - - /** Data block used only to store coordinates of the buffered blocks */ - private DataBlkInt dbi = new DataBlkInt(); - - /** The line buffer. */ - private byte buf[]; - - /** Temporary DataBlkInt object (needed when encoder uses floating-point - filters). This avoid allocating new DataBlk at each time */ - private DataBlkInt intBlk; - - private RenderedImage src; - private J2KImageWriteParamJava param; - - /** The input source raster. */ - private Raster raster; - - /** The raster for a destination tile */ - private Raster aTile; - - private Point co = new Point(); - - private int dcOffset = 0; - - private boolean isBinary = false; - - private Rectangle destinationRegion; - private Rectangle sourceRegion; - - private ColorModel cm; - private SampleModel sm; - - private boolean noTransform = true; - private boolean noSubband = true; - - /** Used to process abortion. */ - private J2KImageWriter writer; - - /** Indicates a raster rather than a RenderedImage - * to be encoded. - */ - private boolean inputIsRaster = false; - - /** - * Creates RenderedImageSrc for encoding a Raster. - * - * @param raster The Raster to be encoded. - * @param param The J2KImageWriteParamJava used in encoding. - * @param writer The J2KImageWriter performs the encoding. - * - * @param IOException If an error occurs while opening the file. - */ - public RenderedImageSrc(Raster raster, - J2KImageWriteParamJava param, - J2KImageWriter writer) { - this.raster = raster; - this.param = param; - this.writer = writer; - this.inputIsRaster = true; - - sourceRegion = param.getSourceRegion(); - - if (sourceRegion == null) - sourceRegion = new Rectangle(raster.getMinX(), raster.getMinY(), - raster.getWidth(), raster.getHeight()); - else - sourceRegion = sourceRegion.intersection(raster.getBounds()); - - if (sourceRegion.isEmpty()) - throw new RuntimeException(I18N.getString("J2KImageWriterCodecLib0")); - - sm = raster.getSampleModel(); - getFromParam(); - setSampleModelAndMore(); - setTile(0, 0); - } - - /** - * Creates RenderedImageSrc for encoding a - * RenderedImage. - * - * @param src The RenderedImage to be encoded. - * @param param The J2KImageWriteParamJava used in encoding. - * @param writer The J2KImageWriter performs the encoding. - * - * @param IOException If an error occurs while opening the file. - * */ - public RenderedImageSrc(RenderedImage src, - J2KImageWriteParamJava param, - J2KImageWriter writer) { - this.src = src; - this.param = param; - this.writer = writer; - - sourceRegion = param.getSourceRegion(); - - if (sourceRegion == null) - sourceRegion = new Rectangle(src.getMinX(), src.getMinY(), - src.getWidth(), src.getHeight()); - else - sourceRegion = sourceRegion.intersection(new Rectangle(src.getMinX(), - src.getMinY(), - src.getWidth(), - src.getHeight())); - if (sourceRegion.isEmpty()) - throw new RuntimeException(I18N.getString("J2KImageWriterCodecLib0")); - - sm = src.getSampleModel(); - cm = src.getColorModel(); - getFromParam(); - setSampleModelAndMore(); - } - - private void getFromParam() { - try { - tileWidth = param.getTileWidth(); - tileHeight = param.getTileHeight(); - tileXOffset = param.getTileGridXOffset(); - tileYOffset = param.getTileGridYOffset(); - } catch(IllegalStateException e) { - param.setTilingMode(param.MODE_EXPLICIT); - if (inputIsRaster) { - param.setTiling(raster.getWidth(), raster.getHeight(), - raster.getMinX(), raster.getMinY()); - } else { - param.setTiling(src.getWidth(), src.getHeight(), - src.getMinX(), src.getMinY()); - } - tileWidth = param.getTileWidth(); - tileHeight = param.getTileHeight(); - tileXOffset = param.getTileGridXOffset(); - tileYOffset = param.getTileGridYOffset(); - } - - scaleX = param.getSourceXSubsampling(); - scaleY = param.getSourceYSubsampling(); - xOffset = param.getSubsamplingXOffset(); - yOffset = param.getSubsamplingYOffset(); - - sourceRegion.translate(xOffset, yOffset); - sourceRegion.width -= xOffset; - sourceRegion.height -= yOffset; - - xOffset = sourceRegion.x % scaleX; - yOffset = sourceRegion.y % scaleY; - - minX = sourceRegion.x / scaleX; - minY = sourceRegion.y / scaleY; - - w = (sourceRegion.width + scaleX - 1) / scaleX; - h = (sourceRegion.height + scaleY - 1) / scaleY; - - tileXOffset += (minX - tileXOffset)/tileWidth * tileWidth; - tileYOffset += (minY - tileYOffset)/tileHeight * tileHeight; - - destinationRegion = new Rectangle(minX, minY, w, h); - - if (!destinationRegion.equals(sourceRegion) || - tileWidth != sm.getWidth() || - tileHeight != sm.getHeight() || - (!inputIsRaster && - (tileXOffset != src.getTileGridXOffset() || - tileYOffset != src.getTileGridYOffset())) || - (inputIsRaster && - (tileXOffset != raster.getMinX() || - tileYOffset != raster.getMinY()))) - noTransform = false; - - } - - private void setSampleModelAndMore() { - nc = sm.getNumBands(); - sourceBands = param.getSourceBands(); - if (sourceBands != null) { - sm = sm.createSubsetSampleModel(sourceBands); - noSubband = false; - } else { - sourceBands = new int[nc]; - for (int i = 0; i < nc; i++) - sourceBands[i] = i; - } - - sm = sm.createCompatibleSampleModel(tileWidth, tileHeight); - nc = sm.getNumBands(); - isBinary = ImageUtil.isBinary(sm); - - if(cm != null) { - // XXX: rb should be set to getComponentSize(); - rb = cm.getComponentSize(0); - for (int i = 1; i < cm.getNumComponents(); i++) - if (rb < cm.getComponentSize(i)) - rb = cm.getComponentSize(i); - } else { - // XXX: rb should be set to getSampleSize(); - rb = sm.getSampleSize(0); - for (int i = 1; i < sm.getNumBands(); i++) - if (rb < sm.getSampleSize(i)) - rb = sm.getSampleSize(i); - } - - if (!isOrigSigned(0) && rb > 1) - // XXX: if rb is an int[] this will have to change. - dcOffset = 1 << rb - 1; - } - - - public int getTilePartULX() { - return tileXOffset; - } - - public int getTilePartULY() { - return tileYOffset; - } - - /** - * Returns the width of the current tile in pixels. - * - * @return The total image width in pixels. - * */ - public int getTileWidth() { - int width = tileWidth; - int maxX = getImgULX() + getImgWidth(); - int x = co.x * tileWidth + tileXOffset; - if (x + tileWidth >= maxX) - width = maxX - x; - return width; - } - - /** - * Returns the overall height of the current tile in pixels. - * - * @return The total image height in pixels. */ - public int getTileHeight() { - int height = tileHeight; - int maxY = getImgULY() + getImgHeight(); - int y = co.y * tileHeight + tileYOffset; - if (y + tileHeight >= maxY) - height = maxY - y; - - return height; - } - - public int getNomTileWidth() { - return tileWidth; - } - - public int getNomTileHeight() { - return tileHeight; - } - - /** - * Returns the overall width of the image in pixels. This is the image's - * width without accounting for any component subsampling or tiling. The - * value of w is returned. - * - * @return The total image's width in pixels. - * */ - public int getImgWidth() { - return w; - } - - /** - * Returns the overall height of the image in pixels. This is the image's - * height without accounting for any component subsampling or tiling. The - * value of h is returned. - * - * @return The total image's height in pixels. - * */ - public int getImgHeight() { - return h; - } - - /** - * Returns the number of components in the image. The value of nc - * is returned. - * - * @return The number of components in the image. - * */ - public int getNumComps() { - return nc; - } - - public int getTileGridXOffset() { - return param.getTileGridXOffset(); - } - - public int getTileGridYOffset() { - return param.getTileGridYOffset(); - } - - public int getTileCompHeight(int t, int c) { - return tileHeight; - } - - public int getTileCompWidth(int t, int c) { - return tileWidth; - } - - /** - * Returns the component subsampling factor in the horizontal direction, - * for the specified component. This is, approximately, the ratio of - * dimensions between the reference grid and the component itself, see the - * 'ImgData' interface desription for details. - * - * @param c The index of the component (between 0 and C-1) - * - * @return The horizontal subsampling factor of component 'c' - * - * @see ImgData - * */ - public int getCompSubsX(int c) { - return 1; - } - - /** - * Returns the component subsampling factor in the vertical direction, for - * the specified component. This is, approximately, the ratio of - * dimensions between the reference grid and the component itself, see the - * 'ImgData' interface desription for details. - * - * @param c The index of the component (between 0 and C-1) - * - * @return The vertical subsampling factor of component 'c' - * - * @see ImgData - * */ - public int getCompSubsY(int c) { - return 1; - } - - /** - * Returns the width in pixels of the specified component in the current - * tile. This default implementation assumes no tiling and no component - * subsampling (i.e., all components, or components, have the same - * dimensions in pixels). - * - * @param c The index of the component, from 0 to C-1. - * - * @return The width in pixels of component n in the current - * tile. - * */ - public int getCompWidth(int n) { - return w; - } - - /** - * Returns the height in pixels of the specified component in the current - * tile. This default implementation assumes no tiling and no component - * subsampling (i.e., all components, or components, have the same - * dimensions in pixels). - * - * @param c The index of the component, from 0 to C-1. - * - * @return The height in pixels of component c in the current - * tile. - * */ - public int getCompHeight(int c) { - return h; - } - - /** - * Returns the width in pixels of the specified component in the overall - * image. This default implementation assumes no component, or component, - * subsampling (i.e. all components have the same dimensions in pixels). - * - * @param c The index of the component, from 0 to C-1. - * - * @return The width in pixels of component c in the overall - * image. - * */ - public int getCompImgWidth(int c) { - return w; - } - - /** - * Returns the height in pixels of the specified component in the overall - * image. This default implementation assumes no component, or component, - * subsampling (i.e. all components have the same dimensions in pixels). - * - * @param c The index of the component, from 0 to C-1. - * - * @return The height in pixels of component c in the overall - * image. - * */ - public int getCompImgHeight(int c) { - return h; - } - - /** - * Changes the current tile, given the new coordinates. - * - * @param x The horizontal coordinate of the tile. - * - * @param y The vertical coordinate of the new tile. - * */ - public void setTile(int x, int y) { - if (x >= getNumXTiles()) { - y += x/ getNumXTiles(); - x = x % getNumXTiles(); - } - co.x = x; - co.y = y; - aTile = null; - } - - /** - * Advances to the next tile, in standard scan-line order (by rows then - * columns). - * */ - public void nextTile() { - co.x++; - if (co.x >= getNumXTiles()) { - co.x = 0; - co.y++; - } - setTile(co.x, co.y); - } - - /** - * Returns the coordinates of the current tile. This default - * implementation assumes no-tiling, so (0,0) is returned. - * - * @param co If not null this object is used to return the information. If - * null a new one is created and returned. - * - * @return The current tile's coordinates. - * */ - public Point getTile(Point co) { - if (co != null) - return co; - else - return new Point(0, 0); - } - - /** - * Returns the index of the current tile, relative to a standard scan-line - * order. - * - * @return The current tile's index (starts at 0). - * */ - public int getTileIdx() { - return getNumXTiles() * co.y + co.x; - } - - /** - * Returns the horizontal and vertical offset of the upper-left corner of - * the current tile, in the specified component, relative to the canvas - * origin, in the component coordinates (not in the reference grid - * coordinates). These are the coordinates of the current tile's (not - * active tile) upper-left corner relative to the canvas. - * - * @param co If not null the object is used to return the values, if null - * a new one is created and returned. - * - * @param c The index of the component (between 0 and C-1) - * - * @return The horizontal and vertical offsets of the upper-left corner of - * the current tile, for the specified component, relative to the canvas - * origin, in the component coordinates. - * */ - public Point getTileOff(Point p, int c) { - if (p != null) { - p.x = co.x * tileWidth + tileXOffset; - p.y = co.y * tileHeight + tileYOffset; - return co; - } else - return new Point(co.x * tileWidth + tileXOffset, - co.y * tileHeight + tileYOffset); - } - - /** - * Returns the horizontal coordinate of the upper-left corner of the - * active tile, with respect to the canvas origin, in the component - * coordinates, for the specified component. - * - * @param c The index of the component (between 0 and C-1) - * - * @return The horizontal coordinate of the upper-left corner of the - * active tile, with respect to the canvas origin, for component 'c', in - * the component coordinates. - * */ - public int getCompULX(int c) { - return raster.getMinX(); - } - - /** - * Returns the vertical coordinate of the upper-left corner of the active - * tile, with respect to the canvas origin, in the component coordinates, - * for the specified component. - * - * @param c The index of the component (between 0 and C-1) - * - * @return The vertical coordinate of the upper-left corner of the active - * tile, with respect to the canvas origin, for component 'c', in the - * component coordinates. - * */ - public int getCompULY(int c) { - return raster.getMinY(); - } - - /** - * Returns the horizontal coordinate of the image origin, the top-left - * corner, in the canvas system, on the reference grid. - * - * @return The horizontal coordinate of the image origin in the canvas - * system, on the reference grid. - * */ - public int getImgULX() { - return destinationRegion.x; - } - - /** - * Returns the vertical coordinate of the image origin, the top-left - * corner, in the canvas system, on the reference grid. - * - * @return The vertical coordinate of the image origin in the canvas - * system, on the reference grid. - * */ - public int getImgULY() { - return destinationRegion.y; - } - - /** - * Returns the number of tiles in the horizontal and vertical - * directions. - * - * @param co If not null this object is used to return the information. If - * null a new one is created and returned. - * - * @return The number of tiles in the horizontal (Point.x) and vertical - * (Point.y) directions. - * */ - public Point getNumTiles(Point co) { - if (co != null) { - co.x = getNumXTiles(); - co.y = getNumYTiles(); - return co; - } - else { - return new Point(getNumXTiles(), getNumYTiles()); - } - } - - /** - * Returns the total number of tiles in the image. This default - * implementation assumes no tiling, so 1 is always returned. - * - * @return The total number of tiles in the image. - * */ - public int getNumTiles() { - return getNumXTiles() * getNumYTiles(); - } - - /** - * Returns the number of bits corresponding to the nominal range of the - * data in the specified component. This is the value rb (range bits) that - * was specified in the constructor, which normally is 8 for non bilevel - * data, and 1 for bilevel data. - * - *

If this number is b then the nominal range is between - * -2^(b-1) and 2^(b-1)-1, since unsigned data is level shifted to have a - * nominal avergae of 0. - * - * @param c The index of the component. - * - * @return The number of bits corresponding to the nominal range of the - * data. For floating-point data this value is not applicable and the - * return value is undefined. - * */ - public int getNomRangeBits(int c) { - // Check component index - // XXX: Should be component-dependent. - return rb; - } - - /** - * Returns the position of the fixed point in the specified component - * (i.e. the number of fractional bits), which is always 0 for this - * ImgReader. - * - * @param c The index of the component. - * - * @return The position of the fixed-point (i.e. the number of fractional - * bits). Always 0 for this ImgReader. - * */ - public int getFixedPoint(int c) { - // Check component index - return 0; - } - - - /** - * Returns, in the blk argument, the block of image data containing the - * specifed rectangular area, in the specified component. The data is - * returned, as a reference to the internal data, if any, instead of as a - * copy, therefore the returned data should not be modified. - * - *

After being read the coefficients are level shifted by subtracting - * 2^(nominal bit range - 1) - * - *

The rectangular area to return is specified by the 'ulx', 'uly', 'w' - * and 'h' members of the 'blk' argument, relative to the current - * tile. These members are not modified by this method. The 'offset' and - * 'scanw' of the returned data can be arbitrary. See the 'DataBlk' class. - * - *

If the data array in blk is null, then a new one - * is created if necessary. The implementation of this interface may - * choose to return the same array or a new one, depending on what is more - * efficient. Therefore, the data array in blk prior to the - * method call should not be considered to contain the returned data, a - * new array may have been created. Instead, get the array from - * blk after the method has returned. - * - *

The returned data always has its 'progressive' attribute unset - * (i.e. false). - * - *

When an I/O exception is encountered the JJ2KExceptionHandler is - * used. The exception is passed to its handleException method. The action - * that is taken depends on the action that has been registered in - * JJ2KExceptionHandler. See JJ2KExceptionHandler for details. - * - *

This method implements buffering for the 3 components: When the - * first one is asked, all the 3 components are read and stored until they - * are needed. - * - * @param blk Its coordinates and dimensions specify the area to - * return. Some fields in this object are modified to return the data. - * - * @param c The index of the component from which to get the data. Only 0, - * 1 and 3 are valid. - * - * @return The requested DataBlk - * - * @see #getCompData - * - * @see JJ2KExceptionHandler - */ - public final DataBlk getInternCompData(DataBlk blk, int c) { - if (writer != null && writer.getAbortRequest()) - throw new RuntimeException(J2KImageWriter.WRITE_ABORTED); - - if (barr == null) - barr = new int[nc][]; - - // Check type of block provided as an argument - if(blk.getDataType()!=DataBlk.TYPE_INT){ - if(intBlk==null) - intBlk = new DataBlkInt(blk.ulx,blk.uly,blk.w,blk.h); - else{ - intBlk.ulx = blk.ulx; - intBlk.uly = blk.uly; - intBlk.w = blk.w; - intBlk.h = blk.h; - } - blk = intBlk; - } - - float percentage = - (getTileIdx() + (blk.uly + 1.0F) / blk.h) / getNumTiles(); - writer.processImageProgressWrapper(percentage * 100.0F); - - // If asking a component for the first time for this block, read the 3 - // components - if ((barr[c] == null) || - (dbi.ulx > blk.ulx) || (dbi.uly > blk.uly) || - (dbi.ulx+dbi.w < blk.ulx+blk.w) || - (dbi.uly+dbi.h < blk.uly+blk.h)) { - int k,j,i,mi; - - // Reset data arrays if needed - if (barr[c] == null || barr[c].length < blk.w*blk.h) { - barr[c] = new int[blk.w*blk.h]; - } - blk.setData(barr[c]); - - for (i = (c + 1) % nc; i != c; i = (i + 1) % nc) - if (barr[i] == null || barr[i].length < blk.w*blk.h) { - barr[i] = new int[blk.w*blk.h]; - } - - // set attributes of the DataBlk used for buffering - dbi.ulx = blk.ulx; - dbi.uly = blk.uly; - dbi.w = blk.w; - dbi.h = blk.h; - - // get data from the image - if (aTile == null) { - aTile = getTile(co.x, co.y); - Rectangle temp = aTile.getBounds(); - aTile = aTile.createTranslatedChild(temp.x-minX, - temp.y-minY); - } - - for (i = 0; i < nc ; i++) { - aTile.getSamples(blk.ulx, blk.uly, blk.w, blk.h, i, barr[i]); - for (k = 0; k < barr[i].length; k++) - barr[i][k] -= dcOffset; - } - //getByteData(raster, new Rectangle(blk.ulx, blk.uly, blk.w, blk.h), barr); - - // Set buffer attributes - blk.setData(barr[c]); - blk.offset = 0; - blk.scanw = blk.w; - } else { //Asking for the 2nd or 3rd block component - blk.setData(barr[c]); - blk.offset = (blk.ulx-dbi.ulx)*dbi.w+blk.ulx-dbi.ulx; - blk.scanw = dbi.scanw; - } - - // Turn off the progressive attribute - blk.progressive = false; - return blk; - } - - /** - * Returns, in the blk argument, a block of image data containing the - * specifed rectangular area, in the specified component. The data is - * returned, as a copy of the internal data, therefore the returned data - * can be modified "in place". - * - *

After being read the coefficients are level shifted by subtracting - * 2^(nominal bit range - 1) - * - *

The rectangular area to return is specified by the 'ulx', 'uly', 'w' - * and 'h' members of the 'blk' argument, relative to the current - * tile. These members are not modified by this method. The 'offset' of - * the returned data is 0, and the 'scanw' is the same as the block's - * width. See the 'DataBlk' class. - * - *

If the data array in 'blk' is 'null', then a new one is created. If - * the data array is not 'null' then it is reused, and it must be large - * enough to contain the block's data. Otherwise an 'ArrayStoreException' - * or an 'IndexOutOfBoundsException' is thrown by the Java system. - * - *

The returned data has its 'progressive' attribute unset - * (i.e. false). - * - *

When an I/O exception is encountered the JJ2KExceptionHandler is - * used. The exception is passed to its handleException method. The action - * that is taken depends on the action that has been registered in - * JJ2KExceptionHandler. See JJ2KExceptionHandler for details. - * - * @param blk Its coordinates and dimensions specify the area to - * return. If it contains a non-null data array, then it must have the - * correct dimensions. If it contains a null data array a new one is - * created. The fields in this object are modified to return the data. - * - * @param c The index of the component from which to get the data. Only - * 0,1 and 2 are valid. - * - * @return The requested DataBlk - * - * @see #getInternCompData - * - * @see JJ2KExceptionHandler - * */ - public final DataBlk getCompData(DataBlk blk, int c) { - // NOTE: can not directly call getInterCompData since that returns - // internally buffered data. - int ulx,uly,w,h; - - // Check type of block provided as an argument - if(blk.getDataType()!=DataBlk.TYPE_INT){ - DataBlkInt tmp = new DataBlkInt(blk.ulx,blk.uly,blk.w,blk.h); - blk = tmp; - } - - int bakarr[] = (int[])blk.getData(); - // Save requested block size - ulx = blk.ulx; - uly = blk.uly; - w = blk.w; - h = blk.h; - // Force internal data buffer to be different from external - blk.setData(null); - getInternCompData(blk,c); - // Copy the data - if (bakarr == null) { - bakarr = new int[w*h]; - } - if (blk.offset == 0 && blk.scanw == w) { - // Requested and returned block buffer are the same size - System.arraycopy(blk.getData(),0,bakarr,0,w*h); - } - else { // Requested and returned block are different - for (int i=h-1; i>=0; i--) { // copy line by line - System.arraycopy(blk.getData(),blk.offset+i*blk.scanw, - bakarr,i*w,w); - } - } - blk.setData(bakarr); - blk.offset = 0; - blk.scanw = blk.w; - return blk; - } - - /** - * Returns true if the data read was originally signed in the specified - * component, false if not. This method always returns false since PPM - * data is always unsigned. - * - * @param c The index of the component, from 0 to N-1. - * - * @return always false, since PPM data is always unsigned. - * */ - public boolean isOrigSigned(int c) { - if (isBinary) return true; - - // Check component index - SampleModel sm = null; - if (inputIsRaster) - sm = raster.getSampleModel(); - else - sm = src.getSampleModel(); - - if (sm.getDataType() == DataBuffer.TYPE_USHORT || - sm.getDataType() == DataBuffer.TYPE_BYTE) - return false; - return true; - } - - private int getNumXTiles() { - int x = destinationRegion.x; - int tx = tileXOffset; - int tw = tileWidth; - return ToTile(x + destinationRegion.width - 1, tx, tw) - ToTile(x, tx, tw) + 1; - } - - private int getNumYTiles() { - int y = destinationRegion.y; - int ty = tileYOffset; - int th = tileHeight; - return ToTile(y + destinationRegion.height - 1, ty, th) - ToTile(y, ty, th) + 1; - } - - private static int ToTile(int pos, int tileOffset, int tileSize) { - pos -= tileOffset; - if (pos < 0) { - pos += 1 - tileSize; // force round to -infinity (ceiling) - } - return pos/tileSize; - } - - private Raster getTile(int tileX, int tileY) { - int sx = tileXOffset + tileX * tileWidth; - int sy = tileYOffset + tileY * tileHeight; - tileX += tileXOffset / tileWidth; - tileY += tileYOffset / tileHeight; - - if (inputIsRaster) { - if (noTransform) { - return raster.createChild(sx, sy, getTileWidth(), getTileHeight(), - sx, sy, sourceBands); - } - - WritableRaster ras = - Raster.createWritableRaster(sm, new Point(sx, sy)); - - int x = mapToSourceX(sx); - int y = mapToSourceY(sy); - - int minY = raster.getMinY(); - int maxY = raster.getMinY() + raster.getHeight(); - - int cTileWidth = getTileWidth(); - for (int j = 0; j < getTileHeight(); j++, sy++, y += scaleY) { - if (y < minY || y >= maxY) - continue; - Raster source = raster.createChild(x, y, (cTileWidth - 1) * scaleX + 1, 1, - x, y, null); - int tempX = sx; - for (int i = 0, offset = x; i < cTileWidth; i++, tempX++, offset += scaleX) { - for (int k = 0; k < nc; k++) { - int p = source.getSample(offset, y, sourceBands[k]); - ras.setSample(tempX, sy, k, p); - } - } - } - - return ras; - - } else { - if (noTransform) { - Raster ras = src.getTile(tileX, tileY); - if (noSubband) - return ras; - else { - return ras.createChild(sx, sy, tileWidth, tileHeight, - sx, sy, sourceBands); - } - } - - WritableRaster ras = Raster.createWritableRaster(sm, new Point(sx, sy)); - - int x = mapToSourceX(sx); - int y = mapToSourceY(sy); - - int minY = src.getMinY(); - int maxY = src.getMinY() + src.getHeight(); - int length = tileWidth * scaleX; - - if (x + length >= src.getWidth()) - length = src.getWidth() - x; - int dLength = (length + scaleX -1 ) / scaleX; - - for (int j = 0; j < tileHeight; j++, sy++, y += scaleY) { - if (y < minY || y >= maxY) - continue; - - Raster source = src.getData(new Rectangle(x, y, length, 1)); - - int tempX = sx; - for (int i = 0, offset = x; i < dLength; i++, tempX++, offset += scaleX) { - - for (int k = 0; k < nc; k++) { - int p = source.getSample(offset, y, sourceBands[k]); - - ras.setSample(tempX, sy, k, p); - } - } - } - return ras; - } - } - - private int mapToSourceX(int x) { - return x * scaleX + xOffset; - } - - private int mapToSourceY(int y) { - return y * scaleY + yOffset; - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ResolutionBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ResolutionBox.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ResolutionBox.java 2005-02-11 00:01:37.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/ResolutionBox.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,229 +0,0 @@ -/* - * $RCSfile: ResolutionBox.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:37 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.metadata.IIOMetadataNode; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** This class is defined to represent a Resolution Box of JPEG JP2 - * file format. A Data Entry URL Box has a length, and a fixed type - * of "resc" (capture resolution) or "resd" (default display resolution). - * - * Its contens includes the resolution numerators, denominator, and the - * exponents for both horizontal and vertical directions. - */ -public class ResolutionBox extends Box { - /** The data elements in this box. */ - private short numV; - private short numH; - private short denomV; - private short denomH; - private byte expV; - private byte expH; - - /** The cached horizontal/vertical resolutions. */ - private float hRes; - private float vRes; - - /** Constructs a ResolutionBox from the provided type and - * content data array. - */ - public ResolutionBox(int type, byte[] data) { - super(18, type, data); - } - - /** Constructs a ResolutionBox from the provided type and - * horizontal/vertical resolutions. - */ - public ResolutionBox(int type, float hRes, float vRes) { - super(18, type, null); - this.hRes = hRes; - this.vRes = vRes; - denomH = denomV = 1; - - expV = 0; - if (vRes >= 32768) { - int temp = (int)vRes; - while (temp >= 32768) { - expV++; - temp /= 10; - } - numV = (short)(temp & 0xFFFF); - } else { - numV = (short)vRes; - } - - expH = 0; - if (hRes >= 32768) { - int temp = (int)hRes; - while (temp >= 32768) { - expH++; - temp /= 10; - } - numH = (short)(temp & 0xFFFF); - } else { - numH = (short)hRes; - } - } - - /** Constructs a ResolutionBox based on the provided - * org.w3c.dom.Node. - */ - public ResolutionBox(Node node) throws IIOInvalidTreeException { - super(node); - NodeList children = node.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - String name = child.getNodeName(); - - if ("VerticalResolutionNumerator".equals(name)) { - numV = Box.getShortElementValue(child); - } - - if ("VerticalResolutionDenominator".equals(name)) { - denomV = Box.getShortElementValue(child); - } - - if ("HorizontalResolutionNumerator".equals(name)) { - numH = Box.getShortElementValue(child); - } - - if ("HorizontalResolutionDenominator".equals(name)) { - denomH = Box.getShortElementValue(child); - } - - if ("VerticalResolutionExponent".equals(name)) { - expV = Box.getByteElementValue(child); - } - - if ("HorizontalResolutionExponent".equals(name)) { - expH = Box.getByteElementValue(child); - } - } - } - - /** Return the horizontal resolution. */ - public float getHorizontalResolution() { - return hRes; - } - - /** Return the vertical resolution. */ - public float getVerticalResolution() { - return vRes; - } - - /** Parse the data elements from the provided content data array. */ - protected void parse(byte[] data) { - numV = (short)(((data[0] & 0xFF) << 8) | (data[1] & 0xFF)); - denomV = (short)(((data[2] & 0xFF) << 8) | (data[3] & 0xFF)); - numH = (short)(((data[4] & 0xFF) << 8) | (data[5] & 0xFF)); - denomH = (short)(((data[6] & 0xFF) << 8) | (data[7] & 0xFF)); - expV = data[8]; - expH = data[9]; - vRes = (float)((numV & 0xFFFF) * Math.pow(10, expV) / (denomV & 0xFFFF)); - hRes = (float)((numH & 0xFFFF)* Math.pow(10, expH) / (denomH & 0xFFFF)); - } - - /** Creates an IIOMetadataNode from this resolution - * box. The format of this node is defined in the XML dtd and xsd - * for the JP2 image file. - */ - public IIOMetadataNode getNativeNode() { - IIOMetadataNode node = new IIOMetadataNode(Box.getName(getType())); - setDefaultAttributes(node); - - IIOMetadataNode child = new IIOMetadataNode("VerticalResolutionNumerator"); - child.setUserObject(new Short(numV)); - child.setNodeValue("" + numV); - node.appendChild(child); - - child = new IIOMetadataNode("VerticalResolutionDenominator"); - child.setUserObject(new Short(denomV)); - child.setNodeValue("" + denomV); - node.appendChild(child); - - child = new IIOMetadataNode("HorizontalResolutionNumerator"); - child.setUserObject(new Short(numH)); - child.setNodeValue("" + numH); - node.appendChild(child); - - child = new IIOMetadataNode("HorizontalResolutionDenominator"); - child.setUserObject(new Short(denomH)); - child.setNodeValue("" + denomH); - node.appendChild(child); - - child = new IIOMetadataNode("VerticalResolutionExponent"); - child.setUserObject(new Byte(expV)); - child.setNodeValue("" + expV); - node.appendChild(child); - - child = new IIOMetadataNode("HorizontalResolutionExponent"); - child.setUserObject(new Byte(expH)); - child.setNodeValue("" + expH); - node.appendChild(child); - - return node; - } - - protected void compose() { - if (data != null) - return; - data = new byte[10]; - data[0] = (byte)(numV >> 8); - data[1] = (byte)(numV & 0xFF); - data[2] = (byte)(denomV >> 8); - data[3] = (byte)(denomV & 0xFF); - - data[4] = (byte)(numH >> 8); - data[5] = (byte)(numH & 0xFF); - data[6] = (byte)(denomH >> 8); - data[7] = (byte)(denomH & 0xFF); - - data[8] = expV; - data[9] = expH; - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/SignatureBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/SignatureBox.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/SignatureBox.java 2005-02-11 00:01:37.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/SignatureBox.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,93 +0,0 @@ -/* - * $RCSfile: SignatureBox.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:37 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; -import org.w3c.dom.Node; -import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.metadata.IIOMetadataNode; - -/** This class is defined to represent a Signature Box of JPEG JP2 - * file format. This type of box has a fixed length of 12, a type of "jP " - * and a four byte content of 0x0D0A870A, which is used to detects of the - * common file transmission errors which substitutes with or - * vice versa. - */ -public class SignatureBox extends Box { - /** Constructs a SignatureBox. */ - public SignatureBox() { - super(12, 0x6A502020, null); - } - - /** Constructs a SignatureBox based on the provided - * org.w3c.dom.Node. - */ - public SignatureBox(Node node) throws IIOInvalidTreeException { - super(node); - } - - /** Constructs a SignatureBox based on the provided - * byte array. - */ - public SignatureBox(byte[] data) throws IIOInvalidTreeException { - super(12, 0x6A502020, data); - } - - /** Creates an IIOMetadataNode from this signature - * box. The format of this node is defined in the XML dtd and xsd - * for the JP2 image file. - */ - public IIOMetadataNode getNativeNode() { - IIOMetadataNode node = new IIOMetadataNode(Box.getName(getType())); - setDefaultAttributes(node); - node.setAttribute("Signature", Integer.toString(0x0D0A870A)); - return node; - } - - protected void compose() { - if (data != null) - return; - data = new byte[]{(byte)0x0D, (byte)0x0A, (byte)0x87, (byte)0x0A}; - } -} - diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/UUIDBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/UUIDBox.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/UUIDBox.java 2005-02-11 00:01:37.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/UUIDBox.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,130 +0,0 @@ -/* - * $RCSfile: UUIDBox.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:37 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.metadata.IIOMetadataNode; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** This class is defined to represent a UUID Box of JPEG JP2 - * file format. This type of box has a length, a type of "uuid". Its - * content is a 16-byte UUID followed with a various-length data. - */ -public class UUIDBox extends Box { - /** Cache the element names for this box's xml definition */ - private static String[] elementNames = {"UUID", "Data"}; - - /** This method will be called by the getNativeNodeForSimpleBox of the - * class Box to get the element names. - */ - public static String[] getElementNames() { - return elementNames; - } - - /** The data elements in this UUID box. */ - private byte[] uuid; - private byte[] udata; - - /** Constructs a UUIDBox from its content data array. */ - public UUIDBox(byte[] data) { - super(8 + data.length, 0x75756964, data); - } - - /** Constructs a UUIDBox based on the provided - * org.w3c.dom.Node. - */ - public UUIDBox(Node node) throws IIOInvalidTreeException { - super(node); - NodeList children = node.getChildNodes(); - - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - String name = child.getNodeName(); - - if ("UUID".equals(name)) { - uuid = Box.getByteArrayElementValue(child); - } - - if ("Data".equals(name)) { - udata = Box.getByteArrayElementValue(child); - } - } - } - - /** Parses the data elements from the provided data array. */ - protected void parse(byte[] data) { - uuid = new byte[16]; - System.arraycopy(data, 0, uuid, 0, 16); - udata = new byte[data.length - 16]; - System.arraycopy(data, 16, udata, 0, udata.length); - } - - /** Returns the UUID of this box. */ - public byte[] getUUID() { - return uuid; - } - - /** Returns the UUID data of this box. */ - public byte[] getData() { - return udata; - } - - /** Creates an IIOMetadataNode from this UUID - * box. The format of this node is defined in the XML dtd and xsd - * for the JP2 image file. - */ - public IIOMetadataNode getNativeNode() { - return getNativeNodeForSimpleBox(); - } - - protected void compose() { - if (data != null) - return; - data = new byte[16 + udata.length]; - System.arraycopy(uuid, 0, data, 0, 16); - System.arraycopy(udata, 0, data, 16, udata.length); - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/UUIDListBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/UUIDListBox.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/UUIDListBox.java 2006-10-10 19:48:57.000000000 -0400 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/UUIDListBox.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,157 +0,0 @@ -/* - * $RCSfile: UUIDListBox.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.2 $ - * $Date: 2006/10/10 23:48:57 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.metadata.IIOMetadataNode; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import com.sun.media.imageioimpl.common.ImageUtil; - -/** This class is defined to represent a UUID list Box of JPEG JP2 - * file format. This type of box has a length, a type of "ulst". Its - * contents include the number of UUID entry and a list of 16-byte UUIDs. - */ -public class UUIDListBox extends Box { - /** The data elements of this box. */ - private short num; - private byte[][] uuids; - - /** Constructs a UUIDListBox from the provided uuid number - * and uuids. The provided uuids should have a size of 16; otherwise, - * Exception may thrown in later the process. The provided - * number should consistent with the size of the uuid array. - */ - public UUIDListBox(short num, byte[][] uuids) { - super(10 + (uuids.length << 4), 0x756c7374, null); - this.num = num; - this.uuids = uuids; - } - - /** Constructs a UUIDListBox from the provided content - * data array. - */ - public UUIDListBox(byte[] data) { - super(8 + data.length, 0x756c7374, data); - } - - /** Constructs a UUIDListBox based on the provided - * org.w3c.dom.Node. - */ - public UUIDListBox(Node node) throws IIOInvalidTreeException { - super(node); - NodeList children = node.getChildNodes(); - int index = 0; - - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - - if ("NumberUUID".equals(child.getNodeName())) { - num = (short)Box.getShortElementValue(child); - uuids = new byte[num][]; - } - - } - - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - - if ("UUID".equals(child.getNodeName()) && index < num) { - uuids[index++] = Box.getByteArrayElementValue(child); - } - } - } - - /** Parses the data elements from the provided content data array. */ - protected void parse(byte[] data) { - num = (short)(((data[0] & 0xFF) << 8) | (data[1] & 0xFF)); - - uuids = new byte[num][]; - int pos = 2; - for (int i = 0; i < num; i++) { - uuids[i] = new byte[16]; - System.arraycopy(data, pos, uuids[i], 0, 16); - pos += 16; - } - } - - /** Creates an IIOMetadataNode from this UUID list - * box. The format of this node is defined in the XML dtd and xsd - * for the JP2 image file. - */ - public IIOMetadataNode getNativeNode() { - IIOMetadataNode node = new IIOMetadataNode(Box.getName(getType())); - setDefaultAttributes(node); - - IIOMetadataNode child = new IIOMetadataNode("NumberUUID"); - child.setUserObject(new Short(num)); - child.setNodeValue("" + num); - node.appendChild(child); - - for (int i = 0; i < num; i++) { - child = new IIOMetadataNode("UUID"); - child.setUserObject(uuids[i]); - child.setNodeValue(ImageUtil.convertObjectToString(uuids[i])); - node.appendChild(child); - } - - return node; - } - - protected void compose() { - if (data != null) - return; - data = new byte[2 + num * 16]; - - data[0] = (byte)(num >> 8); - data[1] = (byte)(num & 0xFF); - - for (int i = 0, pos = 2; i < num; i++) { - System.arraycopy(uuids[i], 0, data, pos, 16); - pos += 16; - } - } -} diff -urN jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/XMLBox.java zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/XMLBox.java --- jai-imageio-core-cvs20091111-CLEANED/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/XMLBox.java 2005-02-11 00:01:37.000000000 -0500 +++ zzx2/src/share/classes/com/sun/media/imageioimpl/plugins/jpeg2000/XMLBox.java 1969-12-31 19:00:00.000000000 -0500 @@ -1,116 +0,0 @@ -/* - * $RCSfile: XMLBox.java,v $ - * - * - * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistribution of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any - * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND - * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY - * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL - * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF - * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS - * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR - * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, - * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND - * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR - * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that this software is not designed or intended for - * use in the design, construction, operation or maintenance of any - * nuclear facility. - * - * $Revision: 1.1 $ - * $Date: 2005/02/11 05:01:37 $ - * $State: Exp $ - */ -package com.sun.media.imageioimpl.plugins.jpeg2000; - -import javax.imageio.metadata.IIOInvalidTreeException; -import javax.imageio.metadata.IIOMetadataNode; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** This class is defined to represent a XML box of JPEG JP2 - * file format. This type of box has a length, a type of "xml ". Its - * content is a text string of a XML instance. - */ -public class XMLBox extends Box { - /** Cache the element names for this box's xml definition */ - private static String[] elementNames = {"Content"}; - - /** This method will be called by the getNativeNodeForSimpleBox of the - * class Box to get the element names. - */ - public static String[] getElementNames() { - return elementNames; - } - - /** Create a Box from its content. */ - public XMLBox(byte[] data) { - super(8 + data.length, 0x786D6C20, data); - } - - /** Constructs a UUIDListBox based on the provided - * org.w3c.dom.Node. - */ - public XMLBox(Node node) throws IIOInvalidTreeException { - super(node); - NodeList children = node.getChildNodes(); - - for (int i = 0; i < children.getLength(); i++) { - Node child = children.item(i); - String name = child.getNodeName(); - - if ("Content".equals(name)) { - String value = child.getNodeValue(); - if (value != null) - data = value.getBytes(); - else if (child instanceof IIOMetadataNode) { - value = (String)((IIOMetadataNode)child).getUserObject(); - if (value != null) - data = value.getBytes(); - } - } - } - } - - /** Creates an IIOMetadataNode from this XML - * box. The format of this node is defined in the XML dtd and xsd - * for the JP2 image file. - */ - public IIOMetadataNode getNativeNode() { - try { - IIOMetadataNode node = new IIOMetadataNode(Box.getName(getType())); - setDefaultAttributes(node); - IIOMetadataNode child = new IIOMetadataNode("Content"); - String value = null; - if (data != null) - value = new String(data); - child.setUserObject(value); - child.setNodeValue(value); - node.appendChild(child); - return node; - } catch (Exception e) { - throw new IllegalArgumentException(I18N.getString("Box0")); - } - } -}