[poppler] Branch 'xpdf303merge' - 14 commits - poppler/JPXStream.cc poppler/JPXStream.h poppler/Stream.cc poppler/Stream.h utils/pdfinfo.cc

Albert Astals Cid aacid at kemper.freedesktop.org
Mon Sep 5 15:04:01 PDT 2011


 poppler/JPXStream.cc | 1000 +++++++++++++++++++++++++++++++--------------------
 poppler/JPXStream.h  |   43 --
 poppler/Stream.cc    |  170 ++++++--
 poppler/Stream.h     |   31 +
 utils/pdfinfo.cc     |   30 +
 5 files changed, 822 insertions(+), 452 deletions(-)

New commits:
commit 2230b8f2128edf4994d8a742f562e1b5acf96b74
Author: Albert Astals Cid <aacid at kde.org>
Date:   Tue Sep 6 00:05:53 2011 +0200

    xpdf303: Merge JPXStream changes

diff --git a/poppler/JPXStream.cc b/poppler/JPXStream.cc
index 069fba0..54bee6f 100644
--- a/poppler/JPXStream.cc
+++ b/poppler/JPXStream.cc
@@ -21,13 +21,13 @@
 //========================================================================
 
 #include <config.h>
-#include <limits.h>
 
 #ifdef USE_GCC_PRAGMAS
 #pragma implementation
 #endif
 
-#include "goo/gmem.h"
+#include <limits.h>
+#include "gmem.h"
 #include "Error.h"
 #include "JArithmeticDecoder.h"
 #include "JPXStream.h"
@@ -40,16 +40,11 @@
 //  - support for palettes, channel maps, etc.
 //  - make sure all needed JP2/JPX subboxes are parsed (readBoxes)
 //  - can we assume that QCC segments must come after the QCD segment?
-//  - skip EPH markers (readTilePartData)
 //  - handle tilePartToEOC in readTilePartData
-//  - deal with multiple codeword segments (readTilePartData,
-//    readCodeBlockData)
 //  - progression orders 2, 3, and 4
 //  - in coefficient decoding (readCodeBlockData):
-//    - termination pattern: terminate after every coding pass
-//    - error resilience segmentation symbol
 //    - selective arithmetic coding bypass
-//    - vertically causal context formation
+//      (this also affects reading the cb->dataLen array)
 //    - coeffs longer than 31 bits (should just ignore the extra bits?)
 //  - handle boxes larger than 2^32 bytes
 //  - the fixed-point arithmetic won't handle 16-bit pixels
@@ -247,6 +242,8 @@ JPXCover jpxCover(150);
 JPXStream::JPXStream(Stream *strA):
   FilterStream(strA)
 {
+  bufStr = new BufStream(str, 2);
+
   nComps = 0;
   bpc = NULL;
   width = height = 0;
@@ -264,11 +261,11 @@ JPXStream::JPXStream(Stream *strA):
 
 JPXStream::~JPXStream() {
   close();
-  delete str;
+  delete bufStr;
 }
 
 void JPXStream::reset() {
-  str->reset();
+  bufStr->reset();
   if (readBoxes()) {
     curY = img.yOffset;
   } else {
@@ -332,7 +329,8 @@ void JPXStream::close() {
 		      if (subband->cbs) {
 			for (k = 0; k < subband->nXCBs * subband->nYCBs; ++k) {
 			  cb = &subband->cbs[k];
-			  gfree(cb->coeffs);
+			  gfree(cb->dataLen);
+			  gfree(cb->touched);
 			  if (cb->arithDecoder) {
 			    delete cb->arithDecoder;
 			  }
@@ -358,7 +356,7 @@ void JPXStream::close() {
     gfree(img.tiles);
     img.tiles = NULL;
   }
-  FilterStream::close();
+  bufStr->close();
 }
 
 int JPXStream::getChar() {
@@ -427,7 +425,8 @@ void JPXStream::fillReadBuf() {
       if (pix >= 0 && pix < palette.nEntries) {
 	pix = palette.c[pix * palette.nComps + curComp];
       } else {
-	pix = 
+	pix = 0;
+      }
       pixBits = palette.bpc[curComp];
     }
     if (++curComp == (Guint)(havePalette ? palette.nComps : img.nComps)) {
@@ -436,6 +435,10 @@ void JPXStream::fillReadBuf() {
       if (++curX == img.xSize) {
 	curX = img.xOffset;
 	++curY;
+	if (pixBits < 8) {
+	  pix <<= 8 - pixBits;
+	  pixBits = 8;
+	}
       }
     }
     if (pixBits == 8) {
@@ -465,8 +468,8 @@ void JPXStream::getImageParams(int *bitsPerComponent,
 
   csPrec = 0; // make gcc happy
   haveBPC = haveCSMode = gFalse;
-  str->reset();
-  if (str->lookChar() == 0xff) {
+  bufStr->reset();
+  if (bufStr->lookChar() == 0xff) {
     getImageParams2(bitsPerComponent, csMode);
   } else {
     while (readBoxHdr(&boxType, &boxLen, &dataLen)) {
@@ -510,12 +513,12 @@ void JPXStream::getImageParams(int *bitsPerComponent,
 		haveCSMode = gTrue;
 	      }
 	      for (i = 0; i < dataLen - 7; ++i) {
-		str->getChar();
+		bufStr->getChar();
 	      }
 	    }
 	  } else {
 	    for (i = 0; i < dataLen - 3; ++i) {
-	      str->getChar();
+	      bufStr->getChar();
 	    }
 	  }
 	}
@@ -528,12 +531,12 @@ void JPXStream::getImageParams(int *bitsPerComponent,
       } else {
 	cover(4);
 	for (i = 0; i < dataLen; ++i) {
-	  str->getChar();
+	  bufStr->getChar();
 	}
       }
     }
   }
-  str->close();
+  bufStr->close();
 }
 
 // Get image parameters from the codestream.
@@ -571,7 +574,7 @@ void JPXStream::getImageParams2(int *bitsPerComponent,
       cover(6);
       if (segLen > 2) {
 	for (i = 0; i < segLen - 2; ++i) {
-	  str->getChar();
+	  bufStr->getChar();
 	}
       }
     }
@@ -588,11 +591,13 @@ GBool JPXStream::readBoxes() {
   // check for a naked JPEG 2000 codestream (without the JP2/JPX
   // wrapper) -- this appears to be a violation of the PDF spec, but
   // Acrobat allows it
-  if (str->lookChar() == 0xff) {
+  if (bufStr->lookChar() == 0xff) {
     cover(7);
     error(errSyntaxWarning, getPos(),
 	  "Naked JPEG 2000 codestream, missing JP2/JPX wrapper");
-    readCodestream(0);
+    if (!readCodestream(0)) {
+      return gFalse;
+    }
     nComps = img.nComps;
     bpc = (Guint *)gmallocn(nComps, sizeof(Guint));
     for (i = 0; i < nComps; ++i) {
@@ -626,7 +631,8 @@ GBool JPXStream::readBoxes() {
 	return gFalse;
       }
       if (compression != 7) {
-	error(errSyntaxError, getPos(), "Unknown compression type in JPX stream");
+	error(errSyntaxError, getPos(),
+	      "Unknown compression type in JPX stream");
 	return gFalse;
       }
       bpc = (Guint *)gmallocn(nComps, sizeof(Guint));
@@ -638,11 +644,13 @@ GBool JPXStream::readBoxes() {
     case 0x62706363:		// bits per component
       cover(10);
       if (!haveImgHdr) {
-	error(errSyntaxError, getPos(), "Found bits per component box before image header box in JPX stream");
+	error(errSyntaxError, getPos(),
+	      "Found bits per component box before image header box in JPX stream");
 	return gFalse;
       }
       if (dataLen != nComps) {
-	error(errSyntaxError, getPos(), "Invalid bits per component box in JPX stream");
+	error(errSyntaxError, getPos(),
+	      "Invalid bits per component box in JPX stream");
 	return gFalse;
       }
       for (i = 0; i < nComps; ++i) {
@@ -728,10 +736,12 @@ GBool JPXStream::readBoxes() {
     case 0x6A703263:		// contiguous codestream
       cover(15);
       if (!bpc) {
-	error(errSyntaxError, getPos(), "JPX stream is missing the image header box");
+	error(errSyntaxError, getPos(),
+	      "JPX stream is missing the image header box");
       }
       if (!haveCS) {
-	error(errSyntaxError, getPos(), "JPX stream has no supported color spec");
+	error(errSyntaxError, getPos(),
+	      "JPX stream has no supported color spec");
       }
       if (!readCodestream(dataLen)) {
 	return gFalse;
@@ -740,7 +750,7 @@ GBool JPXStream::readBoxes() {
     default:
       cover(16);
       for (i = 0; i < dataLen; ++i) {
-	if (str->getChar() == EOF) {
+	if (bufStr->getChar() == EOF) {
 	  error(errSyntaxError, getPos(), "Unexpected EOF in JPX stream");
 	  return gFalse;
 	}
@@ -857,7 +867,7 @@ GBool JPXStream::readColorSpecBox(Guint dataLen) {
   case 4:			// vendor color (JPX)
     cover(18);
     for (i = 0; i < dataLen - 3; ++i) {
-      if (str->getChar() == EOF) {
+      if (bufStr->getChar() == EOF) {
 	goto err;
       }
     }
@@ -898,6 +908,11 @@ GBool JPXStream::readCodestream(Guint len) {
       break;
     case 0x51:			// SIZ - image and tile size
       cover(20);
+      if (haveSIZ) {
+	error(errSyntaxError, getPos(),
+	      "Duplicate SIZ marker segment in JPX stream");
+	return gFalse;
+      }
       if (!readUWord(&capabilities) ||
 	  !readULong(&img.xSize) ||
 	  !readULong(&img.ySize) ||
@@ -912,7 +927,18 @@ GBool JPXStream::readCodestream(Guint len) {
 	return gFalse;
       }
       if (haveImgHdr && img.nComps != nComps) {
-	error(errSyntaxError, getPos(), "Different number of components in JPX SIZ marker segment");
+	error(errSyntaxError, getPos(),
+	      "Different number of components in JPX SIZ marker segment");
+	return gFalse;
+      }
+      if (img.xSize == 0 || img.ySize == 0 ||
+	  img.xOffset >= img.xSize || img.yOffset >= img.ySize ||
+	  img.xTileSize == 0 || img.yTileSize == 0 ||
+	  img.xTileOffset > img.xOffset ||
+	  img.yTileOffset > img.yOffset ||
+	  img.xTileSize + img.xTileOffset <= img.xOffset ||
+	  img.yTileSize + img.yTileOffset <= img.yOffset) {
+	error(errSyntaxError, getPos(), "Error in JPX SIZ marker segment");
 	return gFalse;
       }
       img.nXTiles = (img.xSize - img.xTileOffset + img.xTileSize - 1)
@@ -922,12 +948,14 @@ GBool JPXStream::readCodestream(Guint len) {
       // check for overflow before allocating memory
       if (img.nXTiles <= 0 || img.nYTiles <= 0 ||
 	  img.nXTiles >= INT_MAX / img.nYTiles) {
-	error(errSyntaxError, getPos(), "Bad tile count in JPX SIZ marker segment");
+	error(errSyntaxError, getPos(),
+	      "Bad tile count in JPX SIZ marker segment");
 	return gFalse;
       }
       img.tiles = (JPXTile *)gmallocn(img.nXTiles * img.nYTiles,
 				      sizeof(JPXTile));
       for (i = 0; i < img.nXTiles * img.nYTiles; ++i) {
+	img.tiles[i].init = gFalse;
 	img.tiles[i].tileComps = (JPXTileComp *)gmallocn(img.nComps,
 							 sizeof(JPXTileComp));
 	for (comp = 0; comp < img.nComps; ++comp) {
@@ -944,6 +972,11 @@ GBool JPXStream::readCodestream(Guint len) {
 	  error(errSyntaxError, getPos(), "Error in JPX SIZ marker segment");
 	  return gFalse;
 	}
+	if (img.tiles[0].tileComps[comp].hSep == 0 ||
+	    img.tiles[0].tileComps[comp].vSep == 0) {
+	  error(errSyntaxError, getPos(), "Error in JPX SIZ marker segment");
+	  return gFalse;
+	}
 	img.tiles[0].tileComps[comp].sgned =
 	    (img.tiles[0].tileComps[comp].prec & 0x80) ? gTrue : gFalse;
 	img.tiles[0].tileComps[comp].prec =
@@ -956,6 +989,11 @@ GBool JPXStream::readCodestream(Guint len) {
       break;
     case 0x52:			// COD - coding style default
       cover(21);
+      if (!haveSIZ) {
+	error(errSyntaxError, getPos(),
+	      "JPX COD marker segment before SIZ segment");
+	return gFalse;
+      }
       if (!readUByte(&img.tiles[0].tileComps[0].style) ||
 	  !readUByte(&img.tiles[0].progOrder) ||
 	  !readUWord(&img.tiles[0].nLayers) ||
@@ -968,6 +1006,12 @@ GBool JPXStream::readCodestream(Guint len) {
 	error(errSyntaxError, getPos(), "Error in JPX COD marker segment");
 	return gFalse;
       }
+      if (img.tiles[0].tileComps[0].nDecompLevels > 32 ||
+	  img.tiles[0].tileComps[0].codeBlockW > 8 ||
+	  img.tiles[0].tileComps[0].codeBlockH > 8) {
+	error(errSyntaxError, getPos(), "Error in JPX COD marker segment");
+	return gFalse;
+      }
       img.tiles[0].tileComps[0].codeBlockW += 2;
       img.tiles[0].tileComps[0].codeBlockH += 2;
       for (i = 0; i < img.nXTiles * img.nYTiles; ++i) {
@@ -1033,7 +1077,8 @@ GBool JPXStream::readCodestream(Guint len) {
     case 0x53:			// COC - coding style component
       cover(22);
       if (!haveCOD) {
-	error(errSyntaxError, getPos(), "JPX COC marker segment before COD segment");
+	error(errSyntaxError, getPos(),
+	      "JPX COC marker segment before COD segment");
 	return gFalse;
       }
       if ((img.nComps > 256 && !readUWord(&comp)) ||
@@ -1048,6 +1093,12 @@ GBool JPXStream::readCodestream(Guint len) {
 	error(errSyntaxError, getPos(), "Error in JPX COC marker segment");
 	return gFalse;
       }
+      if (img.tiles[0].tileComps[comp].nDecompLevels > 32 ||
+	  img.tiles[0].tileComps[comp].codeBlockW > 8 ||
+	  img.tiles[0].tileComps[comp].codeBlockH > 8) {
+	error(errSyntaxError, getPos(), "Error in JPX COC marker segment");
+	return gFalse;
+      }
       img.tiles[0].tileComps[comp].style =
 	  (img.tiles[0].tileComps[comp].style & ~1) | (style & 1);
       img.tiles[0].tileComps[comp].codeBlockW += 2;
@@ -1102,11 +1153,20 @@ GBool JPXStream::readCodestream(Guint len) {
       break;
     case 0x5c:			// QCD - quantization default
       cover(23);
+      if (!haveSIZ) {
+	error(errSyntaxError, getPos(),
+	      "JPX QCD marker segment before SIZ segment");
+	return gFalse;
+      }
       if (!readUByte(&img.tiles[0].tileComps[0].quantStyle)) {
 	error(errSyntaxError, getPos(), "Error in JPX QCD marker segment");
 	return gFalse;
       }
       if ((img.tiles[0].tileComps[0].quantStyle & 0x1f) == 0x00) {
+	if (segLen <= 3) {
+	  error(errSyntaxError, getPos(), "Error in JPX QCD marker segment");
+	  return gFalse;
+	}
 	img.tiles[0].tileComps[0].nQuantSteps = segLen - 3;
 	img.tiles[0].tileComps[0].quantSteps =
 	    (Guint *)greallocn(img.tiles[0].tileComps[0].quantSteps,
@@ -1129,6 +1189,10 @@ GBool JPXStream::readCodestream(Guint len) {
 	  return gFalse;
 	}
       } else if ((img.tiles[0].tileComps[0].quantStyle & 0x1f) == 0x02) {
+	if (segLen < 5) {
+	  error(errSyntaxError, getPos(), "Error in JPX QCD marker segment");
+	  return gFalse;
+	}
 	img.tiles[0].tileComps[0].nQuantSteps = (segLen - 3) / 2;
 	img.tiles[0].tileComps[0].quantSteps =
 	    (Guint *)greallocn(img.tiles[0].tileComps[0].quantSteps,
@@ -1167,7 +1231,8 @@ GBool JPXStream::readCodestream(Guint len) {
     case 0x5d:			// QCC - quantization component
       cover(24);
       if (!haveQCD) {
-	error(errSyntaxError, getPos(), "JPX QCC marker segment before QCD segment");
+	error(errSyntaxError, getPos(),
+	      "JPX QCC marker segment before QCD segment");
 	return gFalse;
       }
       if ((img.nComps > 256 && !readUWord(&comp)) ||
@@ -1178,6 +1243,10 @@ GBool JPXStream::readCodestream(Guint len) {
 	return gFalse;
       }
       if ((img.tiles[0].tileComps[comp].quantStyle & 0x1f) == 0x00) {
+	if (segLen <= (img.nComps > 256 ? 5U : 4U)) {
+	  error(errSyntaxError, getPos(), "Error in JPX QCC marker segment");
+	  return gFalse;
+	}
 	img.tiles[0].tileComps[comp].nQuantSteps =
 	    segLen - (img.nComps > 256 ? 5 : 4);
 	img.tiles[0].tileComps[comp].quantSteps =
@@ -1201,6 +1270,10 @@ GBool JPXStream::readCodestream(Guint len) {
 	  return gFalse;
 	}
       } else if ((img.tiles[0].tileComps[comp].quantStyle & 0x1f) == 0x02) {
+	if (segLen < (img.nComps > 256 ? 5U : 4U) + 2) {
+	  error(errSyntaxError, getPos(), "Error in JPX QCC marker segment");
+	  return gFalse;
+	}
 	img.tiles[0].tileComps[comp].nQuantSteps =
 	    (segLen - (img.nComps > 256 ? 5 : 4)) / 2;
 	img.tiles[0].tileComps[comp].quantSteps =
@@ -1235,10 +1308,10 @@ GBool JPXStream::readCodestream(Guint len) {
     case 0x5e:			// RGN - region of interest
       cover(25);
 #if 1 //~ ROI is unimplemented
-      fprintf(stderr, "RGN\n");
+      error(errUnimplemented, -1, "got a JPX RGN segment");
       for (i = 0; i < segLen - 2; ++i) {
-	if (str->getChar() == EOF) {
-	  error(errSyntaxError, getPos(), "Error in JPX PPM marker segment");
+	if (bufStr->getChar() == EOF) {
+	  error(errSyntaxError, getPos(), "Error in JPX RGN marker segment");
 	  return gFalse;
 	}
       }
@@ -1256,10 +1329,10 @@ GBool JPXStream::readCodestream(Guint len) {
     case 0x5f:			// POC - progression order change
       cover(26);
 #if 1 //~ progression order changes are unimplemented
-      fprintf(stderr, "POC\n");
+      error(errUnimplemented, -1, "got a JPX POC segment");
       for (i = 0; i < segLen - 2; ++i) {
-	if (str->getChar() == EOF) {
-	  error(errSyntaxError, getPos(), "Error in JPX PPM marker segment");
+	if (bufStr->getChar() == EOF) {
+	  error(errSyntaxError, getPos(), "Error in JPX POC marker segment");
 	  return gFalse;
 	}
       }
@@ -1284,9 +1357,9 @@ GBool JPXStream::readCodestream(Guint len) {
     case 0x60:			// PPM - packed packet headers, main header
       cover(27);
 #if 1 //~ packed packet headers are unimplemented
-      fprintf(stderr, "PPM\n");
+      error(errUnimplemented, -1, "Got a JPX PPM segment");
       for (i = 0; i < segLen - 2; ++i) {
-	if (str->getChar() == EOF) {
+	if (bufStr->getChar() == EOF) {
 	  error(errSyntaxError, getPos(), "Error in JPX PPM marker segment");
 	  return gFalse;
 	}
@@ -1297,7 +1370,7 @@ GBool JPXStream::readCodestream(Guint len) {
       // skipped
       cover(28);
       for (i = 0; i < segLen - 2; ++i) {
-	if (str->getChar() == EOF) {
+	if (bufStr->getChar() == EOF) {
 	  error(errSyntaxError, getPos(), "Error in JPX TLM marker segment");
 	  return gFalse;
 	}
@@ -1307,7 +1380,7 @@ GBool JPXStream::readCodestream(Guint len) {
       // skipped
       cover(29);
       for (i = 0; i < segLen - 2; ++i) {
-	if (str->getChar() == EOF) {
+	if (bufStr->getChar() == EOF) {
 	  error(errSyntaxError, getPos(), "Error in JPX PLM marker segment");
 	  return gFalse;
 	}
@@ -1317,7 +1390,7 @@ GBool JPXStream::readCodestream(Guint len) {
       // skipped
       cover(30);
       for (i = 0; i < segLen - 2; ++i) {
-	if (str->getChar() == EOF) {
+	if (bufStr->getChar() == EOF) {
 	  error(errSyntaxError, getPos(), "Error in JPX CRG marker segment");
 	  return gFalse;
 	}
@@ -1327,7 +1400,7 @@ GBool JPXStream::readCodestream(Guint len) {
       // skipped
       cover(31);
       for (i = 0; i < segLen - 2; ++i) {
-	if (str->getChar() == EOF) {
+	if (bufStr->getChar() == EOF) {
 	  error(errSyntaxError, getPos(), "Error in JPX COM marker segment");
 	  return gFalse;
 	}
@@ -1342,7 +1415,7 @@ GBool JPXStream::readCodestream(Guint len) {
       error(errSyntaxError, getPos(),
 	    "Unknown marker segment {0:02x} in JPX stream", segType);
       for (i = 0; i < segLen - 2; ++i) {
-	if (str->getChar() == EOF) {
+	if (bufStr->getChar() == EOF) {
 	  break;
 	}
       }
@@ -1351,15 +1424,18 @@ GBool JPXStream::readCodestream(Guint len) {
   } while (!haveSOT);
 
   if (!haveSIZ) {
-    error(errSyntaxError, getPos(), "Missing SIZ marker segment in JPX stream");
+    error(errSyntaxError, getPos(),
+	  "Missing SIZ marker segment in JPX stream");
     return gFalse;
   }
   if (!haveCOD) {
-    error(errSyntaxError, getPos(), "Missing COD marker segment in JPX stream");
+    error(errSyntaxError, getPos(),
+	  "Missing COD marker segment in JPX stream");
     return gFalse;
   }
   if (!haveQCD) {
-    error(errSyntaxError, getPos(), "Missing QCD marker segment in JPX stream");
+    error(errSyntaxError, getPos(),
+	  "Missing QCD marker segment in JPX stream");
     return gFalse;
   }
 
@@ -1385,6 +1461,10 @@ GBool JPXStream::readCodestream(Guint len) {
   //----- finish decoding the image
   for (i = 0; i < img.nXTiles * img.nYTiles; ++i) {
     tile = &img.tiles[i];
+    if (!tile->init) {
+      error(errSyntaxError, getPos(), "Uninitialized tile in JPX codestream");
+      return gFalse;
+    }
     for (comp = 0; comp < img.nComps; ++comp) {
       tileComp = &tile->tileComps[comp];
       inverseTransform(tileComp);
@@ -1406,12 +1486,13 @@ GBool JPXStream::readTilePart() {
   JPXPrecinct *precinct;
   JPXSubband *subband;
   JPXCodeBlock *cb;
+  int *sbCoeffs;
   GBool haveSOD;
   Guint tileIdx, tilePartLen, tilePartIdx, nTileParts;
   GBool tilePartToEOC;
   Guint precinctSize, style;
   Guint n, nSBs, nx, ny, sbx0, sby0, comp, segLen;
-  Guint i, j, k, cbX, cbY, r, pre, sb, cbi;
+  Guint i, j, k, cbX, cbY, r, pre, sb, cbi, cbj;
   int segType, level;
 
   // process the SOT marker segment
@@ -1423,7 +1504,8 @@ GBool JPXStream::readTilePart() {
     return gFalse;
   }
 
-  if (tileIdx >= img.nXTiles * img.nYTiles) {
+  if ((tilePartIdx > 0 && !img.tiles[tileIdx].init) ||
+      tileIdx >= img.nXTiles * img.nYTiles) {
     error(errSyntaxError, getPos(), "Weird tile index in JPX stream");
     return gFalse;
   }
@@ -1453,6 +1535,12 @@ GBool JPXStream::readTilePart() {
 	error(errSyntaxError, getPos(), "Error in JPX COD marker segment");
 	return gFalse;
       }
+      if (img.tiles[tileIdx].tileComps[0].nDecompLevels > 32 ||
+	  img.tiles[tileIdx].tileComps[0].codeBlockW > 8 ||
+	  img.tiles[tileIdx].tileComps[0].codeBlockH > 8) {
+	error(errSyntaxError, getPos(), "Error in JPX COD marker segment");
+	return gFalse;
+      }
       img.tiles[tileIdx].tileComps[0].codeBlockW += 2;
       img.tiles[tileIdx].tileComps[0].codeBlockH += 2;
       for (comp = 0; comp < img.nComps; ++comp) {
@@ -1521,6 +1609,12 @@ GBool JPXStream::readTilePart() {
 	error(errSyntaxError, getPos(), "Error in JPX COC marker segment");
 	return gFalse;
       }
+      if (img.tiles[tileIdx].tileComps[comp].nDecompLevels > 32 ||
+	  img.tiles[tileIdx].tileComps[comp].codeBlockW > 8 ||
+	  img.tiles[tileIdx].tileComps[comp].codeBlockH > 8) {
+	error(errSyntaxError, getPos(), "Error in JPX COD marker segment");
+	return gFalse;
+      }
       img.tiles[tileIdx].tileComps[comp].style =
 	  (img.tiles[tileIdx].tileComps[comp].style & ~1) | (style & 1);
       img.tiles[tileIdx].tileComps[comp].codeBlockW += 2;
@@ -1556,8 +1650,11 @@ GBool JPXStream::readTilePart() {
 	return gFalse;
       }
       if ((img.tiles[tileIdx].tileComps[0].quantStyle & 0x1f) == 0x00) {
-	img.tiles[tileIdx].tileComps[0].nQuantSteps =
-	    segLen - 3;
+	if (segLen <= 3) {
+	  error(errSyntaxError, getPos(), "Error in JPX QCD marker segment");
+	  return gFalse;
+	}
+	img.tiles[tileIdx].tileComps[0].nQuantSteps = segLen - 3;
 	img.tiles[tileIdx].tileComps[0].quantSteps =
 	    (Guint *)greallocn(img.tiles[tileIdx].tileComps[0].quantSteps,
 			       img.tiles[tileIdx].tileComps[0].nQuantSteps,
@@ -1579,6 +1676,10 @@ GBool JPXStream::readTilePart() {
 	  return gFalse;
 	}
       } else if ((img.tiles[tileIdx].tileComps[0].quantStyle & 0x1f) == 0x02) {
+	if (segLen < 5) {
+	  error(errSyntaxError, getPos(), "Error in JPX QCD marker segment");
+	  return gFalse;
+	}
 	img.tiles[tileIdx].tileComps[0].nQuantSteps = (segLen - 3) / 2;
 	img.tiles[tileIdx].tileComps[0].quantSteps =
 	    (Guint *)greallocn(img.tiles[tileIdx].tileComps[0].quantSteps,
@@ -1619,6 +1720,10 @@ GBool JPXStream::readTilePart() {
 	return gFalse;
       }
       if ((img.tiles[tileIdx].tileComps[comp].quantStyle & 0x1f) == 0x00) {
+	if (segLen <= (img.nComps > 256 ? 5U : 4U)) {
+	  error(errSyntaxError, getPos(), "Error in JPX QCC marker segment");
+	  return gFalse;
+	}
 	img.tiles[tileIdx].tileComps[comp].nQuantSteps =
 	    segLen - (img.nComps > 256 ? 5 : 4);
 	img.tiles[tileIdx].tileComps[comp].quantSteps =
@@ -1644,6 +1749,10 @@ GBool JPXStream::readTilePart() {
 	}
       } else if ((img.tiles[tileIdx].tileComps[comp].quantStyle & 0x1f)
 		 == 0x02) {
+	if (segLen < (img.nComps > 256 ? 5U : 4U) + 2) {
+	  error(errSyntaxError, getPos(), "Error in JPX QCC marker segment");
+	  return gFalse;
+	}
 	img.tiles[tileIdx].tileComps[comp].nQuantSteps =
 	    (segLen - (img.nComps > 256 ? 5 : 4)) / 2;
 	img.tiles[tileIdx].tileComps[comp].quantSteps =
@@ -1664,10 +1773,10 @@ GBool JPXStream::readTilePart() {
     case 0x5e:			// RGN - region of interest
       cover(38);
 #if 1 //~ ROI is unimplemented
-      fprintf(stderr, "RGN\n");
+      error(errUnimplemented, -1, "Got a JPX RGN segment");
       for (i = 0; i < segLen - 2; ++i) {
-	if (str->getChar() == EOF) {
-	  error(errSyntaxError, getPos(), "Error in JPX PPM marker segment");
+	if (bufStr->getChar() == EOF) {
+	  error(errSyntaxError, getPos(), "Error in JPX RGN marker segment");
 	  return gFalse;
 	}
       }
@@ -1685,10 +1794,10 @@ GBool JPXStream::readTilePart() {
     case 0x5f:			// POC - progression order change
       cover(39);
 #if 1 //~ progression order changes are unimplemented
-      fprintf(stderr, "POC\n");
+      error(errUnimplemented, -1, "Got a JPX POC segment");
       for (i = 0; i < segLen - 2; ++i) {
-	if (str->getChar() == EOF) {
-	  error(errSyntaxError, getPos(), "Error in JPX PPM marker segment");
+	if (bufStr->getChar() == EOF) {
+	  error(errSyntaxError, getPos(), "Error in JPX POC marker segment");
 	  return gFalse;
 	}
       }
@@ -1713,9 +1822,9 @@ GBool JPXStream::readTilePart() {
     case 0x61:			// PPT - packed packet headers, tile-part hdr
       cover(40);
 #if 1 //~ packed packet headers are unimplemented
-      fprintf(stderr, "PPT\n");
+      error(errUnimplemented, -1, "Got a JPX PPT segment");
       for (i = 0; i < segLen - 2; ++i) {
-	if (str->getChar() == EOF) {
+	if (bufStr->getChar() == EOF) {
 	  error(errSyntaxError, getPos(), "Error in JPX PPT marker segment");
 	  return gFalse;
 	}
@@ -1725,7 +1834,7 @@ GBool JPXStream::readTilePart() {
       // skipped
       cover(41);
       for (i = 0; i < segLen - 2; ++i) {
-	if (str->getChar() == EOF) {
+	if (bufStr->getChar() == EOF) {
 	  error(errSyntaxError, getPos(), "Error in JPX PLT marker segment");
 	  return gFalse;
 	}
@@ -1735,7 +1844,7 @@ GBool JPXStream::readTilePart() {
       // skipped
       cover(42);
       for (i = 0; i < segLen - 2; ++i) {
-	if (str->getChar() == EOF) {
+	if (bufStr->getChar() == EOF) {
 	  error(errSyntaxError, getPos(), "Error in JPX COM marker segment");
 	  return gFalse;
 	}
@@ -1749,9 +1858,9 @@ GBool JPXStream::readTilePart() {
       cover(44);
       error(errSyntaxError, getPos(),
 	    "Unknown marker segment {0:02x} in JPX tile-part stream",
- 	    segType);
+	    segType);
       for (i = 0; i < segLen - 2; ++i) {
-	if (str->getChar() == EOF) {
+	if (bufStr->getChar() == EOF) {
 	  break;
 	}
       }
@@ -1762,6 +1871,7 @@ GBool JPXStream::readTilePart() {
   //----- initialize the tile, precincts, and code-blocks
   if (tilePartIdx == 0) {
     tile = &img.tiles[tileIdx];
+    tile->init = gTrue;
     i = tileIdx / img.nXTiles;
     j = tileIdx % img.nXTiles;
     if ((tile->x0 = img.xTileOffset + j * img.xTileSize) < img.xOffset) {
@@ -1787,9 +1897,10 @@ GBool JPXStream::readTilePart() {
 	tile->maxNDecompLevels = tileComp->nDecompLevels;
       }
       tileComp->x0 = jpxCeilDiv(tile->x0, tileComp->hSep);
-      tileComp->y0 = jpxCeilDiv(tile->y0, tileComp->hSep);
+      tileComp->y0 = jpxCeilDiv(tile->y0, tileComp->vSep);
       tileComp->x1 = jpxCeilDiv(tile->x1, tileComp->hSep);
-      tileComp->y1 = jpxCeilDiv(tile->y1, tileComp->hSep);
+      tileComp->y1 = jpxCeilDiv(tile->y1, tileComp->vSep);
+      tileComp->w = tileComp->x1 - tileComp->x0;
       tileComp->cbW = 1 << tileComp->codeBlockW;
       tileComp->cbH = 1 << tileComp->codeBlockH;
       tileComp->data = (int *)gmallocn((tileComp->x1 - tileComp->x0) *
@@ -1878,6 +1989,19 @@ GBool JPXStream::readTilePart() {
 						    sizeof(JPXCodeBlock));
 	    sbx0 = jpxFloorDivPow2(subband->x0, tileComp->codeBlockW);
 	    sby0 = jpxFloorDivPow2(subband->y0, tileComp->codeBlockH);
+	    if (r == 0) { // (NL)LL
+	      sbCoeffs = tileComp->data;
+	    } else if (sb == 0) { // (NL-r+1)HL
+	      sbCoeffs = tileComp->data
+		         + resLevel->bx1[1] - resLevel->bx0[1];
+	    } else if (sb == 1) { // (NL-r+1)LH
+	      sbCoeffs = tileComp->data
+		         + (resLevel->by1[0] - resLevel->by0[0]) * tileComp->w;
+	    } else { // (NL-r+1)HH
+	      sbCoeffs = tileComp->data
+		         + (resLevel->by1[0] - resLevel->by0[0]) * tileComp->w
+		         + resLevel->bx1[1] - resLevel->bx0[1];
+	    }
 	    cb = subband->cbs;
 	    for (cbY = 0; cbY < subband->nYCBs; ++cbY) {
 	      for (cbX = 0; cbX < subband->nXCBs; ++cbX) {
@@ -1901,18 +2025,21 @@ GBool JPXStream::readTilePart() {
 		cb->lBlock = 3;
 		cb->nextPass = jpxPassCleanup;
 		cb->nZeroBitPlanes = 0;
-		cb->coeffs =
-		    (JPXCoeff *)gmallocn((1 << (tileComp->codeBlockW
-						+ tileComp->codeBlockH)),
-					 sizeof(JPXCoeff));
-		for (cbi = 0;
-		     cbi < (Guint)(1 << (tileComp->codeBlockW
-					 + tileComp->codeBlockH));
-		     ++cbi) {
-		  cb->coeffs[cbi].flags = 0;
-		  cb->coeffs[cbi].len = 0;
-		  cb->coeffs[cbi].mag = 0;
+		cb->dataLenSize = 1;
+		cb->dataLen = (Guint *)gmalloc(sizeof(Guint));
+		cb->coeffs = sbCoeffs
+		             + (cb->y0 - subband->y0) * tileComp->w
+		             + (cb->x0 - subband->x0);
+		cb->touched = (char *)gmalloc(1 << (tileComp->codeBlockW
+						    + tileComp->codeBlockH));
+		cb->len = 0;
+		for (cbj = 0; cbj < cb->y1 - cb->y0; ++cbj) {
+		  for (cbi = 0; cbi < cb->x1 - cb->x0; ++cbi) {
+		    cb->coeffs[cbj * tileComp->w + cbi] = 0;
+		  }
 		}
+		memset(cb->touched, 0,
+		       (1 << (tileComp->codeBlockW + tileComp->codeBlockH)));
 		cb->arithDecoder = NULL;
 		cb->stats = NULL;
 		++cb;
@@ -1958,6 +2085,9 @@ GBool JPXStream::readTilePartData(Guint tileIdx,
 
     // setup
     startBitBuf(tilePartLen);
+    if (tileComp->style & 0x02) {
+      skipSOP();
+    }
 
     // zero-length flag
     if (!readBits(1, &bits)) {
@@ -2116,19 +2246,41 @@ GBool JPXStream::readTilePartData(Guint tileIdx,
 		++cb->lBlock;
 	      }
 
-	      // length of compressed data
-	      //~ deal with multiple codeword segments
-	      for (n = cb->lBlock, i = cb->nCodingPasses >> 1;
-		   i;
-		   ++n, i >>= 1) ;
-	      if (!readBits(n, &cb->dataLen)) {
-		goto err;
+	      // one codeword segment for each of the coding passes
+	      if (tileComp->codeBlockStyle & 0x04) {
+		if (cb->nCodingPasses > cb->dataLenSize) {
+		  cb->dataLenSize = cb->nCodingPasses;
+		  cb->dataLen = (Guint *)greallocn(cb->dataLen,
+						   cb->dataLenSize,
+						   sizeof(Guint));
+		}
+
+		// read the lengths
+		for (i = 0; i < cb->nCodingPasses; ++i) {
+		  if (!readBits(cb->lBlock, &cb->dataLen[i])) {
+		    goto err;
+		  }
+		}
+
+	      // one codeword segment for all of the coding passes
+	      } else {
+
+		// read the length
+		for (n = cb->lBlock, i = cb->nCodingPasses >> 1;
+		     i;
+		     ++n, i >>= 1) ;
+		if (!readBits(n, &cb->dataLen[0])) {
+		  goto err;
+		}
 	      }
 	    }
 	  }
 	}
       }
     }
+    if (tileComp->style & 0x04) {
+      skipEPH();
+    }
     tilePartLen = finishBitBuf();
 
     //----- packet data
@@ -2143,7 +2295,13 @@ GBool JPXStream::readTilePartData(Guint tileIdx,
 				   tile->res, sb, cb)) {
 	      return gFalse;
 	    }
-	    tilePartLen -= cb->dataLen;
+	    if (tileComp->codeBlockStyle & 0x04) {
+	      for (i = 0; i < cb->nCodingPasses; ++i) {
+		tilePartLen -= cb->dataLen[i];
+	      }
+	    } else {
+	      tilePartLen -= cb->dataLen[0];
+	    }
 	    cb->seen = gTrue;
 	  }
 	}
@@ -2232,18 +2390,20 @@ GBool JPXStream::readCodeBlockData(JPXTileComp *tileComp,
 				   JPXSubband *subband,
 				   Guint res, Guint sb,
 				   JPXCodeBlock *cb) {
-  JPXCoeff *coeff0, *coeff1, *coeff;
+  int *coeff0, *coeff1, *coeff;
+  char *touched0, *touched1, *touched;
   Guint horiz, vert, diag, all, cx, xorBit;
-  int horizSign, vertSign;
-  Guint i, x, y0, y1, y2;
+  int horizSign, vertSign, bit;
+  int segSym;
+  Guint i, x, y0, y1;
 
   if (cb->arithDecoder) {
     cover(63);
-    cb->arithDecoder->restart(cb->dataLen);
+    cb->arithDecoder->restart(cb->dataLen[0]);
   } else {
     cover(64);
     cb->arithDecoder = new JArithmeticDecoder();
-    cb->arithDecoder->setStream(str, cb->dataLen);
+    cb->arithDecoder->setStream(bufStr, cb->dataLen[0]);
     cb->arithDecoder->start();
     cb->stats = new JArithmeticDecoderStats(jpxNContexts);
     cb->stats->setEntry(jpxContextSigProp, 4, 0);
@@ -2252,78 +2412,80 @@ GBool JPXStream::readCodeBlockData(JPXTileComp *tileComp,
   }
 
   for (i = 0; i < cb->nCodingPasses; ++i) {
+    if ((tileComp->codeBlockStyle & 0x04) && i > 0) {
+      cb->arithDecoder->setStream(bufStr, cb->dataLen[i]);
+      cb->arithDecoder->start();
+    }
+
     switch (cb->nextPass) {
 
     //----- significance propagation pass
     case jpxPassSigProp:
       cover(65);
-      for (y0 = cb->y0, coeff0 = cb->coeffs;
+      for (y0 = cb->y0, coeff0 = cb->coeffs, touched0 = cb->touched;
 	   y0 < cb->y1;
-	   y0 += 4, coeff0 += 4 << tileComp->codeBlockW) {
-	for (x = cb->x0, coeff1 = coeff0;
+	   y0 += 4, coeff0 += 4 * tileComp->w,
+	     touched0 += 4 << tileComp->codeBlockW) {
+	for (x = cb->x0, coeff1 = coeff0, touched1 = touched0;
 	     x < cb->x1;
-	     ++x, ++coeff1) {
-	  for (y1 = 0, coeff = coeff1;
+	     ++x, ++coeff1, ++touched1) {
+	  for (y1 = 0, coeff = coeff1, touched = touched1;
 	       y1 < 4 && y0+y1 < cb->y1;
-	       ++y1, coeff += tileComp->cbW) {
-	    if (!(coeff->flags & jpxCoeffSignificant)) {
+	       ++y1, coeff += tileComp->w, touched += tileComp->cbW) {
+	    if (!*coeff) {
 	      horiz = vert = diag = 0;
 	      horizSign = vertSign = 2;
 	      if (x > cb->x0) {
-		if (coeff[-1].flags & jpxCoeffSignificant) {
+		if (coeff[-1]) {
 		  ++horiz;
-		  horizSign += (coeff[-1].flags & jpxCoeffSign) ? -1 : 1;
+		  horizSign += coeff[-1] < 0 ? -1 : 1;
 		}
 		if (y0+y1 > cb->y0) {
-		  diag += (coeff[-(int)tileComp->cbW - 1].flags
-			   >> jpxCoeffSignificantB) & 1;
+		  diag += coeff[-(int)tileComp->w - 1] ? 1 : 0;
 		}
-		if (y0+y1 < cb->y1 - 1) {
-		  diag += (coeff[tileComp->cbW - 1].flags
-			   >> jpxCoeffSignificantB) & 1;
+		if (y0+y1 < cb->y1 - 1 &&
+		    (!(tileComp->codeBlockStyle & 0x08) || y1 < 3)) {
+		  diag += coeff[tileComp->w - 1] ? 1 : 0;
 		}
 	      }
 	      if (x < cb->x1 - 1) {
-		if (coeff[1].flags & jpxCoeffSignificant) {
+		if (coeff[1]) {
 		  ++horiz;
-		  horizSign += (coeff[1].flags & jpxCoeffSign) ? -1 : 1;
+		  horizSign += coeff[1] < 0 ? -1 : 1;
 		}
 		if (y0+y1 > cb->y0) {
-		  diag += (coeff[-(int)tileComp->cbW + 1].flags
-			   >> jpxCoeffSignificantB) & 1;
+		  diag += coeff[-(int)tileComp->w + 1] ? 1 : 0;
 		}
-		if (y0+y1 < cb->y1 - 1) {
-		  diag += (coeff[tileComp->cbW + 1].flags
-			   >> jpxCoeffSignificantB) & 1;
+		if (y0+y1 < cb->y1 - 1 &&
+		    (!(tileComp->codeBlockStyle & 0x08) || y1 < 3)) {
+		  diag += coeff[tileComp->w + 1] ? 1 : 0;
 		}
 	      }
 	      if (y0+y1 > cb->y0) {
-		if (coeff[-(int)tileComp->cbW].flags & jpxCoeffSignificant) {
+		if (coeff[-(int)tileComp->w]) {
 		  ++vert;
-		  vertSign += (coeff[-(int)tileComp->cbW].flags & jpxCoeffSign)
-		              ? -1 : 1;
+		  vertSign += coeff[-(int)tileComp->w] < 0 ? -1 : 1;
 		}
 	      }
-	      if (y0+y1 < cb->y1 - 1) {
-		if (coeff[tileComp->cbW].flags & jpxCoeffSignificant) {
+	      if (y0+y1 < cb->y1 - 1 &&
+		  (!(tileComp->codeBlockStyle & 0x08) || y1 < 3)) {
+		if (coeff[tileComp->w]) {
 		  ++vert;
-		  vertSign += (coeff[tileComp->cbW].flags & jpxCoeffSign)
-		              ? -1 : 1;
+		  vertSign += coeff[tileComp->w] < 0 ? -1 : 1;
 		}
 	      }
 	      cx = sigPropContext[horiz][vert][diag][res == 0 ? 1 : sb];
 	      if (cx != 0) {
 		if (cb->arithDecoder->decodeBit(cx, cb->stats)) {
-		  coeff->flags |= jpxCoeffSignificant | jpxCoeffFirstMagRef;
-		  coeff->mag = (coeff->mag << 1) | 1;
 		  cx = signContext[horizSign][vertSign][0];
 		  xorBit = signContext[horizSign][vertSign][1];
 		  if (cb->arithDecoder->decodeBit(cx, cb->stats) ^ xorBit) {
-		    coeff->flags |= jpxCoeffSign;
+		    *coeff = -1;
+		  } else {
+		    *coeff = 1;
 		  }
 		}
-		++coeff->len;
-		coeff->flags |= jpxCoeffTouched;
+		*touched = 1;
 	      }
 	    }
 	  }
@@ -2335,58 +2497,57 @@ GBool JPXStream::readCodeBlockData(JPXTileComp *tileComp,
     //----- magnitude refinement pass
     case jpxPassMagRef:
       cover(66);
-      for (y0 = cb->y0, coeff0 = cb->coeffs;
+      for (y0 = cb->y0, coeff0 = cb->coeffs, touched0 = cb->touched;
 	   y0 < cb->y1;
-	   y0 += 4, coeff0 += 4 << tileComp->codeBlockW) {
-	for (x = cb->x0, coeff1 = coeff0;
+	   y0 += 4, coeff0 += 4 * tileComp->w,
+	     touched0 += 4 << tileComp->codeBlockW) {
+	for (x = cb->x0, coeff1 = coeff0, touched1 = touched0;
 	     x < cb->x1;
-	     ++x, ++coeff1) {
-	  for (y1 = 0, coeff = coeff1;
+	     ++x, ++coeff1, ++touched1) {
+	  for (y1 = 0, coeff = coeff1, touched = touched1;
 	       y1 < 4 && y0+y1 < cb->y1;
-	       ++y1, coeff += tileComp->cbW) {
-	    if ((coeff->flags & jpxCoeffSignificant) &&
-		!(coeff->flags & jpxCoeffTouched)) {
-	      if (coeff->flags & jpxCoeffFirstMagRef) {
+	       ++y1, coeff += tileComp->w, touched += tileComp->cbW) {
+	    if (*coeff && !*touched) {
+	      if (*coeff == 1 || *coeff == -1) {
 		all = 0;
 		if (x > cb->x0) {
-		  all += (coeff[-1].flags >> jpxCoeffSignificantB) & 1;
+		  all += coeff[-1] ? 1 : 0;
 		  if (y0+y1 > cb->y0) {
-		    all += (coeff[-(int)tileComp->cbW - 1].flags
-			    >> jpxCoeffSignificantB) & 1;
+		    all += coeff[-(int)tileComp->w - 1] ? 1 : 0;
 		  }
-		  if (y0+y1 < cb->y1 - 1) {
-		    all += (coeff[tileComp->cbW - 1].flags
-			    >> jpxCoeffSignificantB) & 1;
+		  if (y0+y1 < cb->y1 - 1 &&
+		      (!(tileComp->codeBlockStyle & 0x08) || y1 < 3)) {
+		    all += coeff[tileComp->w - 1] ? 1 : 0;
 		  }
 		}
 		if (x < cb->x1 - 1) {
-		  all += (coeff[1].flags >> jpxCoeffSignificantB) & 1;
+		  all += coeff[1] ? 1 : 0;
 		  if (y0+y1 > cb->y0) {
-		    all += (coeff[-(int)tileComp->cbW + 1].flags
-			    >> jpxCoeffSignificantB) & 1;
+		    all += coeff[-(int)tileComp->w + 1] ? 1 : 0;
 		  }
-		  if (y0+y1 < cb->y1 - 1) {
-		    all += (coeff[tileComp->cbW + 1].flags
-			    >> jpxCoeffSignificantB) & 1;
+		  if (y0+y1 < cb->y1 - 1 &&
+		      (!(tileComp->codeBlockStyle & 0x08) || y1 < 3)) {
+		    all += coeff[tileComp->w + 1] ? 1 : 0;
 		  }
 		}
 		if (y0+y1 > cb->y0) {
-		  all += (coeff[-(int)tileComp->cbW].flags
-			  >> jpxCoeffSignificantB) & 1;
+		  all += coeff[-(int)tileComp->w] ? 1 : 0;
 		}
-		if (y0+y1 < cb->y1 - 1) {
-		  all += (coeff[tileComp->cbW].flags
-			  >> jpxCoeffSignificantB) & 1;
+		if (y0+y1 < cb->y1 - 1 &&
+		    (!(tileComp->codeBlockStyle & 0x08) || y1 < 3)) {
+		  all += coeff[tileComp->w] ? 1 : 0;
 		}
 		cx = all ? 15 : 14;
 	      } else {
 		cx = 16;
 	      }
-	      coeff->mag = (coeff->mag << 1) |
-		           cb->arithDecoder->decodeBit(cx, cb->stats);
-	      ++coeff->len;
-	      coeff->flags |= jpxCoeffTouched;
-	      coeff->flags &= ~jpxCoeffFirstMagRef;
+	      bit = cb->arithDecoder->decodeBit(cx, cb->stats);
+	      if (*coeff < 0) {
+		*coeff = (*coeff << 1) - bit;
+	      } else {
+		*coeff = (*coeff << 1) + bit;
+	      }
+	      *touched = 1;
 	    }
 	  }
 	}
@@ -2397,145 +2558,153 @@ GBool JPXStream::readCodeBlockData(JPXTileComp *tileComp,
     //----- cleanup pass
     case jpxPassCleanup:
       cover(67);
-      for (y0 = cb->y0, coeff0 = cb->coeffs;
+      for (y0 = cb->y0, coeff0 = cb->coeffs, touched0 = cb->touched;
 	   y0 < cb->y1;
-	   y0 += 4, coeff0 += 4 << tileComp->codeBlockW) {
-	for (x = cb->x0, coeff1 = coeff0;
+	   y0 += 4, coeff0 += 4 * tileComp->w,
+	     touched0 += 4 << tileComp->codeBlockW) {
+	for (x = cb->x0, coeff1 = coeff0, touched1 = touched0;
 	     x < cb->x1;
-	     ++x, ++coeff1) {
+	     ++x, ++coeff1, ++touched1) {
 	  y1 = 0;
 	  if (y0 + 3 < cb->y1 &&
-	      !(coeff1->flags & jpxCoeffTouched) &&
-	      !(coeff1[tileComp->cbW].flags & jpxCoeffTouched) &&
-	      !(coeff1[2 * tileComp->cbW].flags & jpxCoeffTouched) &&
-	      !(coeff1[3 * tileComp->cbW].flags & jpxCoeffTouched) &&
+	      !(*touched1) &&
+	      !(touched1[tileComp->cbW]) &&
+	      !(touched1[2 * tileComp->cbW]) &&
+	      !(touched1[3 * tileComp->cbW]) &&
 	      (x == cb->x0 || y0 == cb->y0 ||
-	       !(coeff1[-(int)tileComp->cbW - 1].flags
-		 & jpxCoeffSignificant)) &&
+	       !coeff1[-(int)tileComp->w - 1]) &&
 	      (y0 == cb->y0 ||
-	       !(coeff1[-(int)tileComp->cbW].flags
-		 & jpxCoeffSignificant)) &&
+	       !coeff1[-(int)tileComp->w]) &&
 	      (x == cb->x1 - 1 || y0 == cb->y0 ||
-	       !(coeff1[-(int)tileComp->cbW + 1].flags
-		 & jpxCoeffSignificant)) &&
+	       !coeff1[-(int)tileComp->w + 1]) &&
 	      (x == cb->x0 ||
-	       (!(coeff1[-1].flags & jpxCoeffSignificant) &&
-		!(coeff1[tileComp->cbW - 1].flags
-		  & jpxCoeffSignificant) &&
-		!(coeff1[2 * tileComp->cbW - 1].flags
-		  & jpxCoeffSignificant) && 
-		!(coeff1[3 * tileComp->cbW - 1].flags
-		  & jpxCoeffSignificant))) &&
+	       (!coeff1[-1] &&
+		!coeff1[tileComp->w - 1] &&
+		!coeff1[2 * tileComp->w - 1] && 
+		!coeff1[3 * tileComp->w - 1])) &&
 	      (x == cb->x1 - 1 ||
-	       (!(coeff1[1].flags & jpxCoeffSignificant) &&
-		!(coeff1[tileComp->cbW + 1].flags
-		  & jpxCoeffSignificant) &&
-		!(coeff1[2 * tileComp->cbW + 1].flags
-		  & jpxCoeffSignificant) &&
-		!(coeff1[3 * tileComp->cbW + 1].flags
-		  & jpxCoeffSignificant))) &&
-	      (x == cb->x0 || y0+4 == cb->y1 ||
-	       !(coeff1[4 * tileComp->cbW - 1].flags & jpxCoeffSignificant)) &&
-	      (y0+4 == cb->y1 ||
-	       !(coeff1[4 * tileComp->cbW].flags & jpxCoeffSignificant)) &&
-	      (x == cb->x1 - 1 || y0+4 == cb->y1 ||
-	       !(coeff1[4 * tileComp->cbW + 1].flags
-		 & jpxCoeffSignificant))) {
+	       (!coeff1[1] &&
+		!coeff1[tileComp->w + 1] &&
+		!coeff1[2 * tileComp->w + 1] &&
+		!coeff1[3 * tileComp->w + 1])) &&
+	      ((tileComp->codeBlockStyle & 0x08) ||
+	       ((x == cb->x0 || y0+4 == cb->y1 ||
+		 !coeff1[4 * tileComp->w - 1]) &&
+		(y0+4 == cb->y1 ||
+		 !coeff1[4 * tileComp->w]) &&
+		(x == cb->x1 - 1 || y0+4 == cb->y1 ||
+		 !coeff1[4 * tileComp->w + 1])))) {
 	    if (cb->arithDecoder->decodeBit(jpxContextRunLength, cb->stats)) {
 	      y1 = cb->arithDecoder->decodeBit(jpxContextUniform, cb->stats);
 	      y1 = (y1 << 1) |
 		   cb->arithDecoder->decodeBit(jpxContextUniform, cb->stats);
-	      for (y2 = 0, coeff = coeff1;
-		   y2 < y1;
-		   ++y2, coeff += tileComp->cbW) {
-		++coeff->len;
-	      }
-	      coeff->flags |= jpxCoeffSignificant | jpxCoeffFirstMagRef;
-	      coeff->mag = (coeff->mag << 1) | 1;
-	      ++coeff->len;
+	      coeff = &coeff1[y1 * tileComp->w];
 	      cx = signContext[2][2][0];
 	      xorBit = signContext[2][2][1];
 	      if (cb->arithDecoder->decodeBit(cx, cb->stats) ^ xorBit) {
-		coeff->flags |= jpxCoeffSign;
+		*coeff = -1;
+	      } else {
+		*coeff = 1;
 	      }
 	      ++y1;
 	    } else {
-	      for (y1 = 0, coeff = coeff1;
-		   y1 < 4;
-		   ++y1, coeff += tileComp->cbW) {
-		++coeff->len;
-	      }
 	      y1 = 4;
 	    }
 	  }
-	  for (coeff = &coeff1[y1 << tileComp->codeBlockW];
+	  for (coeff = &coeff1[y1 * tileComp->w],
+		 touched = &touched1[y1 << tileComp->codeBlockW];
 	       y1 < 4 && y0 + y1 < cb->y1;
-	       ++y1, coeff += tileComp->cbW) {
-	    if (!(coeff->flags & jpxCoeffTouched)) {
+	       ++y1, coeff += tileComp->w, touched += tileComp->cbW) {
+	    if (!*touched) {
 	      horiz = vert = diag = 0;
 	      horizSign = vertSign = 2;
 	      if (x > cb->x0) {
-		if (coeff[-1].flags & jpxCoeffSignificant) {
+		if (coeff[-1]) {
 		  ++horiz;
-		  horizSign += (coeff[-1].flags & jpxCoeffSign) ? -1 : 1;
+		  horizSign += coeff[-1] < 0 ? -1 : 1;
 		}
 		if (y0+y1 > cb->y0) {
-		  diag += (coeff[-(int)tileComp->cbW - 1].flags
-			   >> jpxCoeffSignificantB) & 1;
+		  diag += coeff[-(int)tileComp->w - 1] ? 1 : 0;
 		}
-		if (y0+y1 < cb->y1 - 1) {
-		  diag += (coeff[tileComp->cbW - 1].flags
-			   >> jpxCoeffSignificantB) & 1;
+		if (y0+y1 < cb->y1 - 1 &&
+		    (!(tileComp->codeBlockStyle & 0x08) || y1 < 3)) {
+		  diag += coeff[tileComp->w - 1] ? 1 : 0;
 		}
 	      }
 	      if (x < cb->x1 - 1) {
-		if (coeff[1].flags & jpxCoeffSignificant) {
+		if (coeff[1]) {
 		  ++horiz;
-		  horizSign += (coeff[1].flags & jpxCoeffSign) ? -1 : 1;
+		  horizSign += coeff[1] < 0 ? -1 : 1;
 		}
 		if (y0+y1 > cb->y0) {
-		  diag += (coeff[-(int)tileComp->cbW + 1].flags
-			   >> jpxCoeffSignificantB) & 1;
+		  diag += coeff[-(int)tileComp->w + 1] ? 1 : 0;
 		}
-		if (y0+y1 < cb->y1 - 1) {
-		  diag += (coeff[tileComp->cbW + 1].flags
-			   >> jpxCoeffSignificantB) & 1;
+		if (y0+y1 < cb->y1 - 1 &&
+		    (!(tileComp->codeBlockStyle & 0x08) || y1 < 3)) {
+		  diag += coeff[tileComp->w + 1] ? 1 : 0;
 		}
 	      }
 	      if (y0+y1 > cb->y0) {
-		if (coeff[-(int)tileComp->cbW].flags & jpxCoeffSignificant) {
+		if (coeff[-(int)tileComp->w]) {
 		  ++vert;
-		  vertSign += (coeff[-(int)tileComp->cbW].flags & jpxCoeffSign)
-		              ? -1 : 1;
+		  vertSign += coeff[-(int)tileComp->w] < 0 ? -1 : 1;
 		}
 	      }
-	      if (y0+y1 < cb->y1 - 1) {
-		if (coeff[tileComp->cbW].flags & jpxCoeffSignificant) {
+	      if (y0+y1 < cb->y1 - 1 &&
+		  (!(tileComp->codeBlockStyle & 0x08) || y1 < 3)) {
+		if (coeff[tileComp->w]) {
 		  ++vert;
-		  vertSign += (coeff[tileComp->cbW].flags & jpxCoeffSign)
-		              ? -1 : 1;
+		  vertSign += coeff[tileComp->w] < 0 ? -1 : 1;
 		}
 	      }
 	      cx = sigPropContext[horiz][vert][diag][res == 0 ? 1 : sb];
 	      if (cb->arithDecoder->decodeBit(cx, cb->stats)) {
-		coeff->flags |= jpxCoeffSignificant | jpxCoeffFirstMagRef;
-		coeff->mag = (coeff->mag << 1) | 1;
 		cx = signContext[horizSign][vertSign][0];
 		xorBit = signContext[horizSign][vertSign][1];
 		if (cb->arithDecoder->decodeBit(cx, cb->stats) ^ xorBit) {
-		  coeff->flags |= jpxCoeffSign;
+		  *coeff = -1;
+		} else {
+		  *coeff = 1;
 		}
 	      }
-	      ++coeff->len;
 	    } else {
-	      coeff->flags &= ~jpxCoeffTouched;
+	      *touched = 0;
 	    }
 	  }
 	}
       }
+      ++cb->len;
+      // look for a segmentation symbol
+      if (tileComp->codeBlockStyle & 0x20) {
+	segSym = cb->arithDecoder->decodeBit(jpxContextUniform,
+					     cb->stats) << 3;
+	segSym |= cb->arithDecoder->decodeBit(jpxContextUniform,
+					      cb->stats) << 2;
+	segSym |= cb->arithDecoder->decodeBit(jpxContextUniform,
+					      cb->stats) << 1;
+	segSym |= cb->arithDecoder->decodeBit(jpxContextUniform,
+					      cb->stats);
+	if (segSym != 0x0a) {
+	  // in theory this should be a fatal error, but it seems to
+	  // be problematic
+	  error(errSyntaxWarning, getPos(),
+		"Missing or invalid segmentation symbol in JPX stream");
+	}
+      }
       cb->nextPass = jpxPassSigProp;
       break;
     }
+
+    if (tileComp->codeBlockStyle & 0x02) {
+      cb->stats->reset();
+      cb->stats->setEntry(jpxContextSigProp, 4, 0);
+      cb->stats->setEntry(jpxContextRunLength, 3, 0);
+      cb->stats->setEntry(jpxContextUniform, 46, 0);
+    }
+
+    if (tileComp->codeBlockStyle & 0x04) {
+      cb->arithDecoder->cleanup();
+    }
   }
 
   cb->arithDecoder->cleanup();
@@ -2549,13 +2718,12 @@ void JPXStream::inverseTransform(JPXTileComp *tileComp) {
   JPXPrecinct *precinct;
   JPXSubband *subband;
   JPXCodeBlock *cb;
-  JPXCoeff *coeff0, *coeff;
+  int *coeff0, *coeff;
+  char *touched0, *touched;
   Guint qStyle, guard, eps, shift;
   int shift2;
   double mu;
   int val;
-  int *dataPtr;
-  Guint nx0, ny0, nx1, ny1;
   Guint r, cbX, cbY, x, y;
 
   cover(68);
@@ -2584,24 +2752,26 @@ void JPXStream::inverseTransform(JPXTileComp *tileComp) {
     shift += fracBits;
   }
 
-  // copy (NL)LL into the upper-left corner of the data array, doing
-  // the fixed point adjustment and dequantization along the way
+  // do fixed point adjustment and dequantization on (NL)LL
   cb = subband->cbs;
   for (cbY = 0; cbY < subband->nYCBs; ++cbY) {
     for (cbX = 0; cbX < subband->nXCBs; ++cbX) {
-      for (y = cb->y0, coeff0 = cb->coeffs;
+      for (y = cb->y0, coeff0 = cb->coeffs, touched0 = cb->touched;
 	   y < cb->y1;
-	   ++y, coeff0 += tileComp->cbW) {
-	dataPtr = &tileComp->data[(y - subband->y0)
-				  * (tileComp->x1 - tileComp->x0)
-				  + (cb->x0 - subband->x0)];
-	for (x = cb->x0, coeff = coeff0; x < cb->x1; ++x, ++coeff) {
-	  val = (int)coeff->mag;
+	   ++y, coeff0 += tileComp->w, touched0 += tileComp->cbW) {
+	for (x = cb->x0, coeff = coeff0, touched = touched0;
+	     x < cb->x1;
+	     ++x, ++coeff, ++touched) {
+	  val = *coeff;
 	  if (val != 0) {
-	    shift2 = shift - (cb->nZeroBitPlanes + coeff->len);
+	    shift2 = shift - (cb->nZeroBitPlanes + cb->len + *touched);
 	    if (shift2 > 0) {
 	      cover(94);
-	      val = (val << shift2) + (1 << (shift2 - 1));
+	      if (val < 0) {
+		val = (val << shift2) - (1 << (shift2 - 1));
+	      } else {
+		val = (val << shift2) + (1 << (shift2 - 1));
+	      }
 	    } else {
 	      cover(95);
 	      val >>= -shift2;
@@ -2616,12 +2786,8 @@ void JPXStream::inverseTransform(JPXTileComp *tileComp) {
 	      cover(98);
 	      val = (int)((double)val * mu);
 	    }
-	    if (coeff->flags & jpxCoeffSign) {
-	      cover(99);
-	      val = -val;
-	    }
 	  }
-	  *dataPtr++ = val;
+	  *coeff = val;
 	}
       }
       ++cb;
@@ -2637,61 +2803,33 @@ void JPXStream::inverseTransform(JPXTileComp *tileComp) {
     // tile-component data array -- interleave with (n)HL/LH/HH
     // and inverse transform to get (n-1)LL, which will be stored
     // in the upper-left corner of the tile-component data array
-    if (r == tileComp->nDecompLevels) {
-      cover(72);
-      nx0 = tileComp->x0;
-      ny0 = tileComp->y0;
-      nx1 = tileComp->x1;
-      ny1 = tileComp->y1;
-    } else {
-      cover(73);
-      nx0 = tileComp->resLevels[r+1].x0;
-      ny0 = tileComp->resLevels[r+1].y0;
-      nx1 = tileComp->resLevels[r+1].x1;
-      ny1 = tileComp->resLevels[r+1].y1;
-    }
-    inverseTransformLevel(tileComp, r, resLevel, nx0, ny0, nx1, ny1);
+    inverseTransformLevel(tileComp, r, resLevel);
   }
 }
 
 // Do one level of the inverse transform:
-// - take (n)LL from the tile-component data array
-// - take (n)HL/LH/HH from <resLevel>
-// - leave the resulting (n-1)LL in the tile-component data array
+// - take (n)LL, (n)HL, (n)LH, and (n)HH from the upper-left corner
+//   of the tile-component data array
+// - leave the resulting (n-1)LL in the same place
 void JPXStream::inverseTransformLevel(JPXTileComp *tileComp,
-				      Guint r, JPXResLevel *resLevel,
-				      Guint nx0, Guint ny0,
-				      Guint nx1, Guint ny1) {
+				      Guint r, JPXResLevel *resLevel) {
   JPXPrecinct *precinct;
   JPXSubband *subband;
   JPXCodeBlock *cb;
-  JPXCoeff *coeff0, *coeff;
+  int *coeff0, *coeff;
+  char *touched0, *touched;
   Guint qStyle, guard, eps, shift, t;
   int shift2;
   double mu;
   int val;
-  int *dataPtr;
-  Guint xo, yo;
+  int *dataPtr, *bufPtr;
+  Guint nx1, nx2, ny1, ny2, offset;
   Guint x, y, sb, cbX, cbY;
-  int xx, yy;
 
-  //----- interleave
+  //----- fixed-point adjustment and dequantization
 
-  // spread out LL
-  for (yy = resLevel->y1 - 1; yy >= (int)resLevel->y0; --yy) {
-    for (xx = resLevel->x1 - 1; xx >= (int)resLevel->x0; --xx) {
-      tileComp->data[(2 * yy - ny0) * (tileComp->x1 - tileComp->x0)
-		     + (2 * xx - nx0)] =
-	  tileComp->data[(yy - resLevel->y0) * (tileComp->x1 - tileComp->x0)
-			 + (xx - resLevel->x0)];
-    }
-  }
-
-  // i-quant parameters
   qStyle = tileComp->quantStyle & 0x1f;
   guard = (tileComp->quantStyle >> 5) & 7;
-
-  // interleave HL/LH/HH
   precinct = &resLevel->precincts[0];
   for (sb = 0; sb < 3; ++sb) {
 
@@ -2716,27 +2854,27 @@ void JPXStream::inverseTransformLevel(JPXTileComp *tileComp,
       shift += fracBits;
     }
 
-    // copy the subband coefficients into the data array, doing the
-    // fixed point adjustment and dequantization along the way
-    xo = (sb & 1) ? 0 : 1;
-    yo = (sb > 0) ? 1 : 0;
+    // fixed point adjustment and dequantization
     subband = &precinct->subbands[sb];
     cb = subband->cbs;
     for (cbY = 0; cbY < subband->nYCBs; ++cbY) {
       for (cbX = 0; cbX < subband->nXCBs; ++cbX) {
-	for (y = cb->y0, coeff0 = cb->coeffs;
+	for (y = cb->y0, coeff0 = cb->coeffs, touched0 = cb->touched;
 	     y < cb->y1;
-	     ++y, coeff0 += tileComp->cbW) {
-	  dataPtr = &tileComp->data[(2 * y + yo - ny0)
-				    * (tileComp->x1 - tileComp->x0)
-				    + (2 * cb->x0 + xo - nx0)];
-	  for (x = cb->x0, coeff = coeff0; x < cb->x1; ++x, ++coeff) {
-	    val = (int)coeff->mag;
+	     ++y, coeff0 += tileComp->w, touched0 += tileComp->cbW) {
+	  for (x = cb->x0, coeff = coeff0, touched = touched0;
+	       x < cb->x1;
+	       ++x, ++coeff, ++touched) {
+	    val = *coeff;
 	    if (val != 0) {
-	      shift2 = shift - (cb->nZeroBitPlanes + coeff->len);
+	      shift2 = shift - (cb->nZeroBitPlanes + cb->len + *touched);
 	      if (shift2 > 0) {
 		cover(74);
-		val = (val << shift2) + (1 << (shift2 - 1));
+		if (val < 0) {
+		  val = (val << shift2) - (1 << (shift2 - 1));
+		} else {
+		  val = (val << shift2) + (1 << (shift2 - 1));
+		}
 	      } else {
 		cover(75);
 		val >>= -shift2;
@@ -2750,13 +2888,8 @@ void JPXStream::inverseTransformLevel(JPXTileComp *tileComp,
 		cover(77);
 		val = (int)((double)val * mu);
 	      }
-	      if (coeff->flags & jpxCoeffSign) {
-		cover(78);
-		val = -val;
-	      }
 	    }
-	    *dataPtr = val;
-	    dataPtr += 2;
+	    *coeff = val;
 	  }
 	}
 	++cb;
@@ -2764,32 +2897,112 @@ void JPXStream::inverseTransformLevel(JPXTileComp *tileComp,
     }
   }
 
-  //----- horizontal (row) transforms
-  dataPtr = tileComp->data;
-  for (y = 0; y < ny1 - ny0; ++y) {
-    inverseTransform1D(tileComp, dataPtr, 1, nx0, nx1);
-    dataPtr += tileComp->x1 - tileComp->x0;
+  //----- inverse transform
+
+  // compute the subband bounds:
+  //    0   nx1  nx2
+  //    |    |    |
+  //    v    v    v
+  //   +----+----+
+  //   | LL | HL | <- 0
+  //   +----+----+
+  //   | LH | HH | <- ny1
+  //   +----+----+
+  //               <- ny2
+  nx1 = precinct->subbands[1].x1 - precinct->subbands[1].x0;
+  nx2 = nx1 + precinct->subbands[0].x1 - precinct->subbands[0].x0;
+  ny1 = precinct->subbands[0].y1 - precinct->subbands[0].y0;
+  ny2 = ny1 + precinct->subbands[1].y1 - precinct->subbands[1].y0;
+
+  // horizontal (row) transforms
+  if (r == tileComp->nDecompLevels) {
+    offset = 3 + (tileComp->x0 & 1);
+  } else {
+    offset = 3 + (tileComp->resLevels[r+1].x0 & 1);
+  }
+  for (y = 0, dataPtr = tileComp->data; y < ny2; ++y, dataPtr += tileComp->w) {
+    if (precinct->subbands[0].x0 == precinct->subbands[1].x0) {
+      // fetch LL/LH
+      for (x = 0, bufPtr = tileComp->buf + offset;
+	   x < nx1;
+	   ++x, bufPtr += 2) {
+	*bufPtr = dataPtr[x];
+      }
+      // fetch HL/HH
+      for (x = nx1, bufPtr = tileComp->buf + offset + 1;
+	   x < nx2;
+	   ++x, bufPtr += 2) {
+	*bufPtr = dataPtr[x];
+      }
+    } else {
+      // fetch LL/LH
+      for (x = 0, bufPtr = tileComp->buf + offset + 1;
+	   x < nx1;
+	   ++x, bufPtr += 2) {
+	*bufPtr = dataPtr[x];
+      }
+      // fetch HL/HH
+      for (x = nx1, bufPtr = tileComp->buf + offset;
+	   x < nx2;
+	   ++x, bufPtr += 2) {
+	*bufPtr = dataPtr[x];
+      }
+    }
+    inverseTransform1D(tileComp, tileComp->buf, offset, nx2);
+    for (x = 0, bufPtr = tileComp->buf + offset; x < nx2; ++x, ++bufPtr) {
+      dataPtr[x] = *bufPtr;
+    }
   }
 
-  //----- vertical (column) transforms
-  dataPtr = tileComp->data;
-  for (x = 0; x < nx1 - nx0; ++x) {
-    inverseTransform1D(tileComp, dataPtr,
-		       tileComp->x1 - tileComp->x0, ny0, ny1);
-    ++dataPtr;
+  // vertical (column) transforms
+  if (r == tileComp->nDecompLevels) {
+    offset = 3 + (tileComp->y0 & 1);
+  } else {
+    offset = 3 + (tileComp->resLevels[r+1].y0 & 1);
+  }
+  for (x = 0, dataPtr = tileComp->data; x < nx2; ++x, ++dataPtr) {
+    if (precinct->subbands[1].y0 == precinct->subbands[0].y0) {
+      // fetch LL/HL
+      for (y = 0, bufPtr = tileComp->buf + offset;
+	   y < ny1;
+	   ++y, bufPtr += 2) {
+	*bufPtr = dataPtr[y * tileComp->w];
+      }
+      // fetch LH/HH
+      for (y = ny1, bufPtr = tileComp->buf + offset + 1;
+	   y < ny2;
+	   ++y, bufPtr += 2) {
+	*bufPtr = dataPtr[y * tileComp->w];
+      }
+    } else {
+      // fetch LL/HL
+      for (y = 0, bufPtr = tileComp->buf + offset + 1;
+	   y < ny1;
+	   ++y, bufPtr += 2) {
+	*bufPtr = dataPtr[y * tileComp->w];
+      }
+      // fetch LH/HH
+      for (y = ny1, bufPtr = tileComp->buf + offset;
+	   y < ny2;
+	   ++y, bufPtr += 2) {
+	*bufPtr = dataPtr[y * tileComp->w];
+      }
+    }
+    inverseTransform1D(tileComp, tileComp->buf, offset, ny2);
+    for (y = 0, bufPtr = tileComp->buf + offset; y < ny2; ++y, ++bufPtr) {
+      dataPtr[y * tileComp->w] = *bufPtr;
+    }
   }
 }
 
-void JPXStream::inverseTransform1D(JPXTileComp *tileComp,
-				   int *data, Guint stride,
-				   Guint i0, Guint i1) {
-  int *buf;
-  Guint offset, end, i;
+void JPXStream::inverseTransform1D(JPXTileComp *tileComp, int *data,
+				   Guint offset, Guint n) {
+  Guint end, i;
 
   //----- special case for length = 1
-  if (i1 - i0 == 1) {
+  if (n == 1) {
     cover(79);
-    if (i0 & 1) {
+    if (offset == 4) {
       cover(104);
       *data >>= 1;
     }
@@ -2797,51 +3010,42 @@ void JPXStream::inverseTransform1D(JPXTileComp *tileComp,
   } else {
     cover(80);
 
-    // choose an offset: this makes even buf[] indexes correspond to
-    // odd values of i, and vice versa
-    offset = 3 + (i0 & 1);
-    end = offset + i1 - i0;
-
-    //----- gather
-    buf = tileComp->buf;
-    for (i = 0; i < i1 - i0; ++i) {
-      buf[offset + i] = data[i * stride];
-    }
+    end = offset + n;
 
     //----- extend right
-    buf[end] = buf[end - 2];
-    if (i1 - i0 == 2) {
+    data[end] = data[end - 2];
+    if (n == 2) {
       cover(81);
-      buf[end+1] = buf[offset + 1];
-      buf[end+2] = buf[offset];
-      buf[end+3] = buf[offset + 1];
+      data[end+1] = data[offset + 1];
+      data[end+2] = data[offset];
+      data[end+3] = data[offset + 1];
     } else {
       cover(82);
-      buf[end+1] = buf[end - 3];
-      if (i1 - i0 == 3) {
+      data[end+1] = data[end - 3];
+      if (n == 3) {
 	cover(105);
-	buf[end+2] = buf[offset + 1];
-	buf[end+3] = buf[offset + 2];
+	data[end+2] = data[offset + 1];
+	data[end+3] = data[offset + 2];
       } else {
 	cover(106);
-	buf[end+2] = buf[end - 4];
-	if (i1 - i0 == 4) {
+	data[end+2] = data[end - 4];
+	if (n == 4) {
 	  cover(107);
-	  buf[end+3] = buf[offset + 1];
+	  data[end+3] = data[offset + 1];
 	} else {
 	  cover(108);
-	  buf[end+3] = buf[end - 5];
+	  data[end+3] = data[end - 5];
 	}
       }
     }
 
     //----- extend left
-    buf[offset - 1] = buf[offset + 1];
-    buf[offset - 2] = buf[offset + 2];
-    buf[offset - 3] = buf[offset + 3];
+    data[offset - 1] = data[offset + 1];
+    data[offset - 2] = data[offset + 2];
+    data[offset - 3] = data[offset + 3];
     if (offset == 4) {
       cover(83);
-      buf[0] = buf[offset + 4];
+      data[0] = data[offset + 4];
     }
 
     //----- 9-7 irreversible filter
@@ -2850,27 +3054,27 @@ void JPXStream::inverseTransform1D(JPXTileComp *tileComp,
       cover(84);
       // step 1 (even)
       for (i = 1; i <= end + 2; i += 2) {
-	buf[i] = (int)(idwtKappa * buf[i]);
+	data[i] = (int)(idwtKappa * data[i]);
       }
       // step 2 (odd)
       for (i = 0; i <= end + 3; i += 2) {
-	buf[i] = (int)(idwtIKappa * buf[i]);
+	data[i] = (int)(idwtIKappa * data[i]);
       }
       // step 3 (even)
       for (i = 1; i <= end + 2; i += 2) {
-	buf[i] = (int)(buf[i] - idwtDelta * (buf[i-1] + buf[i+1]));
+	data[i] = (int)(data[i] - idwtDelta * (data[i-1] + data[i+1]));
       }
       // step 4 (odd)
       for (i = 2; i <= end + 1; i += 2) {
-	buf[i] = (int)(buf[i] - idwtGamma * (buf[i-1] + buf[i+1]));
+	data[i] = (int)(data[i] - idwtGamma * (data[i-1] + data[i+1]));
       }
       // step 5 (even)
       for (i = 3; i <= end; i += 2) {
-	buf[i] = (int)(buf[i] - idwtBeta * (buf[i-1] + buf[i+1]));
+	data[i] = (int)(data[i] - idwtBeta * (data[i-1] + data[i+1]));
       }
       // step 6 (odd)
       for (i = 4; i <= end - 1; i += 2) {
-	buf[i] = (int)(buf[i] - idwtAlpha * (buf[i-1] + buf[i+1]));
+	data[i] = (int)(data[i] - idwtAlpha * (data[i-1] + data[i+1]));
       }
 
     //----- 5-3 reversible filter
@@ -2879,18 +3083,13 @@ void JPXStream::inverseTransform1D(JPXTileComp *tileComp,
       cover(85);
       // step 1 (even)
       for (i = 3; i <= end; i += 2) {
-	buf[i] -= (buf[i-1] + buf[i+1] + 2) >> 2;
+	data[i] -= (data[i-1] + data[i+1] + 2) >> 2;
       }
       // step 2 (odd)
       for (i = 4; i < end; i += 2) {
-	buf[i] += (buf[i-1] + buf[i+1]) >> 1;
+	data[i] += (data[i-1] + data[i+1]) >> 1;
       }
     }
-
-    //----- scatter
-    for (i = 0; i < i1 - i0; ++i) {
-      data[i * stride] = buf[offset + i];
-    }
   }
 }
 
@@ -3040,12 +3239,12 @@ int JPXStream::readMarkerHdr(int *segType, Guint *segLen) {
 
   do {
     do {
-      if ((c = str->getChar()) == EOF) {
+      if ((c = bufStr->getChar()) == EOF) {
 	return gFalse;
       }
     } while (c != 0xff);
     do {
-      if ((c = str->getChar()) == EOF) {
+      if ((c = bufStr->getChar()) == EOF) {
 	return gFalse;
       }
     } while (c == 0xff);
@@ -3062,7 +3261,7 @@ int JPXStream::readMarkerHdr(int *segType, Guint *segLen) {
 GBool JPXStream::readUByte(Guint *x) {
   int c0;
 
-  if ((c0 = str->getChar()) == EOF) {
+  if ((c0 = bufStr->getChar()) == EOF) {
     return gFalse;
   }
   *x = (Guint)c0;
@@ -3072,7 +3271,7 @@ GBool JPXStream::readUByte(Guint *x) {
 GBool JPXStream::readByte(int *x) {
  int c0;
 
-  if ((c0 = str->getChar()) == EOF) {
+  if ((c0 = bufStr->getChar()) == EOF) {
     return gFalse;
   }
   *x = c0;
@@ -3085,8 +3284,8 @@ GBool JPXStream::readByte(int *x) {
 GBool JPXStream::readUWord(Guint *x) {
   int c0, c1;
 
-  if ((c0 = str->getChar()) == EOF ||
-      (c1 = str->getChar()) == EOF) {
+  if ((c0 = bufStr->getChar()) == EOF ||
+      (c1 = bufStr->getChar()) == EOF) {
     return gFalse;
   }
   *x = (Guint)((c0 << 8) | c1);
@@ -3096,10 +3295,10 @@ GBool JPXStream::readUWord(Guint *x) {
 GBool JPXStream::readULong(Guint *x) {
   int c0, c1, c2, c3;
 
-  if ((c0 = str->getChar()) == EOF ||
-      (c1 = str->getChar()) == EOF ||
-      (c2 = str->getChar()) == EOF ||
-      (c3 = str->getChar()) == EOF) {
+  if ((c0 = bufStr->getChar()) == EOF ||
+      (c1 = bufStr->getChar()) == EOF ||
+      (c2 = bufStr->getChar()) == EOF ||
+      (c3 = bufStr->getChar()) == EOF) {
     return gFalse;
   }
   *x = (Guint)((c0 << 24) | (c1 << 16) | (c2 << 8) | c3);
@@ -3111,7 +3310,7 @@ GBool JPXStream::readNBytes(int nBytes, GBool signd, int *x) {
 
   y = 0;
   for (i = 0; i < nBytes; ++i) {
-    if ((c = str->getChar()) == EOF) {
+    if ((c = bufStr->getChar()) == EOF) {
       return gFalse;
     }
     y = (y << 8) + c;
@@ -3125,11 +3324,17 @@ GBool JPXStream::readNBytes(int nBytes, GBool signd, int *x) {
   return gTrue;
 }
 
+void JPXStream::startBitBuf(Guint byteCountA) {
+  bitBufLen = 0;
+  bitBufSkip = gFalse;
+  byteCount = byteCountA;
+}
+
 GBool JPXStream::readBits(int nBits, Guint *x) {
   int c;
 
   while (bitBufLen < nBits) {
-    if (byteCount == 0 || (c = str->getChar()) == EOF) {
+    if (byteCount == 0 || (c = bufStr->getChar()) == EOF) {
       return gFalse;
     }
     --byteCount;
@@ -3147,15 +3352,42 @@ GBool JPXStream::readBits(int nBits, Guint *x) {
   return gTrue;
 }
 
-void JPXStream::startBitBuf(Guint byteCountA) {
-  bitBufLen = 0;
-  bitBufSkip = gFalse;
-  byteCount = byteCountA;
+void JPXStream::skipSOP() {
+  int i;
+
+  // SOP occurs at the start of the packet header, so we don't need to
+  // worry about bit-stuff prior to it
+  if (byteCount >= 6 &&
+      bufStr->lookChar(0) == 0xff &&
+      bufStr->lookChar(1) == 0x91) {
+    for (i = 0; i < 6; ++i) {
+      bufStr->getChar();
+    }
+    byteCount -= 6;
+    bitBufLen = 0;
+    bitBufSkip = gFalse;
+  }
+}
+
+void JPXStream::skipEPH() {
+  int i, k;
+
+  k = bitBufSkip ? 1 : 0;
+  if (byteCount >= (Guint)(k + 2) &&
+      bufStr->lookChar(k) == 0xff &&
+      bufStr->lookChar(k + 1) == 0x92) {
+    for (i = 0; i < k + 2; ++i) {
+      bufStr->getChar();
+    }
+    byteCount -= k + 2;
+    bitBufLen = 0;
+    bitBufSkip = gFalse;
+  }
 }
 
 Guint JPXStream::finishBitBuf() {
   if (bitBufSkip) {
-    str->getChar();
+    bufStr->getChar();
     --byteCount;
   }
   return byteCount;
diff --git a/poppler/JPXStream.h b/poppler/JPXStream.h
index ffc3ab9..3085543 100644
--- a/poppler/JPXStream.h
+++ b/poppler/JPXStream.h
@@ -99,24 +99,6 @@ struct JPXTagTreeNode {
 
 //------------------------------------------------------------------------
 
-struct JPXCoeff {
-  Gushort flags;		// flag bits
-  Gushort len;			// number of significant bits in mag
-  Guint mag;			// magnitude value
-};
-
-// coefficient flags
-#define jpxCoeffSignificantB  0
-#define jpxCoeffTouchedB      1
-#define jpxCoeffFirstMagRefB  2
-#define jpxCoeffSignB         7
-#define jpxCoeffSignificant   (1 << jpxCoeffSignificantB)
-#define jpxCoeffTouched       (1 << jpxCoeffTouchedB)
-#define jpxCoeffFirstMagRef   (1 << jpxCoeffFirstMagRefB)
-#define jpxCoeffSign          (1 << jpxCoeffSignB)
-
-//------------------------------------------------------------------------
-
 struct JPXCodeBlock {
   //----- size
   Guint x0, y0, x1, y1;		// bounds
@@ -134,10 +116,13 @@ struct JPXCodeBlock {
   Guint included;		// code-block inclusion in this packet:
 				//   0=not included, 1=included
   Guint nCodingPasses;		// number of coding passes in this pkt
-  Guint dataLen;		// pkt data length
+  Guint *dataLen;		// data lengths (one per codeword segment)
+  Guint dataLenSize;		// size of the dataLen array
 
   //----- coefficient data
-  JPXCoeff *coeffs;		// the coefficients
+  int *coeffs;
+  char *touched;		// coefficient 'touched' flags
+  Gushort len;			// coefficient length
   JArithmeticDecoder		// arithmetic decoder
     *arithDecoder;
   JArithmeticDecoderStats	// arithmetic decoder stats
@@ -212,6 +197,7 @@ struct JPXTileComp {
 
   //----- computed
   Guint x0, y0, x1, y1;		// bounds of the tile-comp, in ref coords
+  Guint w;			// x1 - x0
   Guint cbW;			// code-block width
   Guint cbH;			// code-block height
 
@@ -228,6 +214,8 @@ struct JPXTileComp {
 //------------------------------------------------------------------------
 
 struct JPXTile {
+  GBool init;
+
   //----- from the COD segments (main and tile)
   Guint progOrder;		// progression order
   Guint nLayers;		// number of layers
@@ -302,12 +290,9 @@ private:
 			  JPXCodeBlock *cb);
   void inverseTransform(JPXTileComp *tileComp);
   void inverseTransformLevel(JPXTileComp *tileComp,
-			     Guint r, JPXResLevel *resLevel,
-			     Guint nx0, Guint ny0,
-			     Guint nx1, Guint ny1);
-  void inverseTransform1D(JPXTileComp *tileComp,
-			  int *data, Guint stride,
-			  Guint i0, Guint i1);
+			     Guint r, JPXResLevel *resLevel);
+  void inverseTransform1D(JPXTileComp *tileComp, int *data,
+			  Guint offset, Guint n);
   GBool inverseMultiCompAndDC(JPXTile *tile);
   GBool readBoxHdr(Guint *boxType, Guint *boxLen, Guint *dataLen);
   int readMarkerHdr(int *segType, Guint *segLen);
@@ -316,10 +301,14 @@ private:
   GBool readUWord(Guint *x);
   GBool readULong(Guint *x);
   GBool readNBytes(int nBytes, GBool signd, int *x);
-  GBool readBits(int nBits, Guint *x);
   void startBitBuf(Guint byteCountA);
+  GBool readBits(int nBits, Guint *x);
+  void skipSOP();
+  void skipEPH();
   Guint finishBitBuf();
 
+  BufStream *bufStr;		// buffered stream (for lookahead)
+
   Guint nComps;			// number of components
   Guint *bpc;			// bits per component, for each component
   Guint width, height;		// image size
commit 35bb53feaa2e469253368f03a9835d73aeb1a240
Author: Albert Astals Cid <aacid at kde.org>
Date:   Mon Sep 5 23:20:09 2011 +0200

    xpdf303: Add BufStream

diff --git a/poppler/Stream.cc b/poppler/Stream.cc
index 5f6ba8e..910418e 100644
--- a/poppler/Stream.cc
+++ b/poppler/Stream.cc
@@ -4713,6 +4713,52 @@ EOFStream::~EOFStream() {
 }
 
 //------------------------------------------------------------------------
+// BufStream
+//------------------------------------------------------------------------
+
+BufStream::BufStream(Stream *strA, int bufSizeA): FilterStream(strA) {
+  bufSize = bufSizeA;
+  buf = (int *)gmallocn(bufSize, sizeof(int));
+}
+
+BufStream::~BufStream() {
+  gfree(buf);
+  delete str;
+}
+
+void BufStream::reset() {
+  int i;
+
+  str->reset();
+  for (i = 0; i < bufSize; ++i) {
+    buf[i] = str->getChar();
+  }
+}
+
+int BufStream::getChar() {
+  int c, i;
+
+  c = buf[0];
+  for (i = 1; i < bufSize; ++i) {
+    buf[i-1] = buf[i];
+  }
+  buf[bufSize - 1] = str->getChar();
+  return c;
+}
+
+int BufStream::lookChar() {
+  return buf[0];
+}
+
+int BufStream::lookChar(int idx) {
+  return buf[idx];
+}
+
+GBool BufStream::isBinary(GBool last) {
+  return str->isBinary(gTrue);
+}
+
+//------------------------------------------------------------------------
 // FixedLengthEncoder
 //------------------------------------------------------------------------
 
diff --git a/poppler/Stream.h b/poppler/Stream.h
index 69aa34a..9a5270f 100644
--- a/poppler/Stream.h
+++ b/poppler/Stream.h
@@ -1032,6 +1032,31 @@ public:
 };
 
 //------------------------------------------------------------------------
+// BufStream
+//------------------------------------------------------------------------
+
+class BufStream: public FilterStream {
+public:
+
+  BufStream(Stream *strA, int bufSizeA);
+  virtual ~BufStream();
+  virtual StreamKind getKind() { return strWeird; }
+  virtual void reset();
+  virtual int getChar();
+  virtual int lookChar();
+  virtual GooString *getPSFilter(int psLevel, const char *indent)
+    { return NULL; }
+  virtual GBool isBinary(GBool last = gTrue);
+
+  int lookChar(int idx);
+
+private:
+
+  int *buf;
+  int bufSize;
+};
+
+//------------------------------------------------------------------------
 // FixedLengthEncoder
 //------------------------------------------------------------------------
 
commit 8a9d92fcf05285c1f06bc153aa79d0200d05bbd9
Author: Albert Astals Cid <aacid at kde.org>
Date:   Mon Sep 5 22:57:02 2011 +0200

    xpdf303: CCITTFaxStream header misc fixes

diff --git a/poppler/Stream.h b/poppler/Stream.h
index 138402d..69aa34a 100644
--- a/poppler/Stream.h
+++ b/poppler/Stream.h
@@ -781,7 +781,7 @@ private:
   GBool eof;			// true if at eof
   GBool nextLine2D;		// true if next line uses 2D encoding
   int row;			// current row
-  int inputBuf;			// input buffer
+  Guint inputBuf;		// input buffer
   int inputBits;		// number of bits in input buffer
   int *codingLine;		// coding line changing elements
   int *refLine;			// reference line changing elements
@@ -790,8 +790,8 @@ private:
   int outputBits;		// remaining ouput bits
   int buf;			// character buffer
 
-  void addPixels(int a1, int black);
-  void addPixelsNeg(int a1, int black);
+  void addPixels(int a1, int blackPixels);
+  void addPixelsNeg(int a1, int blackPixels);
   short getTwoDimCode();
   short getWhiteCode();
   short getBlackCode();
commit 22d370c0a1f8c016ebc5a6d8320fe55bfd31c8a7
Author: Albert Astals Cid <aacid at kde.org>
Date:   Mon Sep 5 22:53:45 2011 +0200

    xpdf303: DCTStream misc fixes

diff --git a/poppler/Stream.cc b/poppler/Stream.cc
index 818e0b0..5f6ba8e 100644
--- a/poppler/Stream.cc
+++ b/poppler/Stream.cc
@@ -2764,7 +2764,7 @@ GBool DCTStream::readProgressiveDataUnit(DCTHuffTable *dcHuffTable,
     // ZRL
     if (c == 0xf0) {
       k = 0;
-      while (k < 16) {
+      while (k < 16 && i <= scanInfo.lastCoeff) {
 	j = dctZigZag[i++];
 	if (data[j] == 0) {
 	  ++k;
@@ -2810,10 +2810,10 @@ GBool DCTStream::readProgressiveDataUnit(DCTHuffTable *dcHuffTable,
       if ((amp = readAmp(size)) == 9999) {
 	return gFalse;
       }
-      k = 0;
-      do {
+      j = 0; // make gcc happy
+      for (k = 0; k <= run && i <= scanInfo.lastCoeff; ++k) {
 	j = dctZigZag[i++];
-	while (data[j] != 0) {
+	while (data[j] != 0 && i <= scanInfo.lastCoeff) {
 	  if ((bit = readBit()) == EOF) {
 	    return gFalse;
 	  }
@@ -2822,8 +2822,7 @@ GBool DCTStream::readProgressiveDataUnit(DCTHuffTable *dcHuffTable,
 	  }
 	  j = dctZigZag[i++];
 	}
-	++k;
-      } while (k <= run);
+      }
       data[j] = amp << scanInfo.al;
     }
   }
@@ -3143,6 +3142,9 @@ int DCTStream::readHuffSym(DCTHuffTable *table) {
     ++codeBits;
 
     // look up code
+    if (code < table->firstCode[codeBits]) {
+      break;
+    }
     if (code - table->firstCode[codeBits] < table->numCodes[codeBits]) {
       code -= table->firstCode[codeBits];
       return table->sym[table->firstSym[codeBits] + code];
@@ -3296,6 +3298,15 @@ GBool DCTStream::readBaselineSOF() {
     compInfo[i].hSample = (c >> 4) & 0x0f;
     compInfo[i].vSample = c & 0x0f;
     compInfo[i].quantTable = str->getChar();
+    if (compInfo[i].hSample < 1 || compInfo[i].hSample > 4 ||
+	compInfo[i].vSample < 1 || compInfo[i].vSample > 4) {
+      error(errSyntaxError, getPos(), "Bad DCT sampling factor");
+      return gFalse;
+    }
+    if (compInfo[i].quantTable < 0 || compInfo[i].quantTable > 3) {
+      error(errSyntaxError, getPos(), "Bad DCT quant table selector");
+      return gFalse;
+    }
   }
   progressive = gFalse;
   return gTrue;
@@ -3322,6 +3333,15 @@ GBool DCTStream::readProgressiveSOF() {
     compInfo[i].hSample = (c >> 4) & 0x0f;
     compInfo[i].vSample = c & 0x0f;
     compInfo[i].quantTable = str->getChar();
+    if (compInfo[i].hSample < 1 || compInfo[i].hSample > 4 ||
+	compInfo[i].vSample < 1 || compInfo[i].vSample > 4) {
+      error(errSyntaxError, getPos(), "Bad DCT sampling factor");
+      return gFalse;
+    }
+    if (compInfo[i].quantTable < 0 || compInfo[i].quantTable > 3) {
+      error(errSyntaxError, getPos(), "Bad DCT quant table selector");
+      return gFalse;
+    }
   }
   progressive = gTrue;
   return gTrue;
commit 36d3057546b5a1d717c71b8dcb9773f91e3b5960
Author: Albert Astals Cid <aacid at kde.org>
Date:   Mon Sep 5 22:46:59 2011 +0200

    xpdf303: Add some {}

diff --git a/poppler/Stream.cc b/poppler/Stream.cc
index 2b4e319..818e0b0 100644
--- a/poppler/Stream.cc
+++ b/poppler/Stream.cc
@@ -3136,8 +3136,9 @@ int DCTStream::readHuffSym(DCTHuffTable *table) {
   codeBits = 0;
   do {
     // add a bit to the code
-    if ((bit = readBit()) == EOF)
+    if ((bit = readBit()) == EOF) {
       return 9999;
+    }
     code = (code << 1) + bit;
     ++codeBits;
 
commit 308654eb5dfbb783f29bd645f60c79d5b5fe42c9
Author: Albert Astals Cid <aacid at kde.org>
Date:   Mon Sep 5 22:45:50 2011 +0200

    xpdf303: code1 changed to int in CCITTFaxStream::reset

diff --git a/poppler/Stream.cc b/poppler/Stream.cc
index d8797b5..2b4e319 100644
--- a/poppler/Stream.cc
+++ b/poppler/Stream.cc
@@ -1509,7 +1509,7 @@ void CCITTFaxStream::unfilteredReset () {
 }
 
 void CCITTFaxStream::reset() {
-  short code1;
+  int code1;
 
   unfilteredReset();
 
commit f097dc1f9d580eb1cdc8180d3920fe795493cf89
Author: Albert Astals Cid <aacid at kde.org>
Date:   Mon Sep 5 22:43:16 2011 +0200

    xpdf303: Use 32 bits in CCITTFaxStream::lookBits

diff --git a/poppler/Stream.cc b/poppler/Stream.cc
index ef02196..d8797b5 100644
--- a/poppler/Stream.cc
+++ b/poppler/Stream.cc
@@ -2102,12 +2102,12 @@ short CCITTFaxStream::lookBits(int n) {
       // than are available, but there may still be a valid code in
       // however many bits are available -- we need to return correct
       // data in this case
-      return (inputBuf << (n - inputBits)) & (0xffff >> (16 - n));
+      return (inputBuf << (n - inputBits)) & (0xffffffff >> (32 - n));
     }
     inputBuf = (inputBuf << 8) + c;
     inputBits += 8;
   }
-  return (inputBuf >> (inputBits - n)) & (0xffff >> (16 - n));
+  return (inputBuf >> (inputBits - n)) & (0xffffffff >> (32 - n));
 }
 
 GooString *CCITTFaxStream::getPSFilter(int psLevel, const char *indent) {
commit b5417659042c95891aa549cae396ba4cc6604030
Author: Albert Astals Cid <aacid at kde.org>
Date:   Mon Sep 5 22:40:02 2011 +0200

    xpdf303: Check against lookBits returning EOF

diff --git a/poppler/Stream.cc b/poppler/Stream.cc
index 970c71a..ef02196 100644
--- a/poppler/Stream.cc
+++ b/poppler/Stream.cc
@@ -1923,21 +1923,24 @@ int CCITTFaxStream::lookChar() {
 }
 
 short CCITTFaxStream::getTwoDimCode() {
-  short code;
+  int code;
   const CCITTCode *p;
   int n;
 
   code = 0; // make gcc happy
   if (endOfBlock) {
-    code = lookBits(7);
-    p = &twoDimTab1[code];
-    if (p->bits > 0) {
-      eatBits(p->bits);
-      return p->n;
+    if ((code = lookBits(7)) != EOF) {
+      p = &twoDimTab1[code];
+      if (p->bits > 0) {
+	eatBits(p->bits);
+	return p->n;
+      }
     }
   } else {
     for (n = 1; n <= 7; ++n) {
-      code = lookBits(n);
+      if ((code = lookBits(n)) == EOF) {
+	break;
+      }
       if (n < 7) {
 	code <<= 7 - n;
       }
commit eaf9d31c97a3cc06f4ce94d9190ae1a337634749
Author: Albert Astals Cid <aacid at kde.org>
Date:   Mon Sep 5 22:38:05 2011 +0200

    xpdf303: Set endOfLine to true if code1 is 1

diff --git a/poppler/Stream.cc b/poppler/Stream.cc
index 44f0a08..970c71a 100644
--- a/poppler/Stream.cc
+++ b/poppler/Stream.cc
@@ -1527,6 +1527,7 @@ void CCITTFaxStream::reset() {
   }
   if (code1 == 0x001) {
     eatBits(12);
+    endOfLine = gTrue;
   }
   if (encoding > 0) {
     nextLine2D = !lookBits(1);
commit a654a77e26a6c7d76c318636303f8c636a3d2495
Author: Albert Astals Cid <aacid at kde.org>
Date:   Mon Sep 5 22:36:58 2011 +0200

    xpdf303: Tweaks to CCITTFaxStream::lookChar

diff --git a/poppler/Stream.cc b/poppler/Stream.cc
index afed0eb..44f0a08 100644
--- a/poppler/Stream.cc
+++ b/poppler/Stream.cc
@@ -1575,7 +1575,7 @@ inline void CCITTFaxStream::addPixelsNeg(int a1, int blackPixels) {
 }
 
 int CCITTFaxStream::lookChar() {
-  short code1, code2, code3;
+  int code1, code2, code3;
   int b1i, blackPixels, i, bits;
   GBool gotEOL;
 
@@ -1761,29 +1761,51 @@ int CCITTFaxStream::lookChar() {
       }
     }
 
-    // byte-align the row
-    if (byteAlign) {
-      inputBits &= ~7;
-    }
-
     // check for end-of-line marker, skipping over any extra zero bits
+    // (if EncodedByteAlign is true and EndOfLine is false, there can
+    // be "false" EOL markers -- i.e., if the last n unused bits in
+    // row i are set to zero, and the first 11-n bits in row i+1
+    // happen to be zero -- so we don't look for EOL markers in this
+    // case)
     gotEOL = gFalse;
     if (!endOfBlock && row == rows - 1) {
       eof = gTrue;
-    } else {
+    } else if (endOfLine || !byteAlign) {
       code1 = lookBits(12);
-      while (code1 == 0) {
-	eatBits(1);
-	code1 = lookBits(12);
+      if (endOfLine) {
+	while (code1 != EOF && code1 != 0x001) {
+	  eatBits(1);
+	  code1 = lookBits(12);
+	}
+      } else {
+	while (code1 == 0) {
+	  eatBits(1);
+	  code1 = lookBits(12);
+	}
       }
       if (code1 == 0x001) {
 	eatBits(12);
 	gotEOL = gTrue;
-      } else if (code1 == EOF) {
-	eof = gTrue;
       }
     }
 
+    // byte-align the row
+    // (Adobe apparently doesn't do byte alignment after EOL markers
+    // -- I've seen CCITT image data streams in two different formats,
+    // both with the byteAlign flag set:
+    //   1. xx:x0:01:yy:yy
+    //   2. xx:00:1y:yy:yy
+    // where xx is the previous line, yy is the next line, and colons
+    // separate bytes.)
+    if (byteAlign && !gotEOL) {
+      inputBits &= ~7;
+    }
+
+    // check for end of stream
+    if (lookBits(1) == EOF) {
+      eof = gTrue;
+    }
+
     // get 2D encoding tag
     if (!eof && encoding > 0) {
       nextLine2D = !lookBits(1);
@@ -1791,6 +1813,15 @@ int CCITTFaxStream::lookChar() {
     }
 
     // check for end-of-block marker
+    if (endOfBlock && !endOfLine && byteAlign) {
+      // in this case, we didn't check for an EOL code above, so we
+      // need to check here
+      code1 = lookBits(24);
+      if (code1 == 0x001001) {
+	eatBits(12);
+	gotEOL = gTrue;
+      }
+    }
     if (endOfBlock && gotEOL) {
       code1 = lookBits(12);
       if (code1 == 0x001) {
commit abdf828449cd543e66f326ba862efcb3ca6d342d
Author: Albert Astals Cid <aacid at kde.org>
Date:   Mon Sep 5 22:19:30 2011 +0200

    xpdf303: Remove cygwin workaround

diff --git a/poppler/Stream.cc b/poppler/Stream.cc
index f0a2644..afed0eb 100644
--- a/poppler/Stream.cc
+++ b/poppler/Stream.cc
@@ -794,10 +794,6 @@ void FileStream::setPos(Guint pos, int dir) {
 #endif
     if (pos > size)
       pos = (Guint)size;
-#ifdef __CYGWIN32__
-    //~ work around a bug in cygwin's implementation of fseek
-    rewind(f);
-#endif
 #if HAVE_FSEEKO
     fseeko(f, -(int)pos, SEEK_END);
     bufPos = (Guint)ftello(f);
commit 05ef4227d09381e3a9e8050e447770f44d532386
Author: Albert Astals Cid <aacid at kde.org>
Date:   Mon Sep 5 22:18:33 2011 +0200

    xpdf303: Return false if getLine fails

diff --git a/poppler/Stream.cc b/poppler/Stream.cc
index f82183e..f0a2644 100644
--- a/poppler/Stream.cc
+++ b/poppler/Stream.cc
@@ -444,7 +444,9 @@ GBool ImageStream::getPixel(Guchar *pix) {
   int i;
 
   if (imgIdx >= nVals) {
-    getLine();
+    if (!getLine()) {
+      return gFalse;
+    }
     imgIdx = 0;
   }
   for (i = 0; i < nComps; ++i) {
commit c2d6158bd56328754d77ab8f1bf84d46e6ede773
Author: Albert Astals Cid <aacid at kde.org>
Date:   Mon Sep 5 22:14:39 2011 +0200

    xpdf303: Return NULL if size < 0

diff --git a/poppler/Stream.cc b/poppler/Stream.cc
index 14cba9f..f82183e 100644
--- a/poppler/Stream.cc
+++ b/poppler/Stream.cc
@@ -114,7 +114,7 @@ char *Stream::getLine(char *buf, int size) {
   int i;
   int c;
 
-  if (lookChar() == EOF)
+  if (lookChar() == EOF || size < 0)
     return NULL;
   for (i = 0; i < size - 1; ++i) {
     c = getChar();
commit 04947e1dca858b890302a5a1005b84b34255d670
Author: Albert Astals Cid <aacid at kde.org>
Date:   Mon Sep 5 22:11:24 2011 +0200

    xpdf303: Add -rawdates and print Form information

diff --git a/utils/pdfinfo.cc b/utils/pdfinfo.cc
index 6ea712b..9656478 100644
--- a/utils/pdfinfo.cc
+++ b/utils/pdfinfo.cc
@@ -59,6 +59,7 @@ static int firstPage = 1;
 static int lastPage = 0;
 static GBool printBoxes = gFalse;
 static GBool printMetadata = gFalse;
+static GBool rawDates = gFalse;
 static char textEncName[128] = "";
 static char ownerPassword[33] = "\001";
 static char userPassword[33] = "\001";
@@ -75,6 +76,8 @@ static const ArgDesc argDesc[] = {
    "print the page bounding boxes"},
   {"-meta",   argFlag,     &printMetadata,    0,
    "print the document metadata (XML)"},
+  {"-rawdates", argFlag,   &rawDates,         0,
+   "print the undecoded date strings directly from the PDF file"},
   {"-enc",    argString,   textEncName,    sizeof(textEncName),
    "output text encoding name"},
   {"-listenc",argFlag,     &printEnc,      0,
@@ -102,7 +105,8 @@ int main(int argc, char *argv[]) {
   GooString *ownerPW, *userPW;
   UnicodeMap *uMap;
   Page *page;
-  Object info;
+  Object info, xfa;
+  Object *acroForm;
   char buf[256];
   double w, h, wISO, hISO;
   FILE *f;
@@ -204,8 +208,15 @@ int main(int argc, char *argv[]) {
     printInfoString(info.getDict(), "Author",       "Author:         ", uMap);
     printInfoString(info.getDict(), "Creator",      "Creator:        ", uMap);
     printInfoString(info.getDict(), "Producer",     "Producer:       ", uMap);
-    printInfoDate(info.getDict(),   "CreationDate", "CreationDate:   ");
-    printInfoDate(info.getDict(),   "ModDate",      "ModDate:        ");
+    if (rawDates) {
+      printInfoString(info.getDict(), "CreationDate", "CreationDate:   ",
+		      uMap);
+      printInfoString(info.getDict(), "ModDate",      "ModDate:        ",
+		      uMap);
+    } else {
+      printInfoDate(info.getDict(),   "CreationDate", "CreationDate:   ");
+      printInfoDate(info.getDict(),   "ModDate",      "ModDate:        ");
+    }
   }
   info.free();
 
@@ -213,6 +224,19 @@ int main(int argc, char *argv[]) {
   printf("Tagged:         %s\n",
 	 doc->getStructTreeRoot()->isDict() ? "yes" : "no");
 
+  // print form info
+  if ((acroForm = doc->getCatalog()->getAcroForm())->isDict()) {
+    acroForm->dictLookup("XFA", &xfa);
+    if (xfa.isStream() || xfa.isArray()) {
+      printf("Form:           XFA\n");
+    } else {
+      printf("Form:           AcroForm\n");
+    }
+    xfa.free();
+  } else {
+    printf("Form:           none\n");
+  }
+
   // print page count
   printf("Pages:          %d\n", doc->getNumPages());
 


More information about the poppler mailing list