Search in sources :

Example 1 with KduException

use of kdu_jni.KduException in project imageio-ext by geosolutions-it.

the class LazyJP2KBox method clone.

@Override
public Object clone() {
    // LazyJP2KBox newBox = (LazyJP2KBox)super.clone();
    Jp2_locator locator = new Jp2_locator();
    try {
        final long filePos = this.locator.Get_file_pos();
        locator.Set_file_pos(filePos);
        // return newBox;
        return new LazyJP2KBox(filename, type, locator);
    } catch (KduException e) {
        throw new RuntimeException("Error caused by a Kakadu exception during Box management! ", e);
    }
}
Also used : KduException(kdu_jni.KduException) Jp2_locator(kdu_jni.Jp2_locator)

Example 2 with KduException

use of kdu_jni.KduException in project imageio-ext by geosolutions-it.

the class JP2KFileWalker method init.

/**
 * Parses this file into a {@link TreeModel} object.
 */
private void init() {
    if (this.initialized)
        return;
    // //
    // 
    // create needed kakadu machinery
    // 
    // //
    familySource = new Jp2_family_src();
    final Jp2_input_box inputBox = new Jp2_input_box();
    final Jp2_locator locator = new Jp2_locator();
    List<? extends Throwable> exceptions = Collections.emptyList();
    try {
        // open the family
        familySource.Open(fileName);
        // create the needed objects
        final JP2KFileBox box = new JP2KFileBox();
        this.tree = new DefaultTreeModel(box);
        // Add a listener: a new instance of a JP2KTreeController on the tree
        final JP2KTreeController controller = new JP2KTreeController(this.tree);
        this.tree.addTreeModelListener(controller);
        // recursive parsing
        if (inputBox.Open(familySource, locator)) {
            parse(inputBox, box, 0);
        }
        controller.checkTreeConsistency();
        // clean up
        inputBox.Close();
    } catch (KduException e) {
        throw new RuntimeException("Error caused by a Kakadu exception during Box management! ", e);
    } finally {
        // clean up
        try {
            familySource.Close();
        } catch (Exception e) {
            if (LOGGER.isLoggable(Level.FINEST))
                LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
        }
        try {
            if (inputBox != null)
                inputBox.Close();
        } catch (Exception e) {
            if (LOGGER.isLoggable(Level.FINEST))
                LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
        }
    }
    if (!exceptions.isEmpty()) {
        // TODO Create a specific exception that wraps them all!
        throw new IllegalStateException("Tree Check failed");
    }
}
Also used : KduException(kdu_jni.KduException) Jp2_input_box(kdu_jni.Jp2_input_box) Jp2_locator(kdu_jni.Jp2_locator) JP2KFileBox(it.geosolutions.imageio.plugins.jp2k.box.JP2KFileBox) DefaultTreeModel(javax.swing.tree.DefaultTreeModel) Jp2_family_src(kdu_jni.Jp2_family_src) KduException(kdu_jni.KduException)

Example 3 with KduException

use of kdu_jni.KduException in project imageio-ext by geosolutions-it.

the class JP2KFileWalker method parse.

/**
 * Parses this box, his brothers as well as his children recursively.
 *
 * @param inputBox
 *                the box to begin the parsing with.
 * @param parent
 *                the parent box to which attach this box as well as its
 *                brothers.
 * @param index
 *                the index at which this box should be attached in his
 *                father's children list.
 * @throws KduException
 *                 in case any problem with the low level machinery happens.
 */
private void parse(final Jp2_input_box inputBox, final JP2KBox parent, int index) throws KduException {
    final Jp2_input_box childBox = new Jp2_input_box();
    try {
        // //
        // 
        // get the info for this box
        // 
        // //
        final int boxtype = (int) (0xffffffff & inputBox.Get_box_type());
        final String typeString = BoxUtilities.getTypeString(boxtype);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine("Found box " + typeString);
        }
        LazyJP2KBox currentBox = null;
        // //
        if (BoxUtilities.boxNames.containsKey(boxtype)) {
            final Jp2_locator locator = inputBox.Get_locator();
            // created a lazily loaded box
            currentBox = new LazyJP2KBox(this.fileName, boxtype, locator);
            parent.insert(currentBox, index++);
            this.tree.nodesWereInserted(parent, new int[] { index - 1 });
        } else {
            if (LOGGER.isLoggable(Level.INFO)) {
                LOGGER.info("Box of type " + typeString + " cannot be handled by this file type reader");
            }
        }
        // reopen box
        if (BoxUtilities.SUPERBOX_NAMES.contains(typeString)) {
            if (childBox.Open(inputBox)) {
                if (childBox.Exists()) {
                    parse(childBox, currentBox, 0);
                }
                // close box
                childBox.Close();
            }
        }
        // //
        // 
        // check next
        // 
        // //
        // close box
        inputBox.Close();
        if (inputBox.Open_next()) {
            if (inputBox.Exists()) {
                parse(inputBox, parent, index);
            }
        }
    } catch (KduException e) {
        throw new RuntimeException("Error caused by a Kakadu exception during Box management! ", e);
    } finally {
        // clean up
        try {
            if (childBox != null)
                childBox.Close();
        } catch (Exception e) {
            if (LOGGER.isLoggable(Level.FINEST))
                LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
        }
        try {
            if (inputBox != null)
                inputBox.Close();
        } catch (Exception e) {
            if (LOGGER.isLoggable(Level.FINEST))
                LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
        }
    }
}
Also used : KduException(kdu_jni.KduException) Jp2_input_box(kdu_jni.Jp2_input_box) Jp2_locator(kdu_jni.Jp2_locator) KduException(kdu_jni.KduException)

Example 4 with KduException

use of kdu_jni.KduException in project imageio-ext by geosolutions-it.

the class JP2KKakaduImageReader method getImageTypes.

/**
 * Returns an <code>Iterator</code> containing possible image types to
 * which the given image may be decoded, in the form of
 * <code>ImageTypeSpecifiers</code>s. At least one legal image type will
 * be returned. This implementation simply returns an
 * <code>ImageTypeSpecifier</code> set in compliance with the property of
 * the dataset contained within the underlying data source.
 *
 * @param imageIndex
 *                the index of the image to be retrieved.
 *
 * @return an <code>Iterator</code> containing possible image types to
 *         which the given image may be decoded, in the form of
 *         <code>ImageTypeSpecifiers</code>s
 * @see javax.imageio.ImageReader#getImageTypes(int)
 */
public Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex) throws IOException {
    checkImageIndex(imageIndex);
    final List<ImageTypeSpecifier> l = new java.util.ArrayList<ImageTypeSpecifier>();
    final JP2KCodestreamProperties codestreamP = multipleCodestreams.get(imageIndex);
    // Setting SampleModel and ColorModel for the whole image
    if (codestreamP.getColorModel() == null || codestreamP.getSampleModel() == null) {
        try {
            initializeSampleModelAndColorModel(codestreamP);
        } catch (KduException kdue) {
            throw new RuntimeException("Error while setting sample and color model", kdue);
        }
    }
    final ImageTypeSpecifier imageType = new ImageTypeSpecifier(codestreamP.getColorModel(), codestreamP.getSampleModel());
    l.add(imageType);
    return l.iterator();
}
Also used : KduException(kdu_jni.KduException) ArrayList(java.util.ArrayList) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier)

Example 5 with KduException

use of kdu_jni.KduException in project imageio-ext by geosolutions-it.

the class JP2KKakaduImageReader method setInput.

public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) {
    // //
    // 
    // Reset the reader prior to do anything with it
    // 
    // //
    reset();
    // //
    if (input == null)
        throw new NullPointerException("The provided input is null!");
    // Checking if the provided input is a File
    if (input instanceof File) {
        inputFile = (File) input;
    // Checking if the provided input is a FileImageInputStreamExt
    } else if (input instanceof FileImageInputStreamExt) {
        inputFile = ((FileImageInputStreamExt) input).getFile();
    // Checking if the provided input is a URL
    } else if (input instanceof URL) {
        final URL tempURL = (URL) input;
        if (tempURL.getProtocol().equalsIgnoreCase("file")) {
            inputFile = Utilities.urlToFile(tempURL);
        }
    } else if (input instanceof ImageInputStream) {
        try {
            inputFile = File.createTempFile("buffer", ".j2c");
            FileOutputStream fos = new FileOutputStream(inputFile);
            final byte[] buff = new byte[TEMP_BUFFER_SIZE];
            int bytesRead = 0;
            while ((bytesRead = ((ImageInputStream) input).read(buff)) != -1) fos.write(buff, 0, bytesRead);
            fos.close();
            input = inputFile;
            deleteInputFile = true;
        } catch (IOException ioe) {
            throw new RuntimeException("Unable to create a temp file", ioe);
        }
    }
    if (this.inputFile == null)
        throw new IllegalArgumentException("Invalid source provided.");
    fileName = inputFile.getAbsolutePath();
    // //
    // 
    // Open it up
    // 
    // //
    // Must be disposed last
    Kdu_simple_file_source rawSource = null;
    // Dispose
    final Jp2_family_src familySource = new Jp2_family_src();
    // last
    // Dispose in the
    final Jpx_source wrappedSource = new Jpx_source();
    // middle
    Kdu_codestream codestream = new Kdu_codestream();
    try {
        // Open input file as raw codestream or a JP2/JPX file
        familySource.Open(fileName);
        final int success = wrappedSource.Open(familySource, true);
        if (success < 0) {
            // //
            // 
            // Must open as raw file
            // 
            // //
            familySource.Close();
            wrappedSource.Close();
            rawSource = new Kdu_simple_file_source(fileName);
            if (rawSource != null) {
                if (fileName != null) {
                    FileInputStream fis = new FileInputStream(new File(fileName));
                    byte[] jp2SocMarker = new byte[2];
                    fis.read(jp2SocMarker);
                    if (jp2SocMarker[0] != (byte) 0xFF || jp2SocMarker[1] != (byte) 0x4F)
                        throw new IllegalArgumentException("Not a JP2K source.");
                    fis.close();
                }
                isRawSource = true;
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.fine("Detected raw source");
                numImages = 1;
            }
        } else {
            // we have a valid jp2/jpx file
            isRawSource = false;
            // //
            // 
            // get the number of codestreams in this jpeg2000 file
            // 
            // //
            final int[] count = new int[1];
            if (wrappedSource.Count_codestreams(count))
                numImages = count[0];
            else
                numImages = 0;
        }
        if (!isRawSource)
            fileWalker = new JP2KFileWalker(this.fileName);
        for (int cs = 0; cs < numImages; cs++) {
            if (isRawSource) {
                codestream.Create(rawSource);
            } else {
                final Jpx_codestream_source stream = wrappedSource.Access_codestream(cs);
                final Jpx_input_box inputbox = stream.Open_stream();
                codestream.Create(inputbox);
            }
            final JP2KCodestreamProperties codestreamP = new JP2KCodestreamProperties();
            // //
            // 
            // Initializing size-related properties (Image dims, Tiles)
            // 
            // //
            final Kdu_dims imageDims = new Kdu_dims();
            codestream.Access_siz().Finalize_all();
            codestream.Get_dims(-1, imageDims, false);
            final Kdu_dims tileSize = new Kdu_dims();
            codestream.Get_tile_dims(new Kdu_coords(0, 0), -1, tileSize);
            int tileWidth = tileSize.Access_size().Get_x();
            int tileHeight = tileSize.Access_size().Get_y();
            // maximum integer
            if ((float) tileWidth * tileHeight >= Integer.MAX_VALUE) {
                // TODO: Customize these settings
                tileHeight = 1024;
                tileWidth = 1024;
            }
            codestreamP.setTileWidth(tileWidth);
            codestreamP.setTileHeight(tileHeight);
            codestreamP.setWidth(imageDims.Access_size().Get_x());
            codestreamP.setHeight(imageDims.Access_size().Get_y());
            final int nComponents = codestream.Get_num_components();
            int maxBitDepth = -1;
            int[] componentIndexes = new int[nComponents];
            int[] bitsPerComponent = new int[nComponents];
            boolean isSigned = false;
            for (int i = 0; i < nComponents; i++) {
                // TODO: FIX THIS
                bitsPerComponent[i] = codestream.Get_bit_depth(i);
                if (maxBitDepth < bitsPerComponent[i]) {
                    maxBitDepth = bitsPerComponent[i];
                }
                isSigned |= codestream.Get_signed(i);
                componentIndexes[i] = i;
            }
            codestreamP.setNumComponents(nComponents);
            codestreamP.setBitsPerComponent(bitsPerComponent);
            codestreamP.setComponentIndexes(componentIndexes);
            codestreamP.setMaxBitDepth(maxBitDepth);
            codestreamP.setSigned(isSigned);
            // Initializing Resolution levels and Quality Layers
            final int sourceDWTLevels = codestream.Get_min_dwt_levels();
            codestreamP.setSourceDWTLevels(sourceDWTLevels);
            codestreamP.setMaxSupportedSubSamplingFactor(1 << sourceDWTLevels);
            Kdu_coords tileCoords = new Kdu_coords();
            tileCoords.Set_x(0);
            tileCoords.Set_y(0);
            codestream.Open_tile(tileCoords);
            codestreamP.setMaxAvailableQualityLayers(codestream.Get_max_tile_layers());
            initializeSampleModelAndColorModel(codestreamP);
            codestream.Destroy();
            multipleCodestreams.add(codestreamP);
            if (isRawSource)
                break;
        }
    } catch (KduException e) {
        throw new RuntimeException("Error caused by a Kakadu exception during creation of key objects!", e);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Exception occurred during kakadu reader initialization", e);
    } catch (IOException e) {
        throw new RuntimeException("Exception occurred during kakadu reader initialization", e);
    } finally {
        if (!isRawSource && wrappedSource != null) {
            try {
                if (wrappedSource.Exists())
                    wrappedSource.Close();
            } catch (Throwable e) {
            // yeah I am eating this
            }
            try {
                wrappedSource.Native_destroy();
            } catch (Throwable e) {
            // yeah I am eating this
            }
            if (familySource != null) {
                try {
                    if (familySource.Exists())
                        familySource.Close();
                } catch (Throwable e) {
                // yeah I am eating this
                }
                try {
                    familySource.Native_destroy();
                } catch (Throwable e) {
                // yeah I am eating this
                }
            }
        } else if (isRawSource && rawSource != null) {
            try {
                if (wrappedSource.Exists())
                    wrappedSource.Close();
            } catch (Throwable e) {
            // yeah I am eating this
            }
        }
    }
    // //
    // 
    // Setting input for superclass
    // 
    // //
    super.setInput(input, seekForwardOnly, ignoreMetadata);
}
Also used : FileNotFoundException(java.io.FileNotFoundException) URL(java.net.URL) Jpx_source(kdu_jni.Jpx_source) Kdu_dims(kdu_jni.Kdu_dims) FileImageInputStreamExt(it.geosolutions.imageio.stream.input.FileImageInputStreamExt) Kdu_codestream(kdu_jni.Kdu_codestream) KduException(kdu_jni.KduException) Kdu_simple_file_source(kdu_jni.Kdu_simple_file_source) Jpx_codestream_source(kdu_jni.Jpx_codestream_source) ImageInputStream(javax.imageio.stream.ImageInputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FileOutputStream(java.io.FileOutputStream) Kdu_coords(kdu_jni.Kdu_coords) Jpx_input_box(kdu_jni.Jpx_input_box) Jp2_family_src(kdu_jni.Jp2_family_src) File(java.io.File)

Aggregations

KduException (kdu_jni.KduException)10 Jp2_family_src (kdu_jni.Jp2_family_src)5 Jp2_input_box (kdu_jni.Jp2_input_box)3 Jp2_locator (kdu_jni.Jp2_locator)3 Jpx_source (kdu_jni.Jpx_source)3 Kdu_codestream (kdu_jni.Kdu_codestream)3 Kdu_simple_file_source (kdu_jni.Kdu_simple_file_source)3 FileImageInputStreamExt (it.geosolutions.imageio.stream.input.FileImageInputStreamExt)2 Rectangle (java.awt.Rectangle)2 ColorModel (java.awt.image.ColorModel)2 IndexColorModel (java.awt.image.IndexColorModel)2 SampleModel (java.awt.image.SampleModel)2 File (java.io.File)2 FileInputStream (java.io.FileInputStream)2 IOException (java.io.IOException)2 URL (java.net.URL)2 Jpx_codestream_source (kdu_jni.Jpx_codestream_source)2 Jpx_input_box (kdu_jni.Jpx_input_box)2 Kdu_dims (kdu_jni.Kdu_dims)2 Compression (it.geosolutions.imageio.plugins.jp2k.JP2KKakaduImageWriteParam.Compression)1