#489 Fix for Unexpected End of PackBits Stream for padded streams.

This commit is contained in:
Harald Kuhr 2019-08-07 16:04:46 +02:00
parent e8d1b999a2
commit f6aa810f8b

View File

@ -1,210 +1,186 @@
/* /*
* Copyright (c) 2008, Harald Kuhr * Copyright (c) 2008, Harald Kuhr
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* *
* * Redistributions of source code must retain the above copyright notice, this * * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. * list of conditions and the following disclaimer.
* *
* * Redistributions in binary form must reproduce the above copyright notice, * * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation * this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution. * and/or other materials provided with the distribution.
* *
* * Neither the name of the copyright holder nor the names of its * * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from * contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. * this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
package com.twelvemonkeys.io.enc; package com.twelvemonkeys.io.enc;
import java.io.EOFException; import java.io.EOFException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
/** /**
* Decoder implementation for Apple PackBits run-length encoding. * Decoder implementation for Apple PackBits run-length encoding.
* <p/> * <p/>
* <small>From Wikipedia, the free encyclopedia</small><br/> * <small>From Wikipedia, the free encyclopedia</small><br/>
* PackBits is a fast, simple compression scheme for run-length encoding of * PackBits is a fast, simple compression scheme for run-length encoding of
* data. * data.
* <p/> * <p/>
* Apple introduced the PackBits format with the release of MacPaint on the * Apple introduced the PackBits format with the release of MacPaint on the
* Macintosh computer. This compression scheme is one of the types of * Macintosh computer. This compression scheme is one of the types of
* compression that can be used in TIFF-files. * compression that can be used in TIFF-files.
* <p/> * <p/>
* A PackBits data stream consists of packets of one byte of header followed by * A PackBits data stream consists of packets of one byte of header followed by
* data. The header is a signed byte; the data can be signed, unsigned, or * data. The header is a signed byte; the data can be signed, unsigned, or
* packed (such as MacPaint pixels). * packed (such as MacPaint pixels).
* <p/> * <p/>
* <table><tr><th>Header byte</th><th>Data</th></tr> * <table><tr><th>Header byte</th><th>Data</th></tr>
* <tr><td>0 to 127</td> <td>1 + <i>n</i> literal bytes of data</td></tr> * <tr><td>0 to 127</td> <td>1 + <i>n</i> literal bytes of data</td></tr>
* <tr><td>0 to -127</td> <td>One byte of data, repeated 1 - <i>n</i> times in * <tr><td>0 to -127</td> <td>One byte of data, repeated 1 - <i>n</i> times in
* the decompressed output</td></tr> * the decompressed output</td></tr>
* <tr><td>-128</td> <td>No operation</td></tr></table> * <tr><td>-128</td> <td>No operation</td></tr></table>
* <p/> * <p/>
* Note that interpreting 0 as positive or negative makes no difference in the * Note that interpreting 0 as positive or negative makes no difference in the
* output. Runs of two bytes adjacent to non-runs are typically written as * output. Runs of two bytes adjacent to non-runs are typically written as
* literal data. * literal data.
* <p/> * <p/>
* See <a href="http://developer.apple.com/technotes/tn/tn1023.html">Understanding PackBits</a> * See <a href="http://developer.apple.com/technotes/tn/tn1023.html">Understanding PackBits</a>
* *
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a> * @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/io/enc/PackBitsDecoder.java#1 $ * @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/io/enc/PackBitsDecoder.java#1 $
*/ */
public final class PackBitsDecoder implements Decoder { public final class PackBitsDecoder implements Decoder {
// TODO: Look at ICNSImageReader#unpackbits... What is this weirdness? // TODO: Look at ICNSImageReader#unpackbits... What is this weirdness?
private final boolean disableNoOp; private final boolean disableNoOp;
private final byte[] sample; private final byte[] sample;
private int leftOfRun; private boolean reachedEOF;
private boolean splitRun;
private boolean reachedEOF; /** Creates a {@code PackBitsDecoder}. */
public PackBitsDecoder() {
/** Creates a {@code PackBitsDecoder}. */ this(1, false);
public PackBitsDecoder() { }
this(1, false);
} /**
* Creates a {@code PackBitsDecoder}, with optional compatibility mode.
/** * <p/>
* Creates a {@code PackBitsDecoder}, with optional compatibility mode. * As some implementations of PackBits-like encoders treat {@code -128} as length of
* <p/> * a compressed run, instead of a no-op, it's possible to disable no-ops for compatibility.
* As some implementations of PackBits-like encoders treat {@code -128} as length of * Should be used with caution, even though, most known encoders never write no-ops in the compressed streams.
* a compressed run, instead of a no-op, it's possible to disable no-ops for compatibility. *
* Should be used with caution, even though, most known encoders never write no-ops in the compressed streams. * @param disableNoOp {@code true} if {@code -128} should be treated as a compressed run, and not a no-op
* */
* @param disableNoOp {@code true} if {@code -128} should be treated as a compressed run, and not a no-op public PackBitsDecoder(final boolean disableNoOp) {
*/ this(1, disableNoOp);
public PackBitsDecoder(final boolean disableNoOp) { }
this(1, disableNoOp);
} /**
* Creates a {@code PackBitsDecoder}, with optional compatibility mode.
/** * <p/>
* Creates a {@code PackBitsDecoder}, with optional compatibility mode. * As some implementations of PackBits-like encoders treat {@code -128} as length of
* <p/> * a compressed run, instead of a no-op, it's possible to disable no-ops for compatibility.
* As some implementations of PackBits-like encoders treat {@code -128} as length of * Should be used with caution, even though, most known encoders never write no-ops in the compressed streams.
* a compressed run, instead of a no-op, it's possible to disable no-ops for compatibility. *
* Should be used with caution, even though, most known encoders never write no-ops in the compressed streams. * @param disableNoOp {@code true} if {@code -128} should be treated as a compressed run, and not a no-op
* */
* @param disableNoOp {@code true} if {@code -128} should be treated as a compressed run, and not a no-op public PackBitsDecoder(int sampleSize, final boolean disableNoOp) {
*/ this.sample = new byte[sampleSize];
public PackBitsDecoder(int sampleSize, final boolean disableNoOp) { this.disableNoOp = disableNoOp;
this.sample = new byte[sampleSize]; }
this.disableNoOp = disableNoOp;
} /**
* Decodes bytes from the given input stream, to the given buffer.
/** *
* Decodes bytes from the given input stream, to the given buffer. * @param stream the stream to decode from
* * @param buffer a byte array, minimum 128 (or 129 if no-op is disabled) bytes long
* @param stream the stream to decode from * @return The number of bytes decoded
* @param buffer a byte array, minimum 128 (or 129 if no-op is disabled) bytes long *
* @return The number of bytes decoded * @throws java.io.IOException if a problem occurs during decoding.
* */
* @throws java.io.IOException public int decode(final InputStream stream, final ByteBuffer buffer) throws IOException {
*/ if (reachedEOF) {
public int decode(final InputStream stream, final ByteBuffer buffer) throws IOException { return -1;
if (reachedEOF) { }
return -1;
} // NOTE: We don't decode more than single runs, because some writers add pad bytes inside the stream...
// Start new run
// TODO: Don't decode more than single runs, because some writers add pad bytes inside the stream... int b = stream.read();
while (buffer.hasRemaining()) { if (b < 0) {
int n; reachedEOF = true;
return 0;
if (splitRun) { }
// Continue run
n = leftOfRun; int n = (byte) b;
splitRun = false;
} try {
else { if (n >= 0) {
// Start new run // Copy next n + 1 bytes literally
int b = stream.read(); readFully(stream, buffer, sample.length * (n + 1));
if (b < 0) { }
reachedEOF = true; // Allow -128 for compatibility, see above
break; else if (disableNoOp || n != -128) {
} // Replicate the next byte -n + 1 times
n = (byte) b; for (int s = 0; s < sample.length; s++) {
} sample[s] = readByte(stream);
}
// Split run at or before max
if (n >= 0 && n + 1 > buffer.remaining()) { for (int i = -n + 1; i > 0; i--) {
leftOfRun = n; buffer.put(sample);
splitRun = true; }
break; }
} // else NOOP (-128)
else if (n < 0 && -n + 1 > buffer.remaining()) { }
leftOfRun = n; catch (IndexOutOfBoundsException e) {
splitRun = true; throw new DecodeException("Error in PackBits decompression, data seems corrupt", e);
break; }
}
return buffer.position();
try { }
if (n >= 0) {
// Copy next n + 1 bytes literally static byte readByte(final InputStream pStream) throws IOException {
readFully(stream, buffer, sample.length * (n + 1)); int read = pStream.read();
}
// Allow -128 for compatibility, see above if (read < 0) {
else if (disableNoOp || n != -128) { throw new EOFException("Unexpected end of PackBits stream");
// Replicate the next byte -n + 1 times }
for (int s = 0; s < sample.length; s++) {
sample[s] = readByte(stream); return (byte) read;
} }
for (int i = -n + 1; i > 0; i--) { static void readFully(final InputStream pStream, final ByteBuffer pBuffer, final int pLength) throws IOException {
buffer.put(sample); if (pLength < 0) {
} throw new IndexOutOfBoundsException(String.format("Negative length: %d", pLength));
} }
// else NOOP (-128)
} int total = 0;
catch (IndexOutOfBoundsException e) {
throw new DecodeException("Error in PackBits decompression, data seems corrupt", e); while (total < pLength) {
} int count = pStream.read(pBuffer.array(), pBuffer.arrayOffset() + pBuffer.position() + total, pLength - total);
}
if (count < 0) {
return buffer.position(); throw new EOFException("Unexpected end of PackBits stream");
} }
static byte readByte(final InputStream pStream) throws IOException { total += count;
int read = pStream.read(); }
if (read < 0) { pBuffer.position(pBuffer.position() + total);
throw new EOFException("Unexpected end of PackBits stream"); }
} }
return (byte) read;
}
static void readFully(final InputStream pStream, final ByteBuffer pBuffer, final int pLength) throws IOException {
if (pLength < 0) {
throw new IndexOutOfBoundsException(String.format("Negative length: %d", pLength));
}
int total = 0;
while (total < pLength) {
int count = pStream.read(pBuffer.array(), pBuffer.arrayOffset() + pBuffer.position() + total, pLength - total);
if (count < 0) {
throw new EOFException("Unexpected end of PackBits stream");
}
total += count;
}
pBuffer.position(pBuffer.position() + total);
}
}