001 /*
002 * Copyright (c) Andrey Kuznetsov. All Rights Reserved.
003 *
004 * http://uio.imagero.com
005 *
006 * Redistribution and use in source and binary forms, with or without
007 * modification, are permitted provided that the following conditions are met:
008 *
009 * o Redistributions of source code must retain the above copyright notice,
010 * this list of conditions and the following disclaimer.
011 *
012 * o Redistributions in binary form must reproduce the above copyright notice,
013 * this list of conditions and the following disclaimer in the documentation
014 * and/or other materials provided with the distribution.
015 *
016 * o Neither the name of Andrey Kuznetsov nor the names of
017 * its contributors may be used to endorse or promote products derived
018 * from this software without specific prior written permission.
019 *
020 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
021 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
022 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
023 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
024 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
025 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
026 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
027 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
028 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
029 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
030 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
031 */
032
033 package com.imagero.uio.io;
034 import java.io.IOException;
035 import java.io.InputStream;
036
037 /**
038 * @author Andrey Kuznetsov
039 */
040 public class TargaRLEInputStream extends RLEInputStream {
041
042 int numSamples;
043 byte [] value;
044 boolean rawPacket;
045 int pixelSize;
046 int vindex;
047
048 public TargaRLEInputStream(InputStream in, int pixelSize) {
049 super(in);
050 this.pixelSize = pixelSize;
051 value = new byte[pixelSize];
052 }
053
054 public int read() throws IOException {
055 if (numSamples == 0) {
056 int v = in.read();
057 if(v == -1) {
058 return -1;
059 }
060 if ((v >> 7) == 1) {
061 for (int i = 0; i < value.length; i++) {
062 value[i] = (byte) in.read();
063 }
064 numSamples = ((v & 0x7F) + 1) * pixelSize;
065 rawPacket = false;
066 }
067 else {
068 numSamples = (v + 1) * pixelSize;
069 rawPacket = true;
070 }
071 }
072 numSamples--;
073 if (rawPacket) {
074 return in.read();
075 }
076 else {
077 int b = value[vindex++] & 0xFF;
078 if(vindex == pixelSize) {
079 vindex = 0;
080 }
081 return b;
082 }
083 }
084 }