2 * This file was adapted from Jason Marshall's PNGImageProducer.java
4 * Copyright (c) 1997, Jason Marshall. All Rights Reserved
6 * The author makes no representations or warranties regarding the suitability,
7 * reliability or stability of this code. This code is provided AS IS. The
8 * author shall not be liable for any damages suffered as a result of using,
9 * modifying or redistributing this software or any derivitives thereof.
10 * Permission to use, reproduce, modify and/or (re)distribute this software is
14 package org.xwt.translators;
17 import org.xwt.util.*;
19 import java.util.Hashtable;
20 import java.util.Vector;
21 import java.util.Enumeration;
22 import java.util.zip.*;
24 /** Converts an InputStream carrying a PNG image into an ARGB int[] */
29 // Public Methods ///////////////////////////////////////////////////////////////////////////////
31 /** process a PNG as an inputstream; returns null if there is an error
32 @param name A string describing the image, to be used when logging errors
34 public Picture fromInputStream(InputStream is, String name) throws IOException {
35 underlyingStream = is;
37 inputStream = new DataInputStream(underlyingStream);
40 if ((inputStream.read() != 137) || (inputStream.read() != 80) || (inputStream.read() != 78) || (inputStream.read() != 71) ||
41 (inputStream.read() != 13) || (inputStream.read() != 10) || (inputStream.read() != 26) || (inputStream.read() != 10)) {
42 Log.log(this, "PNG: error: input file " + name + " is not a PNG file");
48 DONE: while (!error) {
50 chunkLength = inputStream.readInt();
51 chunkType = inputStream.readInt();
52 needChunkInfo = false;
56 case CHUNK_bKGD: inputStream.skip(chunkLength); break;
57 case CHUNK_cHRM: inputStream.skip(chunkLength); break;
58 case CHUNK_gAMA: inputStream.skip(chunkLength); break;
59 case CHUNK_hIST: inputStream.skip(chunkLength); break;
60 case CHUNK_pHYs: inputStream.skip(chunkLength); break;
61 case CHUNK_sBIT: inputStream.skip(chunkLength); break;
62 case CHUNK_tEXt: inputStream.skip(chunkLength); break;
63 case CHUNK_zTXt: inputStream.skip(chunkLength); break;
64 case CHUNK_tIME: inputStream.skip(chunkLength); break;
66 case CHUNK_IHDR: handleIHDR(); break;
67 case CHUNK_PLTE: handlePLTE(); break;
68 case CHUNK_tRNS: handletRNS(); break;
70 case CHUNK_IDAT: handleIDAT(); break;
72 case CHUNK_IEND: break DONE;
74 System.err.println("unrecognized chunk type " +
75 Integer.toHexString(chunkType) + ". skipping");
76 inputStream.skip(chunkLength);
79 int crc = inputStream.readInt();
83 return Platform.createPicture(data, width, height);
86 // Chunk Handlers ///////////////////////////////////////////////////////////////////////
88 /** handle data chunk */
89 private void handleIDAT() throws IOException {
90 if (width == -1 || height == -1) throw new IOException("never got image width/height");
92 case 1: mask = 0x1; break;
93 case 2: mask = 0x3; break;
94 case 4: mask = 0xf; break;
95 case 8: case 16: mask = 0xff; break;
96 default: mask = 0x0; break;
98 if (depth < 8) smask = mask << depth;
99 else smask = mask << 8;
101 int count = width * height;
108 ipixels = new int[count];
112 bpixels = new byte[count];
116 throw new IOException("Image has unknown color type");
118 if (interlaceMethod != 0) multipass = true;
122 /** handle header chunk */
123 private void handleIHDR() throws IOException {
124 if (headerFound) throw new IOException("Extraneous IHDR chunk encountered.");
125 if (chunkLength != 13) throw new IOException("IHDR chunk length wrong: " + chunkLength);
126 width = inputStream.readInt();
127 height = inputStream.readInt();
128 depth = inputStream.read();
129 colorType = inputStream.read();
130 compressionMethod = inputStream.read();
131 filterMethod = inputStream.read();
132 interlaceMethod = inputStream.read();
135 /** handle pallette chunk */
136 private void handlePLTE() throws IOException {
137 if (colorType == 3) {
138 palette = new byte[chunkLength];
139 inputStream.readFully(palette);
141 // Ignore suggested palette
142 inputStream.skip(chunkLength);
146 /** handle transparency chunk; modifies palette */
147 private void handletRNS() throws IOException {
148 int chunkLen = chunkLength;
149 if (palette == null) {
150 if (Log.on) Log.log(this, "warning: tRNS chunk encountered before pLTE; ignoring alpha channel");
151 inputStream.skip(chunkLength);
154 int len = palette.length;
155 if (colorType == 3) {
158 int transLength = len/3;
159 byte[] trans = new byte[transLength];
160 for (int i = 0; i < transLength; i++) trans[i] = (byte) 0xff;
161 inputStream.readFully(trans, 0, chunkLength);
163 byte[] newPalette = new byte[len + transLength];
164 for (int i = newPalette.length; i > 0;) {
165 newPalette[--i] = trans[--transLength];
166 newPalette[--i] = palette[--len];
167 newPalette[--i] = palette[--len];
168 newPalette[--i] = palette[--len];
170 palette = newPalette;
173 inputStream.skip(chunkLength);
177 /// Helper functions for IDAT ///////////////////////////////////////////////////////////////////////////////////////////
179 /** Read Image data in off of a compression stream */
180 private void readImageData() throws IOException {
181 InputStream dataStream = new SequenceInputStream(new IDATEnumeration(this));
182 DataInputStream dis = new DataInputStream(new BufferedInputStream(new InflaterInputStream(dataStream, new Inflater())));
183 int bps, filterOffset;
185 case 0: case 3: bps = depth; break;
186 case 2: bps = 3 * depth; break;
187 case 4: bps = depth<<1; break;
188 case 6: bps = depth<<2; break;
189 default: throw new IOException("Unknown color type encountered.");
192 filterOffset = (bps + 7) >> 3;
194 for (pass = (multipass ? 1 : 0); pass < 8; pass++) {
195 int pass = this.pass;
196 int rInc = rowInc[pass];
197 int cInc = colInc[pass];
198 int sCol = startingCol[pass];
199 int val = (width - sCol + cInc - 1) / cInc;
200 int samples = val * filterOffset;
201 int rowSize = (val * bps)>>3;
202 int sRow = startingRow[pass];
203 if (height <= sRow || rowSize == 0) continue;
204 int sInc = rInc * width;
205 byte inbuf[] = new byte[rowSize];
206 int pix[] = new int[rowSize];
208 int temp[] = new int[rowSize];
209 int nextY = sRow; // next Y value and number of rows to report to sendPixels
211 int rowStart = sRow * width;
213 for (int y = sRow; y < height; y += rInc, rowStart += sInc) {
215 int rowFilter = dis.read();
216 dis.readFully(inbuf);
217 if (!filterRow(inbuf, pix, upix, rowFilter, filterOffset)) throw new IOException("Unknown filter type: " + rowFilter);
218 insertPixels(pix, rowStart + sCol, samples);
219 if (multipass && (pass < 6)) blockFill(rowStart);
224 if (!multipass) break;
226 while(dis.read() != -1) System.err.println("Leftover data encountered.");
228 // 24-bit color is our native format
229 if (colorType == 2 || colorType == 6) {
230 data = (int[])pixels;
231 if (colorType == 2) {
232 for(int i=0; i<data.length; i++)
233 data[i] |= 0xFF000000;
236 } else if (colorType == 3) {
237 byte[] pix = (byte[])pixels;
238 data = new int[pix.length];
239 for(int i=0; i<pix.length; i++) {
242 ((palette[4 * (pix[i] & 0xff) + 3] & 0xff) << 24) |
243 ((palette[4 * (pix[i] & 0xff) + 0] & 0xff) << 16) |
244 ((palette[4 * (pix[i] & 0xff) + 1] & 0xff) << 8) |
245 (palette[4 * (pix[i] & 0xff) + 2] & 0xff);
249 ((palette[3 * (pix[i] & 0xff) + 0] & 0xff) << 16) |
250 ((palette[3 * (pix[i] & 0xff) + 1] & 0xff) << 8) |
251 (palette[3 * (pix[i] & 0xff) + 2] & 0xff);
255 } else if (colorType == 0 || colorType == 4) {
256 if (depth == 16) depth = 8;
257 int[] pix = (int[])pixels;
258 data = new int[pix.length];
259 for(int i=0; i<pix.length; i ++) {
260 if (colorType == 0) {
261 int val = (pix[i] & 0xff) << (8 - depth);
268 int alpha = (pix[i] & mask) << (8 - depth);
269 int val = ((pix[i] & smask) >> depth) << (8 - depth);
281 private void insertGreyPixels(int pix[], int offset, int samples) {
283 int ipix[] = ipixels;
284 int cInc = colInc[pass];
287 if (colorType == 0) {
290 for (int j = 0; j < samples; j++, offset += cInc) {
292 else { rs = 7; p = pix[j>>3]; }
293 ipix[offset] = (p>>rs) & 0x1;
297 for (int j = 0; j < samples; j++, offset += cInc) {
298 if (rs != 0) rs -= 2;
299 else { rs = 6; p = pix[j>>2]; }
300 ipix[offset] = (p>>rs) & 0x3;
304 for (int j = 0; j < samples; j++, offset += cInc) {
306 else { rs = 4; p = pix[j>>1]; }
307 ipix[offset] = (p>>rs) & 0xf;
311 for (int j = 0; j < samples; offset += cInc) ipix[offset] = (byte) pix[j++];
314 samples = samples<<1;
315 for (int j = 0; j < samples; j += 2, offset += cInc) ipix[offset] = pix[j];
319 } else if (colorType == 4) {
321 for (int j = 0; j < samples; offset += cInc) ipix[offset] = (pix[j++]<<8) | pix[j++];
323 samples = samples<<1;
324 for (int j = 0; j < samples; j += 2, offset += cInc) ipix[offset] = (pix[j]<<8) | pix[j+=2];
329 private void insertPalettedPixels(int pix[], int offset, int samples) {
332 byte bpix[] = bpixels;
333 int cInc = colInc[pass];
337 for (int j = 0; j < samples; j++, offset += cInc) {
339 else { rs = 7; p = pix[j>>3]; }
340 bpix[offset] = (byte) ((p>>rs) & 0x1);
344 for (int j = 0; j < samples; j++, offset += cInc) {
345 if (rs != 0) rs -= 2;
346 else { rs = 6; p = pix[j>>2]; }
347 bpix[offset] = (byte) ((p>>rs) & 0x3);
351 for (int j = 0; j < samples; j++, offset += cInc) {
353 else { rs = 4; p = pix[j>>1]; }
354 bpix[offset] = (byte) ((p>>rs) & 0xf);
358 for (int j = 0; j < samples; j++, offset += cInc) bpix[offset] = (byte) pix[j];
363 private void insertPixels(int pix[], int offset, int samples) {
367 insertGreyPixels(pix, offset, samples);
371 int ipix[] = ipixels;
372 int cInc = colInc[pass];
374 for (j = 0; j < samples; offset += cInc)
375 ipix[offset] = (pix[j++]<<16) | (pix[j++]<<8) | pix[j++];
377 samples = samples<<1;
378 for (j = 0; j < samples; j += 2, offset += cInc)
379 ipix[offset] = (pix[j]<<16) | (pix[j+=2]<<8) | pix[j+=2];
383 insertPalettedPixels(pix, offset, samples);
387 int ipix[] = ipixels;
388 int cInc = colInc[pass];
390 for (j = 0; j < samples; offset += cInc) {
391 ipix[offset] = (pix[j++]<<16) | (pix[j++]<<8) | pix[j++] |
395 samples = samples<<1;
396 for (j = 0; j < samples; j += 2, offset += cInc) {
397 ipix[offset] = (pix[j]<<16) | (pix[j+=2]<<8) | pix[j+=2] |
407 private void blockFill(int rowStart) {
410 int pass = this.pass;
411 int w = blockWidth[pass];
412 int sCol = startingCol[pass];
413 int cInc = colInc[pass];
415 int maxW = rowStart + dw - w;
417 int h = blockHeight[pass];
418 int maxH = rowStart + (dw * h);
419 int startPos = rowStart + sCol;
422 if (colorType == 3) {
423 byte bpix[] = bpixels;
426 for (; counter <= maxW;) {
427 int end = counter + w;
428 pixel = bpix[counter++];
429 for (; counter < end; counter++) bpix[counter] = pixel;
434 for (pixel = bpix[counter++]; counter < maxW; counter++)
435 bpix[counter] = pixel;
436 if (len < maxH) maxH = len;
437 for (counter = startPos + dw; counter < maxH; counter += dw)
438 System.arraycopy(bpix, startPos, bpix, counter, dw - sCol);
440 int ipix[] = ipixels;
443 for (; counter <= maxW;) {
444 int end = counter + w;
445 pixel = ipix[counter++];
446 for (; counter < end; counter++)
447 ipix[counter] = pixel;
452 for (pixel = ipix[counter++]; counter < maxW; counter++)
453 ipix[counter] = pixel;
454 if (len < maxH) maxH = len;
455 for (counter = startPos + dw; counter < maxH; counter += dw)
456 System.arraycopy(ipix, startPos, ipix, counter, dw - sCol);
460 private boolean filterRow(byte inbuf[], int pix[], int upix[], int rowFilter, int boff) {
461 int rowWidth = pix.length;
464 for (int x = 0; x < rowWidth; x++) pix[x] = 0xff & inbuf[x];
468 for ( ; x < boff; x++) pix[x] = 0xff & inbuf[x];
469 for ( ; x < rowWidth; x++) pix[x] = 0xff & (inbuf[x] + pix[x - boff]);
473 for (int x = 0; x < rowWidth; x++)
474 pix[x] = 0xff & (upix[x] + inbuf[x]);
476 for (int x = 0; x < rowWidth; x++)
477 pix[x] = 0xff & inbuf[x];
483 for ( ; x < boff; x++) {
485 pix[x] = 0xff & ((rval>>1) + inbuf[x]);
487 for ( ; x < rowWidth; x++) {
488 int rval = upix[x] + pix[x - boff];
489 pix[x] = 0xff & ((rval>>1) + inbuf[x]);
493 for ( ; x < boff; x++) pix[x] = 0xff & inbuf[x];
494 for ( ; x < rowWidth; x++) {
495 int rval = pix[x - boff];
496 pix[x] = 0xff & ((rval>>1) + inbuf[x]);
503 for ( ; x < boff; x++) pix[x] = 0xff & (upix[x] + inbuf[x]);
504 for ( ; x < rowWidth; x++) {
505 int a, b, c, p, pa, pb, pc, rval;
510 pa = p > a ? p - a : a - p;
511 pb = p > b ? p - b : b - p;
512 pc = p > c ? p - c : c - p;
513 if ((pa <= pb) && (pa <= pc)) rval = a;
514 else if (pb <= pc) rval = b;
516 pix[x] = 0xff & (rval + inbuf[x]);
520 for ( ; x < boff; x++) pix[x] = 0xff & inbuf[x];
521 for ( ; x < rowWidth; x++) {
522 int rval = pix[x - boff];
523 pix[x] = 0xff & (rval + inbuf[x]);
527 default: return false;
532 // Private Data ///////////////////////////////////////////////////////////////////////////////////////
534 private int target_offset = 0;
535 private int width = -1;
536 private int height = -1;
537 private int sigmask = 0xffff;
538 private Object pixels = null;
539 private int ipixels[] = null;
540 private byte bpixels[] = null;
541 private boolean multipass = false;
542 private boolean complete = false;
543 private boolean error = false;
545 private int[] data = null;
547 private InputStream underlyingStream = null;
548 private DataInputStream inputStream = null;
549 private Thread controlThread = null;
550 private boolean infoAvailable = false;
551 private int updateDelay = 750;
553 // Image decoding state variables
554 private boolean headerFound = false;
555 private int compressionMethod = -1;
556 private int depth = -1;
557 private int colorType = -1;
558 private int filterMethod = -1;
559 private int interlaceMethod = -1;
560 private int pass = 0;
561 private byte palette[] = null;
562 private int mask = 0x0;
563 private int smask = 0x0;
564 private boolean transparency = false;
566 private int chunkLength = 0;
567 private int chunkType = 0;
568 private boolean needChunkInfo = true;
570 private static final int CHUNK_bKGD = 0x624B4744; // "bKGD"
571 private static final int CHUNK_cHRM = 0x6348524D; // "cHRM"
572 private static final int CHUNK_gAMA = 0x67414D41; // "gAMA"
573 private static final int CHUNK_hIST = 0x68495354; // "hIST"
574 private static final int CHUNK_IDAT = 0x49444154; // "IDAT"
575 private static final int CHUNK_IEND = 0x49454E44; // "IEND"
576 private static final int CHUNK_IHDR = 0x49484452; // "IHDR"
577 private static final int CHUNK_PLTE = 0x504C5445; // "PLTE"
578 private static final int CHUNK_pHYs = 0x70485973; // "pHYs"
579 private static final int CHUNK_sBIT = 0x73424954; // "sBIT"
580 private static final int CHUNK_tEXt = 0x74455874; // "tEXt"
581 private static final int CHUNK_tIME = 0x74494D45; // "tIME"
582 private static final int CHUNK_tRNS = 0x74524E53; // "tIME"
583 private static final int CHUNK_zTXt = 0x7A545874; // "zTXt"
585 private static final int startingRow[] = { 0, 0, 0, 4, 0, 2, 0, 1 };
586 private static final int startingCol[] = { 0, 0, 4, 0, 2, 0, 1, 0 };
587 private static final int rowInc[] = { 1, 8, 8, 8, 4, 4, 2, 2 };
588 private static final int colInc[] = { 1, 8, 8, 4, 4, 2, 2, 1 };
589 private static final int blockHeight[] = { 1, 8, 8, 4, 4, 2, 2, 1 };
590 private static final int blockWidth[] = { 1, 8, 4, 4, 2, 2, 1, 1 };
592 // Helper Classes ////////////////////////////////////////////////////////////////////
594 private static class MeteredInputStream extends FilterInputStream {
598 public MeteredInputStream(InputStream in, int size) {
603 public final int read() throws IOException {
606 if (val != -1) bytesLeft--;
612 public final int read(byte b[]) throws IOException {
613 return read(b, 0, b.length);
616 public final int read(byte b[], int off, int len) throws IOException {
618 len = (len > bytesLeft ? bytesLeft : len);
619 int read = in.read(b, off, len);
620 if (read > 0) bytesLeft -= read;
626 public final long skip(long n) throws IOException {
627 n = (n > bytesLeft ? bytesLeft : n);
628 long skipped = in.skip(n);
629 if (skipped > 0) bytesLeft -= skipped;
633 public final int available() throws IOException {
634 int n = in.available();
635 return (n > bytesLeft ? bytesLeft : n);
638 public final void close() throws IOException { /* Eat this */ }
640 public final void mark(int readlimit) {
645 public final void reset() throws IOException {
650 public final boolean markSupported() { return in.markSupported(); }
653 /** Support class, used to eat the IDAT headers dividing up the deflated stream */
654 private static class IDATEnumeration implements Enumeration {
655 InputStream underlyingStream;
657 boolean firstStream = true;
659 public IDATEnumeration(PNG owner) {
661 this.underlyingStream = owner.underlyingStream;
664 public Object nextElement() {
666 return new MeteredInputStream(underlyingStream, owner.chunkLength);
669 public boolean hasMoreElements() {
670 DataInputStream dis = new DataInputStream(underlyingStream);
673 int crc = dis.readInt();
674 owner.needChunkInfo = false;
675 owner.chunkLength = dis.readInt();
676 owner.chunkType = dis.readInt();
677 } catch (IOException ioe) {
681 if (owner.chunkType == PNG.CHUNK_IDAT) return true;