r23713 by jghali - #15983: update libpgf to 7.19.3

scribus-commit scribus-commit at lists.scribus.net
Fri May 8 16:40:48 UTC 2020


Author: jghali
Date: Fri May  8 16:40:48 2020
New Revision: 23713

URL: http://scribus.net/websvn/listing.php?repname=Scribus&sc=1&rev=23713
Log:
#15983: update libpgf to 7.19.3

Added:
    trunk/Scribus/scribus/third_party/pgf/AUTHORS
    trunk/Scribus/scribus/third_party/pgf/COPYING
    trunk/Scribus/scribus/third_party/pgf/README
Modified:
    trunk/Scribus/scribus/imagedataloaders/scimgdataloader_pgf.cpp
    trunk/Scribus/scribus/third_party/pgf/BitStream.h
    trunk/Scribus/scribus/third_party/pgf/Decoder.cpp
    trunk/Scribus/scribus/third_party/pgf/Decoder.h
    trunk/Scribus/scribus/third_party/pgf/Encoder.cpp
    trunk/Scribus/scribus/third_party/pgf/Encoder.h
    trunk/Scribus/scribus/third_party/pgf/PGFimage.cpp
    trunk/Scribus/scribus/third_party/pgf/PGFimage.h
    trunk/Scribus/scribus/third_party/pgf/PGFplatform.h
    trunk/Scribus/scribus/third_party/pgf/PGFstream.cpp
    trunk/Scribus/scribus/third_party/pgf/PGFstream.h
    trunk/Scribus/scribus/third_party/pgf/PGFtypes.h
    trunk/Scribus/scribus/third_party/pgf/Subband.cpp
    trunk/Scribus/scribus/third_party/pgf/Subband.h
    trunk/Scribus/scribus/third_party/pgf/WaveletTransform.cpp
    trunk/Scribus/scribus/third_party/pgf/WaveletTransform.h

Modified: trunk/Scribus/scribus/imagedataloaders/scimgdataloader_pgf.cpp
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=23713&path=/trunk/Scribus/scribus/imagedataloaders/scimgdataloader_pgf.cpp
==============================================================================
--- trunk/Scribus/scribus/imagedataloaders/scimgdataloader_pgf.cpp	(original)
+++ trunk/Scribus/scribus/imagedataloaders/scimgdataloader_pgf.cpp	Fri May  8 16:40:48 2020
@@ -194,7 +194,7 @@
 				pgfImg.GetBitmap(m_image.bytesPerLine(), (UINT8*)m_image.bits(), m_image.depth(), map);
 			}
 		}
-		pgfImg.Close();
+		pgfImg.Destroy();
 #ifdef WIN32
 		CloseHandle(fd);
 #else

Modified: trunk/Scribus/scribus/third_party/pgf/BitStream.h
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=23713&path=/trunk/Scribus/scribus/third_party/pgf/BitStream.h
==============================================================================
--- trunk/Scribus/scribus/third_party/pgf/BitStream.h	(original)
+++ trunk/Scribus/scribus/third_party/pgf/BitStream.h	Fri May  8 16:40:48 2020
@@ -31,6 +31,7 @@
 
 #include "PGFtypes.h"
 
+//////////////////////////////////////////////////////////////////////
 // constants
 //static const WordWidth = 32;
 //static const WordWidthLog = 5;
@@ -38,7 +39,20 @@
 
 /// @brief Make 64 bit unsigned integer from two 32 bit unsigned integers
 #define MAKEU64(a, b) ((UINT64) (((UINT32) (a)) | ((UINT64) ((UINT32) (b))) << 32)) 
- 
+
+/*
+static UINT8 lMask[] = {
+	0x00,                       // 00000000
+	0x80,                       // 10000000 
+	0xc0,                       // 11000000
+	0xe0,                       // 11100000
+	0xf0,                       // 11110000
+	0xf8,                       // 11111000
+	0xfc,                       // 11111100
+	0xfe,                       // 11111110
+	0xff,                       // 11111111
+};
+*/
 // these procedures have to be inlined because of performance reasons
 
 //////////////////////////////////////////////////////////////////////
@@ -252,7 +266,61 @@
 	}
 	return count;
 }
-
+/*
+//////////////////////////////////////////////////////////////////////
+/// BitCopy: copies k bits from source to destination
+/// Note: only 8 bits are copied at a time, if speed is an issue, a more
+/// complicated but faster 64 bit algorithm should be used.
+inline void BitCopy(const UINT8 *sStream, UINT32 sPos, UINT8 *dStream, UINT32 dPos, UINT32 k) {
+	ASSERT(k > 0);
+
+	div_t divS = div(sPos, 8);
+	div_t divD = div(dPos, 8);
+	UINT32 sOff = divS.rem;
+	UINT32 dOff = divD.rem;
+	INT32 tmp = div(dPos + k - 1, 8).quot;
+
+	const UINT8 *sAddr = sStream + divS.quot;
+	UINT8 *dAddrS = dStream + divD.quot;
+	UINT8 *dAddrE = dStream + tmp;
+	UINT8 eMask;
+
+	UINT8 destSB = *dAddrS;
+	UINT8 destEB = *dAddrE;
+	UINT8 *dAddr;
+	UINT8 prec;
+	INT32 shiftl, shiftr;
+
+	if (dOff > sOff) {
+		prec = 0;
+		shiftr = dOff - sOff;
+		shiftl = 8 - dOff + sOff;
+	} else {
+		prec = *sAddr << (sOff - dOff);
+		shiftr = 8 - sOff + dOff;
+		shiftl = sOff - dOff;
+		sAddr++;
+	}
+
+	for (dAddr = dAddrS; dAddr < dAddrE; dAddr++, sAddr++) {
+		*dAddr = prec | (*sAddr >> shiftr);
+		prec = *sAddr << shiftl;
+	}
+
+	if ((sPos + k)%8 == 0) {
+		*dAddr = prec;
+	} else {
+		*dAddr = prec | (*sAddr >> shiftr);
+	}
+
+	eMask = lMask[dOff];
+	*dAddrS = (destSB & eMask) | (*dAddrS & (~eMask));
+
+	INT32 mind = (dPos + k) % 8;
+	eMask = (mind) ? lMask[mind] : lMask[8];
+	*dAddrE = (destEB & (~eMask)) | (*dAddrE & eMask);
+}
+*/
 //////////////////////////////////////////////////////////////////////
 /// Compute bit position of the next 32-bit word
 /// @param pos current bit stream position
@@ -269,4 +337,5 @@
 inline UINT32 NumberOfWords(UINT32 pos) {
 	return (pos + WordWidth - 1) >> WordWidthLog;
 }
+
 #endif //PGF_BITSTREAM_H

Modified: trunk/Scribus/scribus/third_party/pgf/Decoder.cpp
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=23713&path=/trunk/Scribus/scribus/third_party/pgf/Decoder.cpp
==============================================================================
--- trunk/Scribus/scribus/third_party/pgf/Decoder.cpp	(original)
+++ trunk/Scribus/scribus/third_party/pgf/Decoder.cpp	Fri May  8 16:40:48 2020
@@ -34,7 +34,7 @@
 //////////////////////////////////////////////////////
 // PGF: file structure
 //
-// PGFPreHeader PGFHeader PGFPostHeader LevelLengths Level_n-1 Level_n-2 ... Level_0
+// PGFPreHeader PGFHeader [PGFPostHeader] LevelLengths Level_n-1 Level_n-2 ... Level_0
 // PGFPostHeader ::= [ColorTable] [UserData]
 // LevelLengths  ::= UINT32[nLevels]
 
@@ -69,10 +69,10 @@
 /// @param levelLength The location of the levelLength array. The array is allocated in this method. The caller has to delete this array.
 /// @param userDataPos The stream position of the user data (metadata)
 /// @param useOMP If true, then the decoder will use multi-threading based on openMP
-/// @param skipUserData If true, then user data is not read. In case of available user data, the file position is still returned in userDataPos.
+/// @param userDataPolicy Policy of user data (meta-data) handling while reading PGF headers.
 CDecoder::CDecoder(CPGFStream* stream, PGFPreHeader& preHeader, PGFHeader& header, 
 				   PGFPostHeader& postHeader, UINT32*& levelLength, UINT64& userDataPos,
-				   bool useOMP, bool skipUserData) THROW_
+				   bool useOMP, UINT32 userDataPolicy)
 : m_stream(stream)
 , m_startPos(0)
 , m_streamSizeEstimation(0)
@@ -87,29 +87,6 @@
 
 	int count, expected;
 
-	// set number of threads
-#ifdef LIBPGF_USE_OPENMP 
-	m_macroBlockLen = omp_get_num_procs();
-#else
-	m_macroBlockLen = 1;
-#endif
-	
-	if (useOMP && m_macroBlockLen > 1) {
-#ifdef LIBPGF_USE_OPENMP
-		omp_set_num_threads(m_macroBlockLen);
-#endif
-
-		// create macro block array
-		m_macroBlocks = new(std::nothrow) CMacroBlock*[m_macroBlockLen];
-		if (!m_macroBlocks) ReturnWithError(InsufficientMemory);
-		for (int i=0; i < m_macroBlockLen; i++) m_macroBlocks[i] = new CMacroBlock();
-		m_currentBlock = m_macroBlocks[m_currentBlockIndex];
-	} else {
-		m_macroBlocks = 0;
-		m_macroBlockLen = 1; // there is only one macro block
-		m_currentBlock = new CMacroBlock(); 
-	}
-
 	// store current stream position
 	m_startPos = m_stream->GetPos();
 
@@ -153,33 +130,47 @@
 		if (preHeader.version & PGFROI) ReturnWithError(FormatCannotRead);
 #endif
 
-		int size = preHeader.hSize - HeaderSize;
-
-		if (size > 0) {
+		UINT32 size = preHeader.hSize;
+
+		if (size > HeaderSize) {
+			size -= HeaderSize;
+			count = 0;
+
 			// read post-header
 			if (header.mode == ImageModeIndexedColor) {
-				ASSERT((size_t)size >= ColorTableSize);
+				if (size < ColorTableSize) ReturnWithError(FormatCannotRead);
 				// read color table
 				count = expected = ColorTableSize;
 				m_stream->Read(&count, postHeader.clut);
 				if (count != expected) ReturnWithError(MissingData);
+			}
+
+			if (size > (UINT32)count) {
 				size -= count;
-			}
-
-			if (size > 0) {
+
+				// read/skip user data
+				UserdataPolicy policy = (UserdataPolicy)((userDataPolicy <= MaxUserDataSize) ? UP_CachePrefix : 0xFFFFFFFF - userDataPolicy);
 				userDataPos = m_stream->GetPos();
 				postHeader.userDataLen = size;
-				if (skipUserData) {
+
+				if (policy == UP_Skip) {
+					postHeader.cachedUserDataLen = 0;
+					postHeader.userData = nullptr;
 					Skip(size);
 				} else {
+					postHeader.cachedUserDataLen = (policy == UP_CachePrefix) ? __min(size, userDataPolicy) : size;
+
 					// create user data memory block
-					postHeader.userData = new(std::nothrow) UINT8[postHeader.userDataLen];
+					postHeader.userData = new(std::nothrow) UINT8[postHeader.cachedUserDataLen];
 					if (!postHeader.userData) ReturnWithError(InsufficientMemory);
 
 					// read user data
-					count = expected = postHeader.userDataLen;
+					count = expected = postHeader.cachedUserDataLen;
 					m_stream->Read(&count, postHeader.userData);
 					if (count != expected) ReturnWithError(MissingData);
+
+					// skip remaining user data
+					if (postHeader.cachedUserDataLen < size) Skip(size - postHeader.cachedUserDataLen);
 				}
 			}
 		}
@@ -209,6 +200,30 @@
 
 	// store current stream position
 	m_encodedHeaderLength = UINT32(m_stream->GetPos() - m_startPos);
+
+	// set number of threads
+#ifdef LIBPGF_USE_OPENMP 
+	m_macroBlockLen = omp_get_num_procs();
+#else
+	m_macroBlockLen = 1;
+#endif
+
+	if (useOMP && m_macroBlockLen > 1) {
+#ifdef LIBPGF_USE_OPENMP
+		omp_set_num_threads(m_macroBlockLen);
+#endif
+
+		// create macro block array
+		m_macroBlocks = new(std::nothrow) CMacroBlock*[m_macroBlockLen];
+		if (!m_macroBlocks) ReturnWithError(InsufficientMemory);
+		for (int i = 0; i < m_macroBlockLen; i++) m_macroBlocks[i] = new CMacroBlock();
+		m_currentBlock = m_macroBlocks[m_currentBlockIndex];
+	} else {
+		m_macroBlocks = 0;
+		m_macroBlockLen = 1; // there is only one macro block
+		m_currentBlock = new(std::nothrow) CMacroBlock();
+		if (!m_currentBlock) ReturnWithError(InsufficientMemory);
+	}
 }
 
 /////////////////////////////////////////////////////////////////////
@@ -228,7 +243,7 @@
 /// @param target The target buffer
 /// @param len The number of bytes to read
 /// @return The number of bytes copied to the target buffer
-UINT32 CDecoder::ReadEncodedData(UINT8* target, UINT32 len) const THROW_ {
+UINT32 CDecoder::ReadEncodedData(UINT8* target, UINT32 len) const {
 	ASSERT(m_stream);
 
 	int count = len;
@@ -248,7 +263,7 @@
 /// @param height The height of the rectangle
 /// @param startPos The relative subband position of the top left corner of the rectangular region
 /// @param pitch The number of bytes in row of the subband
-void CDecoder::Partition(CSubband* band, int quantParam, int width, int height, int startPos, int pitch) THROW_ {
+void CDecoder::Partition(CSubband* band, int quantParam, int width, int height, int startPos, int pitch) {
 	ASSERT(band);
 
 	const div_t ww = div(width, LinBlockSize);
@@ -310,12 +325,12 @@
 }
 
 ////////////////////////////////////////////////////////////////////
-// Decode and dequantize HL, and LH band of one level
+// Decodes and dequantizes HL, and LH band of one level
 // LH and HH are interleaved in the codestream and must be split
 // Deccoding and dequantization of HL and LH Band (interleaved) using partitioning scheme
 // partitions the plane in squares of side length InterBlockSize
 // It might throw an IOException.
-void CDecoder::DecodeInterleaved(CWaveletTransform* wtChannel, int level, int quantParam) THROW_ {
+void CDecoder::DecodeInterleaved(CWaveletTransform* wtChannel, int level, int quantParam) {
 	CSubband* hlBand = wtChannel->GetSubband(level, HL);
 	CSubband* lhBand = wtChannel->GetSubband(level, LH);
 	const div_t lhH = div(lhBand->GetHeight(), InterBlockSize);
@@ -429,9 +444,9 @@
 }
 
 ////////////////////////////////////////////////////////////////////
-/// Skip a given number of bytes in the open stream.
+/// Skips a given number of bytes in the open stream.
 /// It might throw an IOException.
-void CDecoder::Skip(UINT64 offset) THROW_ {
+void CDecoder::Skip(UINT64 offset) {
 	m_stream->SetPos(FSFromCurrent, offset);
 }
 
@@ -444,12 +459,12 @@
 /// @param band A subband
 /// @param bandPos A valid position in subband band
 /// @param quantParam The quantization parameter
-void CDecoder::DequantizeValue(CSubband* band, UINT32 bandPos, int quantParam) THROW_ {
+void CDecoder::DequantizeValue(CSubband* band, UINT32 bandPos, int quantParam) {
 	ASSERT(m_currentBlock);
 
 	if (m_currentBlock->IsCompletelyRead()) {
 		// all data of current macro block has been read --> prepare next macro block
-		DecodeTileBuffer();
+		GetNextMacroBlock();
 	}
 	
 	band->SetData(bandPos, m_currentBlock->m_value[m_currentBlock->m_valuePos] << quantParam);
@@ -457,9 +472,9 @@
 }
 
 //////////////////////////////////////////////////////////////////////
-// Read next group of blocks from stream and decodes them into macro blocks
+// Gets next macro block
 // It might throw an IOException.
-void CDecoder::DecodeTileBuffer() THROW_ {
+void CDecoder::GetNextMacroBlock() {
 	// current block has been read --> prepare next current block
 	m_macroBlocksAvailable--;
 
@@ -472,11 +487,11 @@
 }
 
 //////////////////////////////////////////////////////////////////////
-// Read next block from stream and decode into macro block
+// Reads next block(s) from stream and decodes them
 // Decoding scheme: <wordLen>(16 bits) [ ROI ] data
 //		ROI	  ::= <bufferSize>(15 bits) <eofTile>(1 bit)
 // It might throw an IOException.
-void CDecoder::DecodeBuffer() THROW_ {
+void CDecoder::DecodeBuffer() {
 	ASSERT(m_macroBlocksAvailable <= 0);
 
 	// macro block management
@@ -493,8 +508,8 @@
 				ReadMacroBlock(m_macroBlocks[i]);
 				m_macroBlocksAvailable++;
 			} catch(IOException& ex) {
-				if (ex.error == MissingData) {
-					break; // no further data available
+				if (ex.error == MissingData || ex.error == FormatCannotRead) {
+					break; // no further data available or the data isn't valid PGF data (might occur in streaming or PPPExt)
 				} else {
 					throw;
 				}
@@ -515,9 +530,9 @@
 }
 
 //////////////////////////////////////////////////////////////////////
-// Read next block from stream and store it in the given block
+// Reads next block from stream and stores it in the given macro block
 // It might throw an IOException.
-void CDecoder::ReadMacroBlock(CMacroBlock* block) THROW_ {
+void CDecoder::ReadMacroBlock(CMacroBlock* block) {
 	ASSERT(block);
 
 	UINT16 wordLen;
@@ -533,18 +548,16 @@
 	count = expected = sizeof(UINT16);
 	m_stream->Read(&count, &wordLen); 
 	if (count != expected) ReturnWithError(MissingData);
-	wordLen = __VAL(wordLen);
-	if (wordLen > BufferSize) 
-		ReturnWithError(FormatCannotRead);
+	wordLen = __VAL(wordLen); // convert wordLen
+	if (wordLen > BufferSize) ReturnWithError(FormatCannotRead);
 
 #ifdef __PGFROISUPPORT__
 	// read ROIBlockHeader
 	if (m_roi) {
-		m_stream->Read(&count, &h.val); 
+		count = expected = sizeof(ROIBlockHeader);
+		m_stream->Read(&count, &h.val);
 		if (count != expected) ReturnWithError(MissingData);
-		
-		// convert ROIBlockHeader
-		h.val = __VAL(h.val);
+		h.val = __VAL(h.val); // convert ROIBlockHeader
 	}
 #endif
 	// save header
@@ -570,44 +583,62 @@
 #endif
 }
 
+#ifdef __PGFROISUPPORT__
 //////////////////////////////////////////////////////////////////////
-// Read next block from stream but don't decode into macro block
-// Encoding scheme: <wordLen>(16 bits) [ ROI ] data
+// Resets stream position to next tile.
+// Used with ROI encoding scheme only.
+// Reads several next blocks from stream but doesn't decode them into macro blocks
+// Encoding scheme: <wordLen>(16 bits) ROI data
 //		ROI	  ::= <bufferSize>(15 bits) <eofTile>(1 bit)
 // It might throw an IOException.
-void CDecoder::SkipTileBuffer() THROW_ {
-	// current block is not used
+void CDecoder::SkipTileBuffer() {
+	ASSERT(m_roi);
+
+	// current macro block belongs to the last tile, so go to the next macro block
 	m_macroBlocksAvailable--;
+	m_currentBlockIndex++;
 
 	// check if pre-decoded data is available
+	while (m_macroBlocksAvailable > 0 && !m_macroBlocks[m_currentBlockIndex]->m_header.rbh.tileEnd) {
+		m_macroBlocksAvailable--;
+		m_currentBlockIndex++;
+	}
 	if (m_macroBlocksAvailable > 0) {
-		m_currentBlock = m_macroBlocks[++m_currentBlockIndex];
+		// set new current macro block
+		m_currentBlock = m_macroBlocks[m_currentBlockIndex];
+		ASSERT(m_currentBlock->m_header.rbh.tileEnd);
 		return;
 	}
-
+	
+	ASSERT(m_macroBlocksAvailable <= 0);
+	m_macroBlocksAvailable = 0;
 	UINT16 wordLen;
+	ROIBlockHeader h(0);
 	int count, expected;
 
-	// read wordLen
-	count = expected = sizeof(wordLen);
-	m_stream->Read(&count, &wordLen); 
-	if (count != expected) ReturnWithError(MissingData);
-	wordLen = __VAL(wordLen);
-	ASSERT(wordLen <= BufferSize);
-
-#ifdef __PGFROISUPPORT__
-	if (m_roi) {
-		// skip ROIBlockHeader
-		m_stream->SetPos(FSFromCurrent, sizeof(ROIBlockHeader));
-	}
-#endif
-
-	// skip data
-	m_stream->SetPos(FSFromCurrent, wordLen*WordBytes);
-}
+	// skips all blocks until tile end
+	do {
+		// read wordLen
+		count = expected = sizeof(wordLen);
+		m_stream->Read(&count, &wordLen);
+		if (count != expected) ReturnWithError(MissingData);
+		wordLen = __VAL(wordLen); // convert wordLen
+		if (wordLen > BufferSize) ReturnWithError(FormatCannotRead);
+
+		// read ROIBlockHeader
+		count = expected = sizeof(ROIBlockHeader);
+		m_stream->Read(&count, &h.val);
+		if (count != expected) ReturnWithError(MissingData);
+		h.val = __VAL(h.val); // convert ROIBlockHeader
+
+		// skip data
+		m_stream->SetPos(FSFromCurrent, wordLen*WordBytes);
+	} while (!h.rbh.tileEnd);
+}
+#endif
 
 //////////////////////////////////////////////////////////////////////
-// Decode block into buffer of given size using bit plane coding.
+// Decodes macro block into buffer of given size using bit plane coding.
 // A buffer contains bufferLen UINT32 values, thus, bufferSize bits per bit plane.
 // Following coding scheme is used: 
 //		Buffer		::= <nPlanes>(5 bits) foreach(plane i): Plane[i]  
@@ -619,10 +650,6 @@
 void CDecoder::CMacroBlock::BitplaneDecode() {
 	UINT32 bufferSize = m_header.rbh.bufferSize; ASSERT(bufferSize <= BufferSize);
 
-	UINT32 nPlanes;
-	UINT32 codePos = 0, codeLen, sigLen, sigPos, signLen, signPos;
-	DataT planeMask;
-
 	// clear significance vector
 	for (UINT32 k=0; k < bufferSize; k++) {
 		m_sigFlagVector[k] = false;
@@ -636,15 +663,17 @@
 
 	// read number of bit planes
 	// <nPlanes>
-	nPlanes = GetValueBlock(m_codeBuffer, 0, MaxBitPlanesLog); 
-	codePos += MaxBitPlanesLog;
+	UINT32 nPlanes = GetValueBlock(m_codeBuffer, 0, MaxBitPlanesLog); 
+	UINT32 codePos = MaxBitPlanesLog;
 
 	// loop through all bit planes
 	if (nPlanes == 0) nPlanes = MaxBitPlanes + 1;
 	ASSERT(0 < nPlanes && nPlanes <= MaxBitPlanes + 1);
-	planeMask = 1 << (nPlanes - 1);
+	DataT planeMask = 1 << (nPlanes - 1);
 
 	for (int plane = nPlanes - 1; plane >= 0; plane--) {
+		UINT32 sigLen = 0;
+
 		// read RL code
 		if (GetBit(m_codeBuffer, codePos)) {
 			// RL coding of sigBits is used
@@ -652,10 +681,10 @@
 			codePos++;
 
 			// read codeLen
-			codeLen = GetValueBlock(m_codeBuffer, codePos, RLblockSizeLen); ASSERT(codeLen <= MaxCodeLen);
+			UINT32 codeLen = GetValueBlock(m_codeBuffer, codePos, RLblockSizeLen); ASSERT(codeLen <= MaxCodeLen);
 
 			// position of encoded sigBits and signBits
-			sigPos = codePos + RLblockSizeLen; ASSERT(sigPos < CodeBufferBitLen); 
+			UINT32 sigPos = codePos + RLblockSizeLen; ASSERT(sigPos < CodeBufferBitLen);
 
 			// refinement bits
 			codePos = AlignWordPos(sigPos + codeLen); ASSERT(codePos < CodeBufferBitLen); 
@@ -680,13 +709,13 @@
 				codePos++;
 
 				// read codeLen
-				codeLen = GetValueBlock(m_codeBuffer, codePos, RLblockSizeLen); ASSERT(codeLen <= MaxCodeLen);
+				UINT32 codeLen = GetValueBlock(m_codeBuffer, codePos, RLblockSizeLen); ASSERT(codeLen <= MaxCodeLen);
 
 				// sign bits
-				signPos = codePos + RLblockSizeLen; ASSERT(signPos < CodeBufferBitLen);
+				UINT32 signPos = codePos + RLblockSizeLen; ASSERT(signPos < CodeBufferBitLen);
 				
 				// significant bits
-				sigPos = AlignWordPos(signPos + codeLen); ASSERT(sigPos < CodeBufferBitLen);
+				UINT32 sigPos = AlignWordPos(signPos + codeLen); ASSERT(sigPos < CodeBufferBitLen);
 
 				// refinement bits
 				codePos = AlignWordPos(sigPos + sigLen); ASSERT(codePos < CodeBufferBitLen);
@@ -700,13 +729,13 @@
 				codePos++;
 
 				// read signLen
-				signLen = GetValueBlock(m_codeBuffer, codePos, RLblockSizeLen); ASSERT(signLen <= MaxCodeLen);
+				UINT32 signLen = GetValueBlock(m_codeBuffer, codePos, RLblockSizeLen); ASSERT(signLen <= MaxCodeLen);
 				
 				// sign bits
-				signPos = AlignWordPos(codePos + RLblockSizeLen); ASSERT(signPos < CodeBufferBitLen);
+				UINT32 signPos = AlignWordPos(codePos + RLblockSizeLen); ASSERT(signPos < CodeBufferBitLen);
 
 				// significant bits
-				sigPos = AlignWordPos(signPos + signLen); ASSERT(sigPos < CodeBufferBitLen);
+				UINT32 sigPos = AlignWordPos(signPos + signLen); ASSERT(sigPos < CodeBufferBitLen);
 
 				// refinement bits
 				codePos = AlignWordPos(sigPos + sigLen); ASSERT(codePos < CodeBufferBitLen);
@@ -727,7 +756,7 @@
 }
 
 ////////////////////////////////////////////////////////////////////
-// Reconstruct bitplane from significant bitset and refinement bitset
+// Reconstructs bitplane from significant bitset and refinement bitset
 // returns length [bits] of sigBits
 // input:  sigBits, refBits, signBits
 // output: m_value
@@ -736,13 +765,11 @@
 	ASSERT(refBits);
 	ASSERT(signBits);
 
-	UINT32 valPos = 0, signPos = 0, refPos = 0;
-	UINT32 sigPos = 0, sigEnd;
-	UINT32 zerocnt;
+	UINT32 valPos = 0, signPos = 0, refPos = 0, sigPos = 0;
 
 	while (valPos < bufferSize) {
 		// search next 1 in m_sigFlagVector using searching with sentinel
-		sigEnd = valPos;
+		UINT32 sigEnd = valPos;
 		while(!m_sigFlagVector[sigEnd]) { sigEnd++; }
 		sigEnd -= valPos;
 		sigEnd += sigPos;
@@ -751,7 +778,7 @@
 		// these 1's are significant bits
 		while (sigPos < sigEnd) {
 			// search 0's
-			zerocnt = SeekBitRange(sigBits, sigPos, sigEnd - sigPos);
+			UINT32 zerocnt = SeekBitRange(sigBits, sigPos, sigEnd - sigPos);
 			sigPos += zerocnt;
 			valPos += zerocnt;
 			if (sigPos < sigEnd) {
@@ -785,7 +812,7 @@
 }
 
 ////////////////////////////////////////////////////////////////////
-// Reconstruct bitplane from significant bitset and refinement bitset
+// Reconstructs bitplane from significant bitset and refinement bitset
 // returns length [bits] of decoded significant bits
 // input:  RL encoded sigBits and signBits in m_codeBuffer, refBits
 // output: m_value
@@ -890,7 +917,7 @@
 }
 
 ////////////////////////////////////////////////////////////////////
-// Reconstruct bitplane from significant bitset, refinement bitset, and RL encoded sign bits
+// Reconstructs bitplane from significant bitset, refinement bitset, and RL encoded sign bits
 // returns length [bits] of sigBits
 // input:  sigBits, refBits, RL encoded signBits
 // output: m_value

Modified: trunk/Scribus/scribus/third_party/pgf/Decoder.h
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=23713&path=/trunk/Scribus/scribus/third_party/pgf/Decoder.h
==============================================================================
--- trunk/Scribus/scribus/third_party/pgf/Decoder.h	(original)
+++ trunk/Scribus/scribus/third_party/pgf/Decoder.h	Fri May  8 16:40:48 2020
@@ -52,12 +52,9 @@
 	public:
 		//////////////////////////////////////////////////////////////////////
 		/// Constructor: Initializes new macro block.
-		/// @param decoder Pointer to outer class.
 		CMacroBlock()
 		: m_header(0)								// makes sure that IsCompletelyRead() returns true for an empty macro block
-#if defined(WIN32) || defined(WINCE) || defined(WIN64)
 #pragma warning( suppress : 4351 )
-#endif
 		, m_value()
 		, m_codeBuffer()
 		, m_valuePos(0)
@@ -102,10 +99,10 @@
 	/// @param levelLength The location of the levelLength array. The array is allocated in this method. The caller has to delete this array.
 	/// @param userDataPos The stream position of the user data (metadata)
 	/// @param useOMP If true, then the decoder will use multi-threading based on openMP
-	/// @param skipUserData If true, then user data is not read. In case of available user data, the file position is still returned in userDataPos.
-	CDecoder(CPGFStream* stream, PGFPreHeader& preHeader, PGFHeader& header, 
+	/// @param userDataPolicy Policy of user data (meta-data) handling while reading PGF headers.
+	CDecoder(CPGFStream* stream, PGFPreHeader& preHeader, PGFHeader& header,
 		     PGFPostHeader& postHeader, UINT32*& levelLength, UINT64& userDataPos, 
-			 bool useOMP, bool skipUserData) THROW_; // throws IOException
+			 bool useOMP, UINT32 userDataPolicy); // throws IOException
 
 	/////////////////////////////////////////////////////////////////////
 	/// Destructor
@@ -122,7 +119,7 @@
 	/// @param height The height of the rectangle
 	/// @param startPos The relative subband position of the top left corner of the rectangular region
 	/// @param pitch The number of bytes in row of the subband
-	void Partition(CSubband* band, int quantParam, int width, int height, int startPos, int pitch) THROW_;
+	void Partition(CSubband* band, int quantParam, int width, int height, int startPos, int pitch);
 
 	/////////////////////////////////////////////////////////////////////
 	/// Deccoding and dequantization of HL and LH subband (interleaved) using partitioning scheme.
@@ -131,25 +128,25 @@
 	/// @param wtChannel A wavelet transform channel containing the HL and HL band
 	/// @param level Wavelet transform level
 	/// @param quantParam Dequantization value
-	void DecodeInterleaved(CWaveletTransform* wtChannel, int level, int quantParam) THROW_;
+	void DecodeInterleaved(CWaveletTransform* wtChannel, int level, int quantParam);
 
 	//////////////////////////////////////////////////////////////////////
-	/// Return the length of all encoded headers in bytes.
+	/// Returns the length of all encoded headers in bytes.
 	/// @return The length of all encoded headers in bytes
 	UINT32 GetEncodedHeaderLength() const			{ return m_encodedHeaderLength; }
 
 	////////////////////////////////////////////////////////////////////
-	/// Reset stream position to beginning of PGF pre-header
-	void SetStreamPosToStart() THROW_				{ ASSERT(m_stream); m_stream->SetPos(FSFromStart, m_startPos); }
+	/// Resets stream position to beginning of PGF pre-header
+	void SetStreamPosToStart()				{ ASSERT(m_stream); m_stream->SetPos(FSFromStart, m_startPos); }
 
 	////////////////////////////////////////////////////////////////////
-	/// Reset stream position to beginning of data block
-	void SetStreamPosToData() THROW_				{ ASSERT(m_stream); m_stream->SetPos(FSFromStart, m_startPos + m_encodedHeaderLength); }
+	/// Resets stream position to beginning of data block
+	void SetStreamPosToData()				{ ASSERT(m_stream); m_stream->SetPos(FSFromStart, m_startPos + m_encodedHeaderLength); }
 
 	////////////////////////////////////////////////////////////////////
-	/// Skip a given number of bytes in the open stream.
-	/// It might throw an IOException.
-	void Skip(UINT64 offset) THROW_;
+	/// Skips a given number of bytes in the open stream.
+	/// It might throw an IOException.
+	void Skip(UINT64 offset);
 
 	/////////////////////////////////////////////////////////////////////
 	/// Dequantization of a single value at given position in subband.
@@ -157,7 +154,7 @@
 	/// @param band A subband
 	/// @param bandPos A valid position in subband band
 	/// @param quantParam The quantization parameter
-	void DequantizeValue(CSubband* band, UINT32 bandPos, int quantParam) THROW_;
+	void DequantizeValue(CSubband* band, UINT32 bandPos, int quantParam);
 
 	//////////////////////////////////////////////////////////////////////
 	/// Copies data from the open stream to a target buffer.
@@ -165,31 +162,28 @@
 	/// @param target The target buffer
 	/// @param len The number of bytes to read
 	/// @return The number of bytes copied to the target buffer
-	UINT32 ReadEncodedData(UINT8* target, UINT32 len) const THROW_;
-
-	/////////////////////////////////////////////////////////////////////
-	/// Reads stream and decodes tile buffer
-	/// It might throw an IOException.
-	void DecodeBuffer() THROW_;
+	UINT32 ReadEncodedData(UINT8* target, UINT32 len) const;
+
+	/////////////////////////////////////////////////////////////////////
+	/// Reads next block(s) from stream and decodes them
+	/// It might throw an IOException.
+	void DecodeBuffer();
 
 	/////////////////////////////////////////////////////////////////////
 	/// @return Stream
 	CPGFStream* GetStream()							{ return m_stream; }
 
 	/////////////////////////////////////////////////////////////////////
-	/// @return True if decoded macro blocks are available for processing
-	bool MacroBlocksAvailable() const				{ return m_macroBlocksAvailable > 1; }
+	/// Gets next macro block
+	/// It might throw an IOException.
+	void GetNextMacroBlock();
 
 #ifdef __PGFROISUPPORT__
 	/////////////////////////////////////////////////////////////////////
-	/// Reads stream and decodes tile buffer
-	/// It might throw an IOException.
-	void DecodeTileBuffer() THROW_;
-
-	/////////////////////////////////////////////////////////////////////
 	/// Resets stream position to next tile.
-	/// It might throw an IOException.
-	void SkipTileBuffer() THROW_;
+	/// Used with ROI encoding scheme only.
+	/// It might throw an IOException.
+	void SkipTileBuffer();
 
 	/////////////////////////////////////////////////////////////////////
 	/// Enables region of interest (ROI) status.
@@ -201,7 +195,7 @@
 #endif
 
 private:
-	void ReadMacroBlock(CMacroBlock* block) THROW_; ///< throws IOException
+	void ReadMacroBlock(CMacroBlock* block); ///< throws IOException
 
 	CPGFStream *m_stream;						///< input PGF stream
 	UINT64 m_startPos;							///< stream position at the beginning of the PGF pre-header

Modified: trunk/Scribus/scribus/third_party/pgf/Encoder.cpp
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=23713&path=/trunk/Scribus/scribus/third_party/pgf/Encoder.cpp
==============================================================================
--- trunk/Scribus/scribus/third_party/pgf/Encoder.cpp	(original)
+++ trunk/Scribus/scribus/third_party/pgf/Encoder.cpp	Fri May  8 16:40:48 2020
@@ -34,7 +34,7 @@
 //////////////////////////////////////////////////////
 // PGF: file structure
 //
-// PGFPreHeader PGFHeader PGFPostHeader LevelLengths Level_n-1 Level_n-2 ... Level_0
+// PGFPreHeader PGFHeader [PGFPostHeader] LevelLengths Level_n-1 Level_n-2 ... Level_0
 // PGFPostHeader ::= [ColorTable] [UserData]
 // LevelLengths  ::= UINT32[nLevels]
 
@@ -67,7 +67,7 @@
 /// @param postHeader [in] An already filled in PGF post-header (containing color table, user data, ...)
 /// @param userDataPos [out] File position of user data
 /// @param useOMP If true, then the encoder will use multi-threading based on openMP
-CEncoder::CEncoder(CPGFStream* stream, PGFPreHeader preHeader, PGFHeader header, const PGFPostHeader& postHeader, UINT64& userDataPos, bool useOMP) THROW_
+CEncoder::CEncoder(CPGFStream* stream, PGFPreHeader preHeader, PGFHeader header, const PGFPostHeader& postHeader, UINT64& userDataPos, bool useOMP)
 : m_stream(stream)
 , m_bufferStartPos(0)
 , m_currLevelIndex(0)
@@ -82,7 +82,7 @@
 
 	int count;
 	m_lastMacroBlock = 0;
-	m_levelLength = NULL;
+	m_levelLength = nullptr;
 
 	// set number of threads
 #ifdef LIBPGF_USE_OPENMP
@@ -157,12 +157,12 @@
 /// Increase post-header size and write new size into stream.
 /// @param preHeader An already filled in PGF pre-header
 /// It might throw an IOException.
-void CEncoder::UpdatePostHeaderSize(PGFPreHeader preHeader) THROW_ {
+void CEncoder::UpdatePostHeaderSize(PGFPreHeader preHeader) {
 	UINT64 curPos = m_stream->GetPos(); // end of user data
 	int count = PreHeaderSize;
 
 	// write preHeader
-	m_stream->SetPos(FSFromStart, m_startPosition);
+	SetStreamPosToStart();
 	preHeader.hSize = __VAL(preHeader.hSize);
 	m_stream->Write(&count, &preHeader);
 
@@ -174,7 +174,7 @@
 /// It might throw an IOException.
 /// @param levelLength A reference to an integer array, large enough to save the relative file positions of all PGF levels
 /// @return number of bytes written into stream
-UINT32 CEncoder::WriteLevelLength(UINT32*& levelLength) THROW_ {
+UINT32 CEncoder::WriteLevelLength(UINT32*& levelLength) {
 	// renew levelLength
 	delete[] levelLength;
 	levelLength = new(std::nothrow) UINT32[m_nLevels];
@@ -199,7 +199,7 @@
 /// Write new levelLength into stream.
 /// It might throw an IOException.
 /// @return Written image bytes.
-UINT32 CEncoder::UpdateLevelLength() THROW_ {
+UINT32 CEncoder::UpdateLevelLength() {
 	UINT64 curPos = m_stream->GetPos(); // end of image
 
 	// set file pos to levelLength
@@ -243,7 +243,7 @@
 /// @param height The height of the rectangle
 /// @param startPos The absolute subband position of the top left corner of the rectangular region
 /// @param pitch The number of bytes in row of the subband
-void CEncoder::Partition(CSubband* band, int width, int height, int startPos, int pitch) THROW_ {
+void CEncoder::Partition(CSubband* band, int width, int height, int startPos, int pitch) {
 	ASSERT(band);
 
 	const div_t hh = div(height, LinBlockSize);
@@ -307,7 +307,7 @@
 //////////////////////////////////////////////////////
 /// Pad buffer with zeros and encode buffer.
 /// It might throw an IOException.
-void CEncoder::Flush() THROW_ {
+void CEncoder::Flush() {
 	if (m_currentBlock->m_valuePos > 0) {
 		// pad buffer with zeros
 		memset(&(m_currentBlock->m_value[m_currentBlock->m_valuePos]), 0, (BufferSize - m_currentBlock->m_valuePos)*DataTSize);
@@ -323,7 +323,7 @@
 // Stores band value from given position bandPos into buffer m_value at position m_valuePos
 // If buffer is full encode it to file
 // It might throw an IOException.
-void CEncoder::WriteValue(CSubband* band, int bandPos) THROW_ {
+void CEncoder::WriteValue(CSubband* band, int bandPos) {
 	if (m_currentBlock->m_valuePos == BufferSize) {
 		EncodeBuffer(ROIBlockHeader(BufferSize, false));
 	}
@@ -338,7 +338,7 @@
 // Encoding scheme: <wordLen>(16 bits) [ ROI ] data
 //		ROI	  ::= <bufferSize>(15 bits) <eofTile>(1 bit)
 // It might throw an IOException.
-void CEncoder::EncodeBuffer(ROIBlockHeader h) THROW_ {
+void CEncoder::EncodeBuffer(ROIBlockHeader h) {
 	ASSERT(m_currentBlock);
 #ifdef __PGFROISUPPORT__
 	ASSERT(m_roi && h.rbh.bufferSize <= BufferSize || h.rbh.bufferSize == BufferSize);
@@ -403,7 +403,7 @@
 /////////////////////////////////////////////////////////////////////
 // Write encoded macro block into stream.
 // It might throw an IOException.
-void CEncoder::WriteMacroBlock(CMacroBlock* block) THROW_ {
+void CEncoder::WriteMacroBlock(CMacroBlock* block) {
 	ASSERT(block);
 #ifdef __PGFROISUPPORT__
 	ROIBlockHeader h = block->m_header;
@@ -424,8 +424,9 @@
 #ifdef __PGFROISUPPORT__
 	// write ROIBlockHeader
 	if (m_roi) {
+		count = sizeof(ROIBlockHeader);
 		h.val = __VAL(h.val);
-		m_stream->Write(&count, &h.val); ASSERT(count == sizeof(UINT16));
+		m_stream->Write(&count, &h.val); ASSERT(count == sizeof(ROIBlockHeader));
 	}
 #endif // __PGFROISUPPORT__
 
@@ -440,7 +441,8 @@
 #ifdef __PGFROISUPPORT__
 	// write ROIBlockHeader
 	if (m_roi) {
-		m_stream->Write(&count, &h.val); ASSERT(count == sizeof(UINT16));
+		count = sizeof(ROIBlockHeader);
+		m_stream->Write(&count, &h.val); ASSERT(count == sizeof(ROIBlockHeader));
 	}
 #endif // __PGFROISUPPORT__
 #endif // PGF_USE_BIG_ENDIAN

Modified: trunk/Scribus/scribus/third_party/pgf/Encoder.h
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=23713&path=/trunk/Scribus/scribus/third_party/pgf/Encoder.h
==============================================================================
--- trunk/Scribus/scribus/third_party/pgf/Encoder.h	(original)
+++ trunk/Scribus/scribus/third_party/pgf/Encoder.h	Fri May  8 16:40:48 2020
@@ -54,9 +54,7 @@
 		/// Constructor: Initializes new macro block.
 		/// @param encoder Pointer to outer class.
 		CMacroBlock(CEncoder *encoder)
-#if defined(WIN32) || defined(WINCE) || defined(WIN64)
 #pragma warning( suppress : 4351 )
-#endif
 		: m_value()
 		, m_codeBuffer()
 		, m_header(0)
@@ -112,7 +110,7 @@
 	/// @param userDataPos [out] File position of user data
 	/// @param useOMP If true, then the encoder will use multi-threading based on openMP
 	CEncoder(CPGFStream* stream, PGFPreHeader preHeader, PGFHeader header, const PGFPostHeader& postHeader, 
-		UINT64& userDataPos, bool useOMP) THROW_; // throws IOException
+		UINT64& userDataPos, bool useOMP); // throws IOException
 
 	/////////////////////////////////////////////////////////////////////
 	/// Destructor
@@ -125,26 +123,26 @@
 	/////////////////////////////////////////////////////////////////////
 	/// Pad buffer with zeros and encode buffer.
 	/// It might throw an IOException.
-	void Flush() THROW_;
+	void Flush();
 
 	/////////////////////////////////////////////////////////////////////
 	/// Increase post-header size and write new size into stream.
 	/// @param preHeader An already filled in PGF pre-header
 	/// It might throw an IOException.
-	void UpdatePostHeaderSize(PGFPreHeader preHeader) THROW_;
+	void UpdatePostHeaderSize(PGFPreHeader preHeader);
 
 	/////////////////////////////////////////////////////////////////////
 	/// Create level length data structure and write a place holder into stream.
 	/// It might throw an IOException.
 	/// @param levelLength A reference to an integer array, large enough to save the relative file positions of all PGF levels
 	/// @return number of bytes written into stream
-	UINT32 WriteLevelLength(UINT32*& levelLength) THROW_;
+	UINT32 WriteLevelLength(UINT32*& levelLength);
 
 	/////////////////////////////////////////////////////////////////////
 	/// Write new levelLength into stream.
 	/// It might throw an IOException.
 	/// @return Written image bytes.
-	UINT32 UpdateLevelLength() THROW_;
+	UINT32 UpdateLevelLength();
 
 	/////////////////////////////////////////////////////////////////////
 	/// Partitions a rectangular region of a given subband.
@@ -156,7 +154,7 @@
 	/// @param height The height of the rectangle
 	/// @param startPos The absolute subband position of the top left corner of the rectangular region
 	/// @param pitch The number of bytes in row of the subband
-	void Partition(CSubband* band, int width, int height, int startPos, int pitch) THROW_;
+	void Partition(CSubband* band, int width, int height, int startPos, int pitch);
 
 	/////////////////////////////////////////////////////////////////////
 	/// Informs the encoder about the encoded level. 
@@ -168,7 +166,7 @@
 	/// It might throw an IOException.
 	/// @param band A subband
 	/// @param bandPos A valid position in subband band
-	void WriteValue(CSubband* band, int bandPos) THROW_;
+	void WriteValue(CSubband* band, int bandPos);
 
 	/////////////////////////////////////////////////////////////////////
 	/// Compute stream length of header.
@@ -185,6 +183,10 @@
 	/// @return file offset
 	INT64 ComputeOffset() const { return m_stream->GetPos() - m_levelLengthPos; }
 
+	////////////////////////////////////////////////////////////////////
+	/// Resets stream position to beginning of PGF pre-header
+	void SetStreamPosToStart() { ASSERT(m_stream); m_stream->SetPos(FSFromStart, m_startPosition); }
+
 	/////////////////////////////////////////////////////////////////////
 	/// Save current stream position as beginning of current level.
 	void SetBufferStartPos() { m_bufferStartPos = m_stream->GetPos(); }
@@ -193,7 +195,7 @@
 	/////////////////////////////////////////////////////////////////////
 	/// Encodes tile buffer and writes it into stream
 	/// It might throw an IOException.
-	void EncodeTileBuffer() THROW_	{ ASSERT(m_currentBlock && m_currentBlock->m_valuePos >= 0 && m_currentBlock->m_valuePos <= BufferSize); EncodeBuffer(ROIBlockHeader(m_currentBlock->m_valuePos, true)); }
+	void EncodeTileBuffer()	{ ASSERT(m_currentBlock && m_currentBlock->m_valuePos >= 0 && m_currentBlock->m_valuePos <= BufferSize); EncodeBuffer(ROIBlockHeader(m_currentBlock->m_valuePos, true)); }
 
 	/////////////////////////////////////////////////////////////////////
 	/// Enables region of interest (ROI) status.
@@ -205,8 +207,8 @@
 #endif
 
 private:
-	void EncodeBuffer(ROIBlockHeader h) THROW_; // throws IOException
-	void WriteMacroBlock(CMacroBlock* block) THROW_; // throws IOException
+	void EncodeBuffer(ROIBlockHeader h); // throws IOException
+	void WriteMacroBlock(CMacroBlock* block); // throws IOException
 
 	CPGFStream *m_stream;						///< output PMF stream
 	UINT64	m_startPosition;					///< stream position of PGF start (PreHeader)

Modified: trunk/Scribus/scribus/third_party/pgf/PGFimage.cpp
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=23713&path=/trunk/Scribus/scribus/third_party/pgf/PGFimage.cpp
==============================================================================
--- trunk/Scribus/scribus/third_party/pgf/PGFimage.cpp	(original)
+++ trunk/Scribus/scribus/third_party/pgf/PGFimage.cpp	Fri May  8 16:40:48 2020
@@ -29,6 +29,7 @@
 #include "PGFimage.h"
 #include "Decoder.h"
 #include "Encoder.h"
+#include "BitStream.h"
 #include <cmath>
 #include <cstring>
 
@@ -50,28 +51,43 @@
 	}
 #endif
 
+#ifdef _DEBUG
+	// allows RGB and RGBA image visualization inside Visual Studio Debugger
+	struct DebugBGRImage {
+		int width, height, pitch;
+		BYTE *data;
+	} roiimage;
+#endif
+
 //////////////////////////////////////////////////////////////////////
-// Standard constructor: It is used to create a PGF instance for opening and reading.
-CPGFImage::CPGFImage() 
-: m_decoder(0)
-, m_encoder(0)
-, m_levelLength(0)
-, m_userDataPos(0)
-, m_currentLevel(0)
-, m_quant(0)
-, m_downsample(false)
-, m_favorSpeedOverSize(false)
-, m_useOMPinEncoder(true)
-, m_useOMPinDecoder(true)
-, m_skipUserData(false)
+// Standard constructor
+CPGFImage::CPGFImage() {
+	Init();
+}
+
+//////////////////////////////////////////////////////////////////////
+void CPGFImage::Init() {
+	// init pointers
+	m_decoder = nullptr;
+	m_encoder = nullptr;
+	m_levelLength = nullptr;
+
+	// init members
 #ifdef __PGFROISUPPORT__
-, m_streamReinitialized(false)
+	m_streamReinitialized = false;
 #endif
-, m_cb(0)
-, m_cbArg(0)
-, m_percent(0)
-, m_progressMode(PM_Relative)
-{
+	m_currentLevel = 0;
+	m_quant = 0;
+	m_userDataPos = 0;
+	m_downsample = false;
+	m_favorSpeedOverSize = false;
+	m_useOMPinEncoder = true;
+	m_useOMPinDecoder = true;
+	m_cb = nullptr;
+	m_cbArg = nullptr;
+	m_progressMode = PM_Relative;
+	m_percent = 0;
+	m_userDataPolicy = UP_CacheAll;
 
 	// init preHeader
 	memcpy(m_preHeader.magic, PGFMagic, 3);
@@ -79,48 +95,42 @@
 	m_preHeader.hSize = 0;
 
 	// init postHeader
-	m_postHeader.userData = 0;
+	m_postHeader.userData = nullptr;
 	m_postHeader.userDataLen = 0;
+	m_postHeader.cachedUserDataLen = 0;
 
 	// init channels
-	for (int i=0; i < MaxChannels; i++) {
-		m_channel[i] = 0;
-		m_wtChannel[i] = 0;
+	for (int i = 0; i < MaxChannels; i++) {
+		m_channel[i] = nullptr;
+		m_wtChannel[i] = nullptr;
 	}
 
 	// set image width and height
-	m_width[0] = 0;
-	m_height[0] = 0;
+	for (int i = 0; i < MaxChannels; i++) {
+		m_width[0] = 0;
+		m_height[0] = 0;
+	}
 }
 
 //////////////////////////////////////////////////////////////////////
 // Destructor: Destroy internal data structures.
 CPGFImage::~CPGFImage() {
+	m_currentLevel = -100; // unusual value used as marker in Destroy()
 	Destroy();
 }
 
 //////////////////////////////////////////////////////////////////////
-// Destroy internal data structures.
-// Destructor calls this method during destruction.
+// Destroy internal data structures. Object state after this is the same as after CPGFImage().
 void CPGFImage::Destroy() {
-	Close();
-
-	for (int i=0; i < m_header.channels; i++) {
-		delete m_wtChannel[i]; m_wtChannel[i]=0; // also deletes m_channel
-		m_channel[i] = 0;
-	}
-	delete[] m_postHeader.userData; m_postHeader.userData = 0; m_postHeader.userDataLen = 0;
-	delete[] m_levelLength; m_levelLength = 0;
-	delete m_encoder; m_encoder = NULL;
-	
-	m_userDataPos = 0;
-}
-
-//////////////////////////////////////////////////////////////////////
-// Close PGF image after opening and reading.
-// Destructor calls this method during destruction.
-void CPGFImage::Close() {
-	delete m_decoder; m_decoder = 0;
+	for (int i = 0; i < m_header.channels; i++) {
+		delete m_wtChannel[i]; // also deletes m_channel
+	}
+	delete[] m_postHeader.userData; 
+	delete[] m_levelLength;
+	delete m_decoder;
+	delete m_encoder;
+
+	if (m_currentLevel != -100) Init();
 }
 
 /////////////////////////////////////////////////////////////////////////////
@@ -128,12 +138,12 @@
 // Precondition: The stream has been opened for reading.
 // It might throw an IOException.
 // @param stream A PGF stream
-void CPGFImage::Open(CPGFStream *stream) THROW_ {
+void CPGFImage::Open(CPGFStream *stream) {
 	ASSERT(stream);
 
 	// create decoder and read PGFPreHeader PGFHeader PGFPostHeader LevelLengths
 	m_decoder = new CDecoder(stream, m_preHeader, m_header, m_postHeader, m_levelLength, 
-		m_userDataPos, m_useOMPinDecoder, m_skipUserData);
+		m_userDataPos, m_useOMPinDecoder, m_userDataPolicy);
 
 	if (m_header.nLevels > MaxLevel) ReturnWithError(FormatCannotRead);
 
@@ -145,7 +155,7 @@
 	m_height[0] = m_header.height;
 
 	// complete header
-	CompleteHeader();
+	if (!CompleteHeader()) ReturnWithError(FormatCannotRead);
 
 	// interpret quant parameter
 	if (m_header.quality > DownsampleThreshold && 
@@ -166,8 +176,8 @@
 	// set channel dimensions (chrominance is subsampled by factor 2)
 	if (m_downsample) {
 		for (int i=1; i < m_header.channels; i++) {
-			m_width[i] = (m_width[0] + 1)/2;
-			m_height[i] = (m_height[0] + 1)/2;
+			m_width[i] = (m_width[0] + 1) >> 1;
+			m_height[i] = (m_height[0] + 1) >> 1;
 		}
 	} else {
 		for (int i=1; i < m_header.channels; i++) {
@@ -205,7 +215,10 @@
 }
 
 ////////////////////////////////////////////////////////////
-void CPGFImage::CompleteHeader() {
+bool CPGFImage::CompleteHeader() {
+	// set current codec version
+	m_header.version = PGFVersionNumber(PGFMajorNumber, PGFYear, PGFWeek);
+
 	if (m_header.mode == ImageModeUnknown) {
 		// undefined mode
 		switch(m_header.bpp) {
@@ -261,20 +274,20 @@
 		// change mode
 		m_header.mode = ImageModeRGBA;
 	}
-	ASSERT(m_header.mode != ImageModeBitmap || m_header.bpp == 1);
-	ASSERT(m_header.mode != ImageModeIndexedColor || m_header.bpp == 8);
-	ASSERT(m_header.mode != ImageModeGrayScale || m_header.bpp == 8);
-	ASSERT(m_header.mode != ImageModeGray16 || m_header.bpp == 16);
-	ASSERT(m_header.mode != ImageModeGray32 || m_header.bpp == 32);
-	ASSERT(m_header.mode != ImageModeRGBColor || m_header.bpp == 24);
-	ASSERT(m_header.mode != ImageModeRGBA || m_header.bpp == 32);
-	ASSERT(m_header.mode != ImageModeRGB12 || m_header.bpp == 12);
-	ASSERT(m_header.mode != ImageModeRGB16 || m_header.bpp == 16);
-	ASSERT(m_header.mode != ImageModeRGB48 || m_header.bpp == 48);
-	ASSERT(m_header.mode != ImageModeLabColor || m_header.bpp == 24);
-	ASSERT(m_header.mode != ImageModeLab48 || m_header.bpp == 48);
-	ASSERT(m_header.mode != ImageModeCMYKColor || m_header.bpp == 32);
-	ASSERT(m_header.mode != ImageModeCMYK64 || m_header.bpp == 64);
+	if (m_header.mode == ImageModeBitmap && m_header.bpp != 1) return false;
+	if (m_header.mode == ImageModeIndexedColor && m_header.bpp != 8) return false;
+	if (m_header.mode == ImageModeGrayScale && m_header.bpp != 8) return false;
+	if (m_header.mode == ImageModeGray16 && m_header.bpp != 16) return false;
+	if (m_header.mode == ImageModeGray32 && m_header.bpp != 32) return false;
+	if (m_header.mode == ImageModeRGBColor && m_header.bpp != 24) return false;
+	if (m_header.mode == ImageModeRGBA && m_header.bpp != 32) return false;
+	if (m_header.mode == ImageModeRGB12 && m_header.bpp != 12) return false;
+	if (m_header.mode == ImageModeRGB16 && m_header.bpp != 16) return false;
+	if (m_header.mode == ImageModeRGB48 && m_header.bpp != 48) return false;
+	if (m_header.mode == ImageModeLabColor && m_header.bpp != 24) return false;
+	if (m_header.mode == ImageModeLab48 && m_header.bpp != 48) return false;
+	if (m_header.mode == ImageModeCMYKColor && m_header.bpp != 32) return false;
+	if (m_header.mode == ImageModeCMYK64 && m_header.bpp != 64) return false;
 
 	// set number of channels
 	if (!m_header.channels) {
@@ -300,8 +313,7 @@
 			m_header.channels = 4;
 			break;
 		default:
-			ASSERT(false);
-			m_header.channels = 3;
+			return false;
 		}
 	}
 
@@ -311,15 +323,20 @@
 	if (!m_header.usedBitsPerChannel || m_header.usedBitsPerChannel > bpc) {
 		m_header.usedBitsPerChannel = bpc;
 	}
+
+	return true;
 }
 
 //////////////////////////////////////////////////////////////////////
 /// Return user data and size of user data.
 /// Precondition: The PGF image has been opened with a call of Open(...).
-/// @param size [out] Size of user data in bytes.
-/// @return A pointer to user data or NULL if there is no user data.
-const UINT8* CPGFImage::GetUserData(UINT32& size) const {
-	size = m_postHeader.userDataLen;
+/// In an encoder scenario don't call this method before WriteHeader().
+/// @param cachedSize [out] Size of returned user data in bytes.
+/// @param pTotalSize [optional out] Pointer to return the size of user data stored in image header in bytes.
+/// @return A pointer to user data or nullptr if there is no user data available.
+const UINT8* CPGFImage::GetUserData(UINT32& cachedSize, UINT32* pTotalSize /*= nullptr*/) const {
+	cachedSize = m_postHeader.cachedUserDataLen;
+	if (pTotalSize) *pTotalSize = m_postHeader.userDataLen;
 	return m_postHeader.userData;
 }
 
@@ -328,7 +345,7 @@
 /// to get a quick reconstruction (coded -> decoded image).
 /// It might throw an IOException.
 /// @param level The image level of the resulting image in the internal image buffer.
-void CPGFImage::Reconstruct(int level /*= 0*/) THROW_ {
+void CPGFImage::Reconstruct(int level /*= 0*/) {
 	if (m_header.nLevels == 0) {
 		// image didn't use wavelet transform
 		if (level == 0) {
@@ -340,10 +357,12 @@
 	} else {
 		int currentLevel = m_header.nLevels;
 
+	#ifdef __PGFROISUPPORT__
 		if (ROIisSupported()) {
 			// enable ROI reading
 			SetROI(PGFRect(0, 0, m_header.width, m_header.height));
 		}
+	#endif
 
 		while (currentLevel > level) {
 			for (int i=0; i < m_header.channels; i++) {
@@ -380,7 +399,7 @@
 // @param level The image level of the resulting image in the internal image buffer.
 // @param cb A pointer to a callback procedure. The procedure is called after reading a single level. If cb returns true, then it stops proceeding.
 // @param data Data Pointer to C++ class container to host callback procedure.
-void CPGFImage::Read(int level /*= 0*/, CallbackPtr cb /*= NULL*/, void *data /*=NULL*/) THROW_ {
+void CPGFImage::Read(int level /*= 0*/, CallbackPtr cb /*= nullptr*/, void *data /*=nullptr*/) {
 	ASSERT((level >= 0 && level < m_header.nLevels) || m_header.nLevels == 0); // m_header.nLevels == 0: image didn't use wavelet transform
 	ASSERT(m_decoder);
 
@@ -408,21 +427,23 @@
 		// encoding scheme without ROI
 		while (m_currentLevel > level) {
 			for (int i=0; i < m_header.channels; i++) {
-				ASSERT(m_wtChannel[i]);
+				CWaveletTransform* wtChannel = m_wtChannel[i];
+				ASSERT(wtChannel);
+
 				// decode file and write stream to m_wtChannel
 				if (m_currentLevel == m_header.nLevels) { 
 					// last level also has LL band
-					m_wtChannel[i]->GetSubband(m_currentLevel, LL)->PlaceTile(*m_decoder, m_quant);
+					wtChannel->GetSubband(m_currentLevel, LL)->PlaceTile(*m_decoder, m_quant);
 				}
 				if (m_preHeader.version & Version5) {
 					// since version 5
-					m_wtChannel[i]->GetSubband(m_currentLevel, HL)->PlaceTile(*m_decoder, m_quant);
-					m_wtChannel[i]->GetSubband(m_currentLevel, LH)->PlaceTile(*m_decoder, m_quant);
+					wtChannel->GetSubband(m_currentLevel, HL)->PlaceTile(*m_decoder, m_quant);
+					wtChannel->GetSubband(m_currentLevel, LH)->PlaceTile(*m_decoder, m_quant);
 				} else {
 					// until version 4
-					m_decoder->DecodeInterleaved(m_wtChannel[i], m_currentLevel, m_quant);
-				}
-				m_wtChannel[i]->GetSubband(m_currentLevel, HH)->PlaceTile(*m_decoder, m_quant);
+					m_decoder->DecodeInterleaved(wtChannel, m_currentLevel, m_quant);
+				}
+				wtChannel->GetSubband(m_currentLevel, HH)->PlaceTile(*m_decoder, m_quant);
 			}
 
 			volatile OSError error = NoError; // volatile prevents optimizations
@@ -453,22 +474,19 @@
 			}
 		}
 	}
-
-	// automatically closing
-	if (m_currentLevel == 0) Close();
 }
 
 #ifdef __PGFROISUPPORT__
 //////////////////////////////////////////////////////////////////////
-/// Read a rectangular region of interest of a PGF image at current stream position.
+/// Read and decode rectangular region of interest (ROI) of a PGF image at current stream position.
 /// The origin of the coordinate axis is the top-left corner of the image.
 /// All coordinates are measured in pixels.
 /// It might throw an IOException.
-/// @param rect [inout] Rectangular region of interest (ROI). The rect might be cropped.
+/// @param rect [inout] Rectangular region of interest (ROI) at level 0. The rect might be cropped.
 /// @param level The image level of the resulting image in the internal image buffer.
 /// @param cb A pointer to a callback procedure. The procedure is called after reading a single level. If cb returns true, then it stops proceeding.
 /// @param data Data Pointer to C++ class container to host callback procedure.
-void CPGFImage::Read(PGFRect& rect, int level /*= 0*/, CallbackPtr cb /*= NULL*/, void *data /*=NULL*/) THROW_ {
+void CPGFImage::Read(PGFRect& rect, int level /*= 0*/, CallbackPtr cb /*= nullptr*/, void *data /*=nullptr*/) {
 	ASSERT((level >= 0 && level < m_header.nLevels) || m_header.nLevels == 0); // m_header.nLevels == 0: image didn't use wavelet transform
 	ASSERT(m_decoder);
 
@@ -481,6 +499,10 @@
 		// new encoding scheme supporting ROI
 		ASSERT(rect.left < m_header.width && rect.top < m_header.height);
 
+		// check rectangle
+		if (rect.right == 0 || rect.right > m_header.width) rect.right = m_header.width;
+		if (rect.bottom == 0 || rect.bottom > m_header.height) rect.bottom = m_header.height;
+
 		const int levelDiff = m_currentLevel - level;
 		double percent = (m_progressMode == PM_Relative) ? pow(0.25, levelDiff) : m_percent;
 		
@@ -491,35 +513,31 @@
 			m_decoder->SetStreamPosToData();
 		}
 
-		// check rectangle
-		if (rect.right == 0 || rect.right > m_header.width) rect.right = m_header.width;
-		if (rect.bottom == 0 || rect.bottom > m_header.height) rect.bottom = m_header.height;
-		
 		// enable ROI decoding and reading
 		SetROI(rect);
 
 		while (m_currentLevel > level) {
 			for (int i=0; i < m_header.channels; i++) {
-				ASSERT(m_wtChannel[i]);
+				CWaveletTransform* wtChannel = m_wtChannel[i];
+				ASSERT(wtChannel);
 
 				// get number of tiles and tile indices
-				const UINT32 nTiles = m_wtChannel[i]->GetNofTiles(m_currentLevel);
-				const PGFRect& tileIndices = m_wtChannel[i]->GetTileIndices(m_currentLevel);
+				const UINT32 nTiles = wtChannel->GetNofTiles(m_currentLevel); // independent of ROI
 
 				// decode file and write stream to m_wtChannel
 				if (m_currentLevel == m_header.nLevels) { // last level also has LL band
 					ASSERT(nTiles == 1);
-					m_decoder->DecodeTileBuffer();
-					m_wtChannel[i]->GetSubband(m_currentLevel, LL)->PlaceTile(*m_decoder, m_quant);
+					m_decoder->GetNextMacroBlock();
+					wtChannel->GetSubband(m_currentLevel, LL)->PlaceTile(*m_decoder, m_quant);
 				}
 				for (UINT32 tileY=0; tileY < nTiles; tileY++) {
 					for (UINT32 tileX=0; tileX < nTiles; tileX++) {
 						// check relevance of tile
-						if (tileIndices.IsInside(tileX, tileY)) {
-							m_decoder->DecodeTileBuffer();
-							m_wtChannel[i]->GetSubband(m_currentLevel, HL)->PlaceTile(*m_decoder, m_quant, true, tileX, tileY);
-							m_wtChannel[i]->GetSubband(m_currentLevel, LH)->PlaceTile(*m_decoder, m_quant, true, tileX, tileY);
-							m_wtChannel[i]->GetSubband(m_currentLevel, HH)->PlaceTile(*m_decoder, m_quant, true, tileX, tileY);
+						if (wtChannel->TileIsRelevant(m_currentLevel, tileX, tileY)) {
+							m_decoder->GetNextMacroBlock();
+							wtChannel->GetSubband(m_currentLevel, HL)->PlaceTile(*m_decoder, m_quant, true, tileX, tileY);
+							wtChannel->GetSubband(m_currentLevel, LH)->PlaceTile(*m_decoder, m_quant, true, tileX, tileY);
+							wtChannel->GetSubband(m_currentLevel, HH)->PlaceTile(*m_decoder, m_quant, true, tileX, tileY);
 						} else {
 							// skip tile
 							m_decoder->SkipTileBuffer();
@@ -556,17 +574,48 @@
 			}
 		}
 	}
-
-	// automatically closing
-	if (m_currentLevel == 0) Close();
 }
 
 //////////////////////////////////////////////////////////////////////
-/// Compute ROIs for each channel and each level
-/// @param rect rectangular region of interest (ROI)
+/// Return ROI of channel 0 at current level in pixels.
+/// The returned rect is only valid after reading a ROI.
+/// @return ROI in pixels
+PGFRect CPGFImage::ComputeLevelROI() const {
+	if (m_currentLevel == 0) {
+		return m_roi;
+	} else {
+		const UINT32 rLeft = LevelSizeL(m_roi.left, m_currentLevel);
+		const UINT32 rRight = LevelSizeL(m_roi.right, m_currentLevel);
+		const UINT32 rTop = LevelSizeL(m_roi.top, m_currentLevel);
+		const UINT32 rBottom = LevelSizeL(m_roi.bottom, m_currentLevel);
+		return PGFRect(rLeft, rTop, rRight - rLeft, rBottom - rTop);
+	}
+}
+
+//////////////////////////////////////////////////////////////////////
+/// Returns aligned ROI in pixels of current level of channel c
+/// @param c A channel index
+PGFRect CPGFImage::GetAlignedROI(int c /*= 0*/) const {
+	PGFRect roi(0, 0, m_width[c], m_height[c]);
+
+	if (ROIisSupported()) {
+		ASSERT(m_wtChannel[c]);
+
+		roi = m_wtChannel[c]->GetAlignedROI(m_currentLevel);
+	}
+	ASSERT(roi.Width() == m_width[c]);
+	ASSERT(roi.Height() == m_height[c]);
+	return roi;
+}
+
+//////////////////////////////////////////////////////////////////////
+/// Compute ROIs for each channel and each level <= current level
+/// Called inside of Read(rect, ...).
+/// @param rect rectangular region of interest (ROI) at level 0
 void CPGFImage::SetROI(PGFRect rect) {
 	ASSERT(m_decoder);
 	ASSERT(ROIisSupported());
+	ASSERT(m_wtChannel[0]);
 
 	// store ROI for a later call of GetBitmap
 	m_roi = rect;
@@ -574,28 +623,15 @@
 	// enable ROI decoding
 	m_decoder->SetROI();
 
-	// enlarge ROI because of border artefacts
-	const UINT32 dx = FilterWidth/2*(1 << m_currentLevel);
-	const UINT32 dy = FilterHeight/2*(1 << m_currentLevel);
-
-	if (rect.left < dx) rect.left = 0;
-	else rect.left -= dx;
-	if (rect.top < dy) rect.top = 0;
-	else rect.top -= dy;
-	rect.right += dx;
-	if (rect.right > m_header.width) rect.right = m_header.width;
-	rect.bottom += dy;
-	if (rect.bottom > m_header.height) rect.bottom = m_header.height;
-
 	// prepare wavelet channels for using ROI
-	ASSERT(m_wtChannel[0]);
 	m_wtChannel[0]->SetROI(rect);
+
 	if (m_downsample && m_header.channels > 1) {
 		// all further channels are downsampled, therefore downsample ROI
 		rect.left >>= 1;
 		rect.top >>= 1;
-		rect.right >>= 1;
-		rect.bottom >>= 1;
+		rect.right = (rect.right + 1) >> 1;
+		rect.bottom = (rect.bottom + 1) >> 1;
 	}
 	for (int i=1; i < m_header.channels; i++) {
 		ASSERT(m_wtChannel[i]);
@@ -615,13 +651,13 @@
 }
 
 //////////////////////////////////////////////////////////////////////
-/// Reads the encoded PGF headers and copies it to a target buffer.
+/// Reads the encoded PGF header and copies it to a target buffer.
 /// Precondition: The PGF image has been opened with a call of Open(...).
 /// It might throw an IOException.
 /// @param target The target buffer
 /// @param targetLen The length of the target buffer in bytes
 /// @return The number of bytes copied to the target buffer
-UINT32 CPGFImage::ReadEncodedHeader(UINT8* target, UINT32 targetLen) const THROW_ {
+UINT32 CPGFImage::ReadEncodedHeader(UINT8* target, UINT32 targetLen) const {
 	ASSERT(target);
 	ASSERT(targetLen > 0);
 	ASSERT(m_decoder);
@@ -640,10 +676,22 @@
 }
 
 ////////////////////////////////////////////////////////////////////
-/// Reset stream position to start of PGF pre-header
-void CPGFImage::ResetStreamPos() THROW_ {
-	ASSERT(m_decoder);
-	return m_decoder->SetStreamPosToStart(); 
+/// Reset stream position to start of PGF pre-header or start of data. Must not be called before Open() or before Write(). 
+/// Use this method after Read() if you want to read the same image several times, e.g. reading different ROIs.
+/// @param startOfData true: you want to read the same image several times. false: resets stream position to the initial position
+void CPGFImage::ResetStreamPos(bool startOfData) {
+	if (startOfData) {
+		ASSERT(m_decoder);
+		m_decoder->SetStreamPosToData();
+	} else {
+		if (m_decoder) {
+			m_decoder->SetStreamPosToStart();
+		} else if (m_encoder) {
+			m_encoder->SetStreamPosToStart();
+		} else {
+			ASSERT(false);
+		}
+	}
 }
 
 //////////////////////////////////////////////////////////////////////
@@ -655,7 +703,7 @@
 /// @param target The target buffer
 /// @param targetLen The length of the target buffer in bytes
 /// @return The number of bytes copied to the target buffer
-UINT32 CPGFImage::ReadEncodedData(int level, UINT8* target, UINT32 targetLen) const THROW_ {
+UINT32 CPGFImage::ReadEncodedData(int level, UINT8* target, UINT32 targetLen) const {
 	ASSERT(level >= 0 && level < m_header.nLevels);
 	ASSERT(target);
 	ASSERT(targetLen > 0);
@@ -715,8 +763,9 @@
 }
 
 //////////////////////////////////////////////////////////////////////
-/// Return version
-BYTE CPGFImage::CurrentVersion(BYTE version) {
+/// Return major version
+BYTE CPGFImage::CodecMajorVersion(BYTE version) {
+	if (version & Version7) return 7;
 	if (version & Version6) return 6;
 	if (version & Version5) return 5;
 	if (version & Version2) return 2;
@@ -739,7 +788,7 @@
 // @param channelMap A integer array containing the mapping of input channel ordering to expected channel ordering.
 // @param cb A pointer to a callback procedure. The procedure is called after each imported buffer row. If cb returns true, then it stops proceeding.
 // @param data Data Pointer to C++ class container to host callback procedure.
-void CPGFImage::ImportBitmap(int pitch, UINT8 *buff, BYTE bpp, int channelMap[] /*= NULL */, CallbackPtr cb /*= NULL*/, void *data /*=NULL*/) THROW_ {
+void CPGFImage::ImportBitmap(int pitch, UINT8 *buff, BYTE bpp, int channelMap[] /*= nullptr */, CallbackPtr cb /*= nullptr*/, void *data /*=nullptr*/) {
 	ASSERT(buff);
 	ASSERT(m_channel[0]);
 
@@ -756,6 +805,7 @@
 
 /////////////////////////////////////////////////////////////////
 // Bilinerar Subsampling of channel ch by a factor 2
+// Called before Write()
 void CPGFImage::Downsample(int ch) {
 	ASSERT(ch > 0);
 
@@ -801,7 +851,7 @@
 
 //////////////////////////////////////////////////////////////////////
 void CPGFImage::ComputeLevels() {
-	const int maxThumbnailWidth = 20*FilterWidth;
+	const int maxThumbnailWidth = 20*FilterSize;
 	const int m = __min(m_header.width, m_header.height);
 	int s = m;
 
@@ -810,17 +860,17 @@
 		// compute a good value depending on the size of the image
 		while (s > maxThumbnailWidth) {
 			m_header.nLevels++;
-			s = s/2;
+			s >>= 1;
 		}
 	}
 
 	int levels = m_header.nLevels; // we need a signed value during level reduction
 
-	// reduce number of levels if the image size is smaller than FilterWidth*2^levels
-	s = FilterWidth*(1 << levels);	// must be at least the double filter size because of subsampling
+	// reduce number of levels if the image size is smaller than FilterSize*(2^levels)
+	s = FilterSize*(1 << levels);	// must be at least the double filter size because of subsampling
 	while (m < s) {
 		levels--;
-		s = s/2;
+		s >>= 1;
 	}
 	if (levels > MaxLevel) m_header.nLevels = MaxLevel;
 	else if (levels < 0) m_header.nLevels = 0;
@@ -834,16 +884,17 @@
 
 //////////////////////////////////////////////////////////////////////
 /// Set PGF header and user data.
-/// Precondition: The PGF image has been closed with Close(...) or never opened with Open(...).
+/// Precondition: The PGF image has been never opened with Open(...).
 /// It might throw an IOException.
 /// @param header A valid and already filled in PGF header structure
 /// @param flags A combination of additional version flags. In case you use level-wise encoding then set flag = PGFROI.
 /// @param userData A user-defined memory block containing any kind of cached metadata.
 /// @param userDataLength The size of user-defined memory block in bytes
-void CPGFImage::SetHeader(const PGFHeader& header, BYTE flags /*=0*/, UINT8* userData /*= 0*/, UINT32 userDataLength /*= 0*/) THROW_ {
+void CPGFImage::SetHeader(const PGFHeader& header, BYTE flags /*=0*/, const UINT8* userData /*= 0*/, UINT32 userDataLength /*= 0*/) {
 	ASSERT(!m_decoder);	// current image must be closed
 	ASSERT(header.quality <= MaxQuality);
-
+	ASSERT(userDataLength <= MaxUserDataSize);
+	
 	// init state
 #ifdef __PGFROISUPPORT__
 	m_streamReinitialized = false;
@@ -856,6 +907,9 @@
 
 	// copy header
 	memcpy(&m_header, &header, HeaderSize);
+
+	// check quality
+	if (m_header.quality > MaxQuality) m_header.quality = MaxQuality;
 
 	// complete header
 	CompleteHeader();
@@ -884,9 +938,10 @@
 		m_preHeader.hSize += ColorTableSize;
 	}
 	if (userDataLength && userData) {
+		if (userDataLength > MaxUserDataSize) userDataLength = MaxUserDataSize;
 		m_postHeader.userData = new(std::nothrow) UINT8[userDataLength];
 		if (!m_postHeader.userData) ReturnWithError(InsufficientMemory);
-		m_postHeader.userDataLen = userDataLength;
+		m_postHeader.userDataLen = m_postHeader.cachedUserDataLen = userDataLength;
 		memcpy(m_postHeader.userData, userData, userDataLength);
 		// update header size
 		m_preHeader.hSize += userDataLength;
@@ -914,12 +969,13 @@
 
 //////////////////////////////////////////////////////////////////
 /// Create wavelet transform channels and encoder. Write header at current stream position.
+/// Performs forward FWT.
 /// Call this method before your first call of Write(int level) or WriteImage(), but after SetHeader().
 /// This method is called inside of Write(stream, ...).
 /// It might throw an IOException.
 /// @param stream A PGF stream
 /// @return The number of bytes written into stream.
-UINT32 CPGFImage::WriteHeader(CPGFStream* stream) THROW_ {
+UINT32 CPGFImage::WriteHeader(CPGFStream* stream) {
 	ASSERT(m_header.nLevels <= MaxLevel);
 	ASSERT(m_header.quality <= MaxQuality); // quality is already initialized
 
@@ -978,7 +1034,7 @@
 
 		m_currentLevel = m_header.nLevels;
 
-		// create encoder and eventually write headers and levelLength
+		// create encoder, write headers and user data, but not level-length area
 		m_encoder = new CEncoder(stream, m_preHeader, m_header, m_postHeader, m_userDataPos, m_useOMPinEncoder);
 		if (m_favorSpeedOverSize) m_encoder->FavorSpeedOverSize();
 
@@ -992,7 +1048,7 @@
 	} else {
 		// very small image: we don't use DWT and encoding
 
-		// create encoder and eventually write headers and levelLength
+		// create encoder, write headers and user data, but not level-length area
 		m_encoder = new CEncoder(stream, m_preHeader, m_header, m_postHeader, m_userDataPos, m_useOMPinEncoder);
 	}
 
@@ -1008,7 +1064,7 @@
 // The image size at level i is double the size (width, height) of the image at level i+1.
 // The image at level 0 contains the original size.
 // It might throw an IOException.
-void CPGFImage::WriteLevel() THROW_ {
+void CPGFImage::WriteLevel() {
 	ASSERT(m_encoder);
 	ASSERT(m_currentLevel > 0);
 	ASSERT(m_header.nLevels > 0);
@@ -1026,18 +1082,19 @@
 				// last level also has LL band
 				ASSERT(nTiles == 1);
 				m_wtChannel[i]->GetSubband(m_currentLevel, LL)->ExtractTile(*m_encoder);
-				m_encoder->EncodeTileBuffer();
+				m_encoder->EncodeTileBuffer(); // encode macro block with tile-end = true
 			}
 			for (UINT32 tileY=0; tileY < nTiles; tileY++) {
 				for (UINT32 tileX=0; tileX < nTiles; tileX++) {
+					// extract tile to macro block and encode already filled macro blocks with tile-end = false
 					m_wtChannel[i]->GetSubband(m_currentLevel, HL)->ExtractTile(*m_encoder, true, tileX, tileY);
 					m_wtChannel[i]->GetSubband(m_currentLevel, LH)->ExtractTile(*m_encoder, true, tileX, tileY);
 					m_wtChannel[i]->GetSubband(m_currentLevel, HH)->ExtractTile(*m_encoder, true, tileX, tileY);
 					if (i == lastChannel && tileY == lastTile && tileX == lastTile) {
-						// all necessary data are buffered. next call of EncodeBuffer will write the last piece of data of the current level.
+						// all necessary data are buffered. next call of EncodeTileBuffer will write the last piece of data of the current level.
 						m_encoder->SetEncodedLevel(--m_currentLevel);
 					}
-					m_encoder->EncodeTileBuffer();
+					m_encoder->EncodeTileBuffer(); // encode last macro block with tile-end = true
 				}
 			}
 		}
@@ -1063,7 +1120,7 @@
 
 //////////////////////////////////////////////////////////////////////
 // Return written levelLength bytes
-UINT32 CPGFImage::UpdatePostHeaderSize() THROW_ {
+UINT32 CPGFImage::UpdatePostHeaderSize() {
 	ASSERT(m_encoder);
 
 	INT64 offset = m_encoder->ComputeOffset(); ASSERT(offset >= 0);
@@ -1079,8 +1136,9 @@
 }
 
 //////////////////////////////////////////////////////////////////////
-/// Encode and write the one and only image at current stream position.
-/// Call this method after WriteHeader(). In case you want to write uncached metadata, 
+/// Encode and write an image at current stream position.
+/// Call this method after WriteHeader(). 
+/// In case you want to write uncached metadata, 
 /// then do that after WriteHeader() and before WriteImage(). 
 /// This method is called inside of Write(stream, ...).
 /// It might throw an IOException.
@@ -1088,7 +1146,7 @@
 /// @param cb A pointer to a callback procedure. The procedure is called after writing a single level. If cb returns true, then it stops proceeding.
 /// @param data Data Pointer to C++ class container to host callback procedure.
 /// @return The number of bytes written into stream.
-UINT32 CPGFImage::WriteImage(CPGFStream* stream, CallbackPtr cb /*= NULL*/, void *data /*= NULL*/) THROW_ {
+UINT32 CPGFImage::WriteImage(CPGFStream* stream, CallbackPtr cb /*= nullptr*/, void *data /*= nullptr*/) {
 	ASSERT(stream);
 	ASSERT(m_preHeader.hSize);
 
@@ -1099,7 +1157,7 @@
 	UINT32 nWrittenBytes = UpdatePostHeaderSize();
 
 	if (levels == 0) {
-		// write channels
+		// for very small images: write channels uncoded
 		for (int c=0; c < m_header.channels; c++) {
 			const UINT32 size = m_width[c]*m_height[c];
 
@@ -1139,7 +1197,7 @@
 	nWrittenBytes += m_encoder->UpdateLevelLength(); // return written image bytes 
 
 	// delete encoder
-	delete m_encoder; m_encoder = NULL;
+	delete m_encoder; m_encoder = nullptr;
 
 	ASSERT(!m_encoder);
 
@@ -1147,7 +1205,7 @@
 }
 
 //////////////////////////////////////////////////////////////////
-/// Encode and write a entire PGF image (header and image) at current stream position.
+/// Encode and write an entire PGF image (header and image) at current stream position.
 /// A PGF image is structered in levels, numbered between 0 and Levels() - 1.
 /// Each level can be seen as a single image, containing the same content
 /// as all other levels, but in a different size (width, height).
@@ -1159,7 +1217,7 @@
 /// @param nWrittenBytes [in-out] The number of bytes written into stream are added to the input value.
 /// @param cb A pointer to a callback procedure. The procedure is called after writing a single level. If cb returns true, then it stops proceeding.
 /// @param data Data Pointer to C++ class container to host callback procedure.
-void CPGFImage::Write(CPGFStream* stream, UINT32* nWrittenBytes /*= NULL*/, CallbackPtr cb /*= NULL*/, void *data /*=NULL*/) THROW_ {
+void CPGFImage::Write(CPGFStream* stream, UINT32* nWrittenBytes /*= nullptr*/, CallbackPtr cb /*= nullptr*/, void *data /*=nullptr*/) {
 	ASSERT(stream);
 	ASSERT(m_preHeader.hSize);
 
@@ -1181,14 +1239,14 @@
 // as all other levels, but in a different size (width, height).
 // The image size at level i is double the size (width, height) of the image at level i+1.
 // The image at level 0 contains the original size.
-// Precondition: the PGF image contains a valid header (see also SetHeader(...)) and WriteHeader() has been called before Write().
+// Precondition: the PGF image contains a valid header (see also SetHeader(...)) and WriteHeader() has been called before.
 // The ROI encoding scheme is used.
 // It might throw an IOException.
 // @param level The image level of the resulting image in the internal image buffer.
 // @param cb A pointer to a callback procedure. The procedure is called after writing a single level. If cb returns true, then it stops proceeding.
 // @param data Data Pointer to C++ class container to host callback procedure.
 // @return The number of bytes written into stream.
-UINT32 CPGFImage::Write(int level, CallbackPtr cb /*= NULL*/, void *data /*=NULL*/) THROW_ {
+UINT32 CPGFImage::Write(int level, CallbackPtr cb /*= nullptr*/, void *data /*=nullptr*/) {
 	ASSERT(m_header.nLevels > 0);
 	ASSERT(0 <= level && level < m_header.nLevels);
 	ASSERT(m_encoder);
@@ -1288,7 +1346,7 @@
 /// @param iFirstColor The color table index of the first entry to retrieve.
 /// @param nColors The number of color table entries to retrieve.
 /// @param prgbColors A pointer to the array of RGBQUAD structures to retrieve the color table entries.
-void CPGFImage::GetColorTable(UINT32 iFirstColor, UINT32 nColors, RGBQUAD* prgbColors) const THROW_ {
+void CPGFImage::GetColorTable(UINT32 iFirstColor, UINT32 nColors, RGBQUAD* prgbColors) const {
 	if (iFirstColor + nColors > ColorTableLen)	ReturnWithError(ColorTableError);
 
 	for (UINT32 i=iFirstColor, j=0; j < nColors; i++, j++) {
@@ -1302,7 +1360,7 @@
 /// @param iFirstColor The color table index of the first entry to set.
 /// @param nColors The number of color table entries to set.
 /// @param prgbColors A pointer to the array of RGBQUAD structures to set the color table entries.
-void CPGFImage::SetColorTable(UINT32 iFirstColor, UINT32 nColors, const RGBQUAD* prgbColors) THROW_ {
+void CPGFImage::SetColorTable(UINT32 iFirstColor, UINT32 nColors, const RGBQUAD* prgbColors) {
 	if (iFirstColor + nColors > ColorTableLen)	ReturnWithError(ColorTableError);
 
 	for (UINT32 i=iFirstColor, j=0; j < nColors; i++, j++) {
@@ -1327,9 +1385,9 @@
 // The sequence of input channels in the input image buffer does not need to be the same as expected from PGF. In case of different sequences you have to
 // provide a channelMap of size of expected channels (depending on image mode). For example, PGF expects in RGB color mode a channel sequence BGR.
 // If your provided image buffer contains a channel sequence ARGB, then the channelMap looks like { 3, 2, 1 }.
-void CPGFImage::RgbToYuv(int pitch, UINT8* buff, BYTE bpp, int channelMap[], CallbackPtr cb, void *data /*=NULL*/) THROW_ {
+void CPGFImage::RgbToYuv(int pitch, UINT8* buff, BYTE bpp, int channelMap[], CallbackPtr cb, void *data /*=nullptr*/) {
 	ASSERT(buff);
-	int yPos = 0, cnt = 0;
+	UINT32 yPos = 0, cnt = 0;
 	double percent = 0;
 	const double dP = 1.0/m_header.height;
 	int defMap[] = { 0, 1, 2, 3, 4, 5, 6, 7 }; ASSERT(sizeof(defMap)/sizeof(defMap[0]) == MaxChannels);
@@ -1347,30 +1405,41 @@
 			const UINT32 w2 = (m_header.width + 7)/8;
 			DataT* y = m_channel[0]; ASSERT(y);
 
-			for (UINT32 h=0; h < m_header.height; h++) {
+			// new unpacked version since version 7
+			for (UINT32 h = 0; h < m_header.height; h++) {
 				if (cb) {
 					if ((*cb)(percent, true, data)) ReturnWithError(EscapePressed);
 					percent += dP;
 				}
-				
-				for (UINT32 j=0; j < w2; j++) {
+				cnt = 0;
+				for (UINT32 j = 0; j < w2; j++) {
+					UINT8 byte = buff[j];
+					for (int k = 0; k < 8; k++) {
+						UINT8 bit = (byte & 0x80) >> 7;
+						if (cnt < w) y[yPos++] = bit;
+						byte <<= 1;
+						cnt++;
+					}
+				}
+				buff += pitch;
+			}
+			/* old version: packed values: 8 pixels in 1 byte
+			for (UINT32 h = 0; h < m_header.height; h++) {
+				if (cb) {
+					if ((*cb)(percent, true, data)) ReturnWithError(EscapePressed);
+					percent += dP;
+				}
+
+				for (UINT32 j = 0; j < w2; j++) {
 					y[yPos++] = buff[j] - YUVoffset8;
 				}
-				for (UINT32 j=w2; j < w; j++) {
-					y[yPos++] = YUVoffset8;
-				}
-				
-				//UINT cnt = w;
-				//for (UINT32 j=0; j < w2; j++) {
-				//	for (int k=7; k >= 0; k--) {
-				//		if (cnt) { 
-				//			y[yPos++] = YUVoffset8 + (1 & (buff[j] >> k));
-				//			cnt--;
-				//		}
-				//	}
+				// version 5 and 6
+				// for (UINT32 j = w2; j < w; j++) {
+				//	y[yPos++] = YUVoffset8;
 				//}
-				buff += pitch;	
-			}
+				buff += pitch;
+			}
+			*/
 		}
 		break;
 	case ImageModeIndexedColor:
@@ -1716,40 +1785,44 @@
 // @param channelMap A integer array containing the mapping of PGF channel ordering to expected channel ordering.
 // @param cb A pointer to a callback procedure. The procedure is called after each copied buffer row. If cb returns true, then it stops proceeding.
 // @param data Data Pointer to C++ class container to host callback procedure.
-void CPGFImage::GetBitmap(int pitch, UINT8* buff, BYTE bpp, int channelMap[] /*= NULL */, CallbackPtr cb /*= NULL*/, void *data /*=NULL*/) const THROW_ {
+void CPGFImage::GetBitmap(int pitch, UINT8* buff, BYTE bpp, int channelMap[] /*= nullptr */, CallbackPtr cb /*= nullptr*/, void *data /*=nullptr*/) const {
 	ASSERT(buff);
-	UINT32 w = m_width[0];
-	UINT32 h = m_height[0];
-	UINT8* targetBuff = 0;	// used if ROI is used
-	UINT8* buffStart = 0;	// used if ROI is used
-	int targetPitch = 0;	// used if ROI is used
+	UINT32 w = m_width[0];  // width of decoded image
+	UINT32 h = m_height[0]; // height of decoded image
+	UINT32 yw = w;			// y-channel width
+	UINT32 uw = m_width[1];	// u-channel width
+	UINT32 roiOffsetX = 0;
+	UINT32 roiOffsetY = 0;
+	UINT32 yOffset = 0;
+	UINT32 uOffset = 0;
 
 #ifdef __PGFROISUPPORT__
-	const PGFRect& roi = (ROIisSupported()) ? m_wtChannel[0]->GetROI(m_currentLevel) : PGFRect(0, 0, w, h); // roi is usually larger than m_roi
-	const PGFRect levelRoi(LevelWidth(m_roi.left, m_currentLevel), LevelHeight(m_roi.top, m_currentLevel), LevelWidth(m_roi.Width(), m_currentLevel), LevelHeight(m_roi.Height(), m_currentLevel));
-	ASSERT(w <= roi.Width() && h <= roi.Height()); 
+	const PGFRect& roi = GetAlignedROI(); // in pixels, roi is usually larger than levelRoi
+	ASSERT(w == roi.Width() && h == roi.Height());
+	const PGFRect levelRoi = ComputeLevelROI();
 	ASSERT(roi.left <= levelRoi.left && levelRoi.right <= roi.right); 
 	ASSERT(roi.top <= levelRoi.top && levelRoi.bottom <= roi.bottom); 
 
 	if (ROIisSupported() && (levelRoi.Width() < w || levelRoi.Height() < h)) {
-		// ROI is used -> create a temporary image buffer for roi
-		// compute pitch
-		targetPitch = pitch;
-		pitch = AlignWordPos(w*bpp)/8;
-
-		// create temporary output buffer
-		targetBuff = buff;
-		buff = buffStart = new(std::nothrow) UINT8[pitch*h];
-		if (!buff) ReturnWithError(InsufficientMemory);
+		// ROI is used 
+		w = levelRoi.Width();
+		h = levelRoi.Height();
+		roiOffsetX = levelRoi.left - roi.left;
+		roiOffsetY = levelRoi.top - roi.top;
+		yOffset = roiOffsetX + roiOffsetY*yw;
+
+		if (m_downsample) {
+			const PGFRect& downsampledRoi = GetAlignedROI(1);
+			uOffset = levelRoi.left/2 - downsampledRoi.left + (levelRoi.top/2 - downsampledRoi.top)*m_width[1];
+		} else {
+			uOffset = yOffset;
+		}
 	}
 #endif
-
-	const bool wOdd = (1 == w%2);
 
 	const double dP = 1.0/h;
 	int defMap[] = { 0, 1, 2, 3, 4, 5, 6, 7 }; ASSERT(sizeof(defMap)/sizeof(defMap[0]) == MaxChannels);
-	if (channelMap == NULL) channelMap = defMap;
-	int sampledPos = 0, yPos = 0;
+	if (channelMap == nullptr) channelMap = defMap;
 	DataT uAvg, vAvg;
 	double percent = 0;
 	UINT32 i, j;
@@ -1764,29 +1837,48 @@
 			const UINT32 w2 = (w + 7)/8;
 			DataT* y = m_channel[0]; ASSERT(y);
 
-			for (i=0; i < h; i++) {
-				
-				for (j=0; j < w2; j++) {
-					buff[j] = Clamp8(y[yPos++] + YUVoffset8);
-				}
-				yPos += w - w2;
-				
-				//UINT32 cnt = w;
-				//for (j=0; j < w2; j++) {
-				//	buff[j] = 0;
-				//	for (int k=0; k < 8; k++) {
-				//		if (cnt) {
-				//			buff[j] <<= 1;
-				//			buff[j] |= (1 & (y[yPos++] - YUVoffset8)); 
-				//			cnt--;
-				//		}
-				//	}
-				//}
-				buff += pitch;
-
-				if (cb) {
-					percent += dP;
-					if ((*cb)(percent, true, data)) ReturnWithError(EscapePressed);
+			if (m_preHeader.version & Version7) {
+				// new unpacked version has a little better compression ratio
+				// since version 7
+				for (i = 0; i < h; i++) {
+					UINT32 cnt = 0;
+					for (j = 0; j < w2; j++) {
+						UINT8 byte = 0;
+						for (int k = 0; k < 8; k++) {
+							byte <<= 1;
+							UINT8 bit = 0;
+							if (cnt < w) {
+								bit = y[yOffset + cnt] & 1;
+							}
+							byte |= bit;
+							cnt++;
+						}
+						buff[j] = byte;
+					}
+					yOffset += yw;
+					buff += pitch;
+
+					if (cb) {
+						percent += dP;
+						if ((*cb)(percent, true, data)) ReturnWithError(EscapePressed);
+					}
+				}
+			} else {
+				// old versions
+				// packed pixels: 8 pixel in 1 byte of channel[0]
+				if (!(m_preHeader.version & Version5)) yw = w2; // not version 5 or 6
+				yOffset = roiOffsetX/8 + roiOffsetY*yw; // 1 byte in y contains 8 pixel values
+				for (i = 0; i < h; i++) {
+					for (j = 0; j < w2; j++) {
+						buff[j] = Clamp8(y[yOffset + j] + YUVoffset8);
+					}
+					yOffset += yw;
+					buff += pitch;
+
+					if (cb) {
+						percent += dP;
+						if ((*cb)(percent, true, data)) ReturnWithError(EscapePressed);
+					}
 				}
 			}
 			break;
@@ -1800,17 +1892,19 @@
 			ASSERT(m_header.bpp == m_header.channels*8);
 			ASSERT(bpp%8 == 0);
 
-			int cnt, channels = bpp/8; ASSERT(channels >= m_header.channels);
+			UINT32 cnt, channels = bpp/8; ASSERT(channels >= m_header.channels);
 
 			for (i=0; i < h; i++) {
+				UINT32 yPos = yOffset;
 				cnt = 0;
 				for (j=0; j < w; j++) {
-					for (int c=0; c < m_header.channels; c++) {
+					for (UINT32 c=0; c < m_header.channels; c++) {
 						buff[cnt + channelMap[c]] = Clamp8(m_channel[c][yPos] + YUVoffset8);
 					}
 					cnt += channels;
 					yPos++;
 				}
+				yOffset += yw;
 				buff += pitch;
 
 				if (cb) {
@@ -1826,7 +1920,7 @@
 			ASSERT(m_header.bpp == m_header.channels*16);
 
 			const DataT yuvOffset16 = 1 << (UsedBitsPerChannel() - 1);
-			int cnt, channels;
+			UINT32 cnt, channels;
 
 			if (bpp%16 == 0) {
 				const int shift = 16 - UsedBitsPerChannel(); ASSERT(shift >= 0);
@@ -1835,14 +1929,16 @@
 				channels = bpp/16; ASSERT(channels >= m_header.channels);
 
 				for (i=0; i < h; i++) {
+					UINT32 yPos = yOffset;
 					cnt = 0;
 					for (j=0; j < w; j++) {
-						for (int c=0; c < m_header.channels; c++) {
+						for (UINT32 c=0; c < m_header.channels; c++) {
 							buff16[cnt + channelMap[c]] = Clamp16((m_channel[c][yPos] + yuvOffset16) << shift);
 						}
 						cnt += channels;
 						yPos++;
 					}
+					yOffset += yw;
 					buff16 += pitch16;
 
 					if (cb) {
@@ -1856,14 +1952,16 @@
 				channels = bpp/8; ASSERT(channels >= m_header.channels);
 				
 				for (i=0; i < h; i++) {
+					UINT32 yPos = yOffset;
 					cnt = 0;
 					for (j=0; j < w; j++) {
-						for (int c=0; c < m_header.channels; c++) {
+						for (UINT32 c=0; c < m_header.channels; c++) {
 							buff[cnt + channelMap[c]] = Clamp8((m_channel[c][yPos] + yuvOffset16) >> shift);
 						}
 						cnt += channels;
 						yPos++;
 					}
+					yOffset += yw;
 					buff += pitch;
 
 					if (cb) {
@@ -1888,35 +1986,41 @@
 				  *buffr = &buff[channelMap[2]],
 				  *buffb = &buff[channelMap[0]];
 			UINT8 g;
-			int cnt, channels = bpp/8;
-			if(m_downsample){
+			UINT32 cnt, channels = bpp/8;
+
+			if (m_downsample) {
 				for (i=0; i < h; i++) {
-					if (i%2) sampledPos -= (w + 1)/2;
+					UINT32 uPos = uOffset;
+					UINT32 yPos = yOffset;
 					cnt = 0;
 					for (j=0; j < w; j++) {
-						// image was downsampled
-						uAvg = u[sampledPos];
-						vAvg = v[sampledPos];
+						// u and v are downsampled
+						uAvg = u[uPos];
+						vAvg = v[uPos];
 						// Yuv
 						buffg[cnt] = g = Clamp8(y[yPos] + YUVoffset8 - ((uAvg + vAvg ) >> 2)); // must be logical shift operator
 						buffr[cnt] = Clamp8(uAvg + g);
 						buffb[cnt] = Clamp8(vAvg + g);
+						cnt += channels;
+						if (j & 1) uPos++;
 						yPos++;
-						cnt += channels;
-						if (j%2) sampledPos++;
-					}
+					}
+					if (i & 1) uOffset += uw;
+					yOffset += yw;
 					buffb += pitch;
 					buffg += pitch;
 					buffr += pitch;
-					if (wOdd) sampledPos++;
+
 					if (cb) {
 						percent += dP;
 						if ((*cb)(percent, true, data)) ReturnWithError(EscapePressed);
 					}
 				}
-			}else{
+
+			} else {
 				for (i=0; i < h; i++) {
 					cnt = 0;
+					UINT32 yPos = yOffset;
 					for (j = 0; j < w; j++) {
 						uAvg = u[yPos];
 						vAvg = v[yPos];
@@ -1924,9 +2028,10 @@
 						buffg[cnt] = g = Clamp8(y[yPos] + YUVoffset8 - ((uAvg + vAvg ) >> 2)); // must be logical shift operator
 						buffr[cnt] = Clamp8(uAvg + g);
 						buffb[cnt] = Clamp8(vAvg + g);
+						cnt += channels;
 						yPos++;
-						cnt += channels;
-					}
+					}
+					yOffset += yw;
 					buffb += pitch;
 					buffg += pitch;
 					buffr += pitch;
@@ -1949,7 +2054,7 @@
 			DataT* y = m_channel[0]; ASSERT(y);
 			DataT* u = m_channel[1]; ASSERT(u);
 			DataT* v = m_channel[2]; ASSERT(v);
-			int cnt, channels;
+			UINT32 cnt, channels;
 			DataT g;
 
 			if (bpp >= 48 && bpp%16 == 0) {
@@ -1959,28 +2064,24 @@
 				channels = bpp/16; ASSERT(channels >= m_header.channels);
 
 				for (i=0; i < h; i++) {
-					if (i%2) sampledPos -= (w + 1)/2;
+					UINT32 uPos = uOffset;
+					UINT32 yPos = yOffset;
 					cnt = 0;
 					for (j=0; j < w; j++) {
-						if (m_downsample) {
-							// image was downsampled
-							uAvg = u[sampledPos];
-							vAvg = v[sampledPos];
-						} else {
-							uAvg = u[yPos];
-							vAvg = v[yPos];
-						}
+						uAvg = u[uPos];
+						vAvg = v[uPos];
 						// Yuv
 						g = y[yPos] + yuvOffset16 - ((uAvg + vAvg ) >> 2); // must be logical shift operator
 						buff16[cnt + channelMap[1]] = Clamp16(g << shift);
 						buff16[cnt + channelMap[2]] = Clamp16((uAvg + g) << shift);
 						buff16[cnt + channelMap[0]] = Clamp16((vAvg + g) << shift);
-						yPos++; 
 						cnt += channels;
-						if (j%2) sampledPos++;
-					}
+						if (!m_downsample || (j & 1)) uPos++;
+						yPos++;
+					}
+					if (!m_downsample || (i & 1)) uOffset += uw;
+					yOffset += yw;
 					buff16 += pitch16;
-					if (wOdd) sampledPos++;
 
 					if (cb) {
 						percent += dP;
@@ -1993,28 +2094,24 @@
 				channels = bpp/8; ASSERT(channels >= m_header.channels);
 
 				for (i=0; i < h; i++) {
-					if (i%2) sampledPos -= (w + 1)/2;
+					UINT32 uPos = uOffset;
+					UINT32 yPos = yOffset;
 					cnt = 0;
 					for (j=0; j < w; j++) {
-						if (m_downsample) {
-							// image was downsampled
-							uAvg = u[sampledPos];
-							vAvg = v[sampledPos];
-						} else {
-							uAvg = u[yPos];
-							vAvg = v[yPos];
-						}
+						uAvg = u[uPos];
+						vAvg = v[uPos];
 						// Yuv
 						g = y[yPos] + yuvOffset16 - ((uAvg + vAvg ) >> 2); // must be logical shift operator
 						buff[cnt + channelMap[1]] = Clamp8(g >> shift); 
 						buff[cnt + channelMap[2]] = Clamp8((uAvg + g) >> shift);
 						buff[cnt + channelMap[0]] = Clamp8((vAvg + g) >> shift);
-						yPos++; 
 						cnt += channels;
-						if (j%2) sampledPos++;
-					}
+						if (!m_downsample || (j & 1)) uPos++;
+						yPos++;
+					}
+					if (!m_downsample || (i & 1)) uOffset += uw;
+					yOffset += yw;
 					buff += pitch;
-					if (wOdd) sampledPos++;
 
 					if (cb) {
 						percent += dP;
@@ -2033,29 +2130,25 @@
 			DataT* l = m_channel[0]; ASSERT(l);
 			DataT* a = m_channel[1]; ASSERT(a);
 			DataT* b = m_channel[2]; ASSERT(b);
-			int cnt, channels = bpp/8; ASSERT(channels >= m_header.channels);
+			UINT32 cnt, channels = bpp/8; ASSERT(channels >= m_header.channels);
 
 			for (i=0; i < h; i++) {
-				if (i%2) sampledPos -= (w + 1)/2;
+				UINT32 uPos = uOffset;
+				UINT32 yPos = yOffset;
 				cnt = 0;
 				for (j=0; j < w; j++) {
-					if (m_downsample) {
-						// image was downsampled
-						uAvg = a[sampledPos];
-						vAvg = b[sampledPos];
-					} else {
-						uAvg = a[yPos];
-						vAvg = b[yPos];
-					}
+					uAvg = a[uPos];
+					vAvg = b[uPos];
 					buff[cnt + channelMap[0]] = Clamp8(l[yPos] + YUVoffset8);
 					buff[cnt + channelMap[1]] = Clamp8(uAvg + YUVoffset8); 
 					buff[cnt + channelMap[2]] = Clamp8(vAvg + YUVoffset8);
 					cnt += channels;
+					if (!m_downsample || (j & 1)) uPos++;
 					yPos++;
-					if (j%2) sampledPos++;
-				}
+				}
+				if (!m_downsample || (i & 1)) uOffset += uw;
+				yOffset += yw;
 				buff += pitch;
-				if (wOdd) sampledPos++;
 
 				if (cb) {
 					percent += dP;
@@ -2074,7 +2167,7 @@
 			DataT* l = m_channel[0]; ASSERT(l);
 			DataT* a = m_channel[1]; ASSERT(a);
 			DataT* b = m_channel[2]; ASSERT(b);
-			int cnt, channels;
+			UINT32 cnt, channels;
 
 			if (bpp%16 == 0) {
 				const int shift = 16 - UsedBitsPerChannel(); ASSERT(shift >= 0);
@@ -2083,26 +2176,22 @@
 				channels = bpp/16; ASSERT(channels >= m_header.channels);
 
 				for (i=0; i < h; i++) {
-					if (i%2) sampledPos -= (w + 1)/2;
+					UINT32 uPos = uOffset;
+					UINT32 yPos = yOffset;
 					cnt = 0;
 					for (j=0; j < w; j++) {
-						if (m_downsample) {
-							// image was downsampled
-							uAvg = a[sampledPos];
-							vAvg = b[sampledPos];
-						} else {
-							uAvg = a[yPos];
-							vAvg = b[yPos];
-						}
+						uAvg = a[uPos];
+						vAvg = b[uPos];
 						buff16[cnt + channelMap[0]] = Clamp16((l[yPos] + yuvOffset16) << shift);
 						buff16[cnt + channelMap[1]] = Clamp16((uAvg + yuvOffset16) << shift);
 						buff16[cnt + channelMap[2]] = Clamp16((vAvg + yuvOffset16) << shift);
 						cnt += channels;
+						if (!m_downsample || (j & 1)) uPos++;
 						yPos++;
-						if (j%2) sampledPos++;
-					}
+					}
+					if (!m_downsample || (i & 1)) uOffset += uw;
+					yOffset += yw;
 					buff16 += pitch16;
-					if (wOdd) sampledPos++;
 
 					if (cb) {
 						percent += dP;
@@ -2115,26 +2204,22 @@
 				channels = bpp/8; ASSERT(channels >= m_header.channels);
 
 				for (i=0; i < h; i++) {
-					if (i%2) sampledPos -= (w + 1)/2;
+					UINT32 uPos = uOffset;
+					UINT32 yPos = yOffset;
 					cnt = 0;
 					for (j=0; j < w; j++) {
-						if (m_downsample) {
-							// image was downsampled
-							uAvg = a[sampledPos];
-							vAvg = b[sampledPos];
-						} else {
-							uAvg = a[yPos];
-							vAvg = b[yPos];
-						}
+						uAvg = a[uPos];
+						vAvg = b[uPos];
 						buff[cnt + channelMap[0]] = Clamp8((l[yPos] + yuvOffset16) >> shift);
 						buff[cnt + channelMap[1]] = Clamp8((uAvg + yuvOffset16) >> shift);
 						buff[cnt + channelMap[2]] = Clamp8((vAvg + yuvOffset16) >> shift);
 						cnt += channels;
+						if (!m_downsample || (j & 1)) uPos++;
 						yPos++;
-						if (j%2) sampledPos++;
-					}
+					}
+					if (!m_downsample || (i & 1)) uOffset += uw;
+					yOffset += yw;
 					buff += pitch;
-					if (wOdd) sampledPos++;
 
 					if (cb) {
 						percent += dP;
@@ -2156,33 +2241,28 @@
 			DataT* v = m_channel[2]; ASSERT(v);
 			DataT* a = m_channel[3]; ASSERT(a);
 			UINT8 g, aAvg;
-			int cnt, channels = bpp/8; ASSERT(channels >= m_header.channels);
+			UINT32 cnt, channels = bpp/8; ASSERT(channels >= m_header.channels);
 
 			for (i=0; i < h; i++) {
-				if (i%2) sampledPos -= (w + 1)/2;
+				UINT32 uPos = uOffset;
+				UINT32 yPos = yOffset;
 				cnt = 0;
 				for (j=0; j < w; j++) {
-					if (m_downsample) {
-						// image was downsampled
-						uAvg = u[sampledPos];
-						vAvg = v[sampledPos];
-						aAvg = Clamp8(a[sampledPos] + YUVoffset8);
-					} else {
-						uAvg = u[yPos];
-						vAvg = v[yPos];
-						aAvg = Clamp8(a[yPos] + YUVoffset8);
-					}
+					uAvg = u[uPos];
+					vAvg = v[uPos];
+					aAvg = Clamp8(a[uPos] + YUVoffset8);
 					// Yuv
 					buff[cnt + channelMap[1]] = g = Clamp8(y[yPos] + YUVoffset8 - ((uAvg + vAvg ) >> 2)); // must be logical shift operator
 					buff[cnt + channelMap[2]] = Clamp8(uAvg + g);
 					buff[cnt + channelMap[0]] = Clamp8(vAvg + g);
 					buff[cnt + channelMap[3]] = aAvg;
-					yPos++; 
 					cnt += channels;
-					if (j%2) sampledPos++;
-				}
+					if (!m_downsample || (j & 1)) uPos++;
+					yPos++;
+				}
+				if (!m_downsample || (i & 1)) uOffset += uw;
+				yOffset += yw;
 				buff += pitch;
-				if (wOdd) sampledPos++;
 
 				if (cb) {
 					percent += dP;
@@ -2203,7 +2283,7 @@
 			DataT* v = m_channel[2]; ASSERT(v);
 			DataT* a = m_channel[3]; ASSERT(a);
 			DataT g, aAvg;
-			int cnt, channels;
+			UINT32 cnt, channels;
 
 			if (bpp%16 == 0) {
 				const int shift = 16 - UsedBitsPerChannel(); ASSERT(shift >= 0);
@@ -2212,31 +2292,26 @@
 				channels = bpp/16; ASSERT(channels >= m_header.channels);
 
 				for (i=0; i < h; i++) {
-					if (i%2) sampledPos -= (w + 1)/2;
+					UINT32 uPos = uOffset;
+					UINT32 yPos = yOffset;
 					cnt = 0;
 					for (j=0; j < w; j++) {
-						if (m_downsample) {
-							// image was downsampled
-							uAvg = u[sampledPos];
-							vAvg = v[sampledPos];
-							aAvg = a[sampledPos] + yuvOffset16;
-						} else {
-							uAvg = u[yPos];
-							vAvg = v[yPos];
-							aAvg = a[yPos] + yuvOffset16;
-						}
+						uAvg = u[uPos];
+						vAvg = v[uPos];
+						aAvg = a[uPos] + yuvOffset16;
 						// Yuv
 						g = y[yPos] + yuvOffset16 - ((uAvg + vAvg ) >> 2); // must be logical shift operator
 						buff16[cnt + channelMap[1]] = Clamp16(g << shift);
 						buff16[cnt + channelMap[2]] = Clamp16((uAvg + g) << shift);
 						buff16[cnt + channelMap[0]] = Clamp16((vAvg + g) << shift);
 						buff16[cnt + channelMap[3]] = Clamp16(aAvg << shift);
-						yPos++; 
 						cnt += channels;
-						if (j%2) sampledPos++;
-					}
+						if (!m_downsample || (j & 1)) uPos++;
+						yPos++;
+					}
+					if (!m_downsample || (i & 1)) uOffset += uw;
+					yOffset += yw;
 					buff16 += pitch16;
-					if (wOdd) sampledPos++;
 
 					if (cb) {
 						percent += dP;
@@ -2249,31 +2324,26 @@
 				channels = bpp/8; ASSERT(channels >= m_header.channels);
 
 				for (i=0; i < h; i++) {
-					if (i%2) sampledPos -= (w + 1)/2;
+					UINT32 uPos = uOffset;
+					UINT32 yPos = yOffset;
 					cnt = 0;
 					for (j=0; j < w; j++) {
-						if (m_downsample) {
-							// image was downsampled
-							uAvg = u[sampledPos];
-							vAvg = v[sampledPos];
-							aAvg = a[sampledPos] + yuvOffset16;
-						} else {
-							uAvg = u[yPos];
-							vAvg = v[yPos];
-							aAvg = a[yPos] + yuvOffset16;
-						}
+						uAvg = u[uPos];
+						vAvg = v[uPos];
+						aAvg = a[uPos] + yuvOffset16;
 						// Yuv
 						g = y[yPos] + yuvOffset16 - ((uAvg + vAvg ) >> 2); // must be logical shift operator
 						buff[cnt + channelMap[1]] = Clamp8(g >> shift); 
 						buff[cnt + channelMap[2]] = Clamp8((uAvg + g) >> shift);
 						buff[cnt + channelMap[0]] = Clamp8((vAvg + g) >> shift);
 						buff[cnt + channelMap[3]] = Clamp8(aAvg >> shift);
-						yPos++; 
 						cnt += channels;
-						if (j%2) sampledPos++;
-					}
+						if (!m_downsample || (j & 1)) uPos++;
+						yPos++;
+					}
+					if (!m_downsample || (i & 1)) uOffset += uw;
+					yOffset += yw;
 					buff += pitch;
-					if (wOdd) sampledPos++;
 
 					if (cb) {
 						percent += dP;
@@ -2290,7 +2360,6 @@
 			ASSERT(m_header.bpp == 32);
 
 			const int yuvOffset31 = 1 << (UsedBitsPerChannel() - 1);
-
 			DataT* y = m_channel[0]; ASSERT(y);
 
 			if (bpp == 32) {
@@ -2299,9 +2368,11 @@
 				int pitch32 = pitch/4;
 
 				for (i=0; i < h; i++) {
-					for (j=0; j < w; j++) {
+					UINT32 yPos = yOffset;
+					for (j = 0; j < w; j++) {
 						buff32[j] = Clamp31((y[yPos++] + yuvOffset31) << shift);
 					}
+					yOffset += yw;
 					buff32 += pitch32;
 
 					if (cb) {
@@ -2317,9 +2388,11 @@
 				if (usedBits < 16) {
 					const int shift = 16 - usedBits;
 					for (i=0; i < h; i++) {
-						for (j=0; j < w; j++) {
+						UINT32 yPos = yOffset;
+						for (j = 0; j < w; j++) {
 							buff16[j] = Clamp16((y[yPos++] + yuvOffset31) << shift);
 						}
+						yOffset += yw;
 						buff16 += pitch16;
 
 						if (cb) {
@@ -2330,9 +2403,11 @@
 				} else {
 					const int shift = __max(0, usedBits - 16);
 					for (i=0; i < h; i++) {
-						for (j=0; j < w; j++) {
+						UINT32 yPos = yOffset;
+						for (j = 0; j < w; j++) {
 							buff16[j] = Clamp16((y[yPos++] + yuvOffset31) >> shift);
 						}
+						yOffset += yw;
 						buff16 += pitch16;
 
 						if (cb) {
@@ -2346,9 +2421,11 @@
 				const int shift = __max(0, UsedBitsPerChannel() - 8);
 				
 				for (i=0; i < h; i++) {
-					for (j=0; j < w; j++) {
+					UINT32 yPos = yOffset;
+					for (j = 0; j < w; j++) {
 						buff[j] = Clamp8((y[yPos++] + yuvOffset31) >> shift);
 					}
+					yOffset += yw;
 					buff += pitch;
 
 					if (cb) {
@@ -2371,15 +2448,16 @@
 			DataT* u = m_channel[1]; ASSERT(u);
 			DataT* v = m_channel[2]; ASSERT(v);
 			UINT16 yval;
-			int cnt;
+			UINT32 cnt;
 
 			for (i=0; i < h; i++) {
+				UINT32 yPos = yOffset;
 				cnt = 0;
 				for (j=0; j < w; j++) {
 					// Yuv
 					uAvg = u[yPos];
 					vAvg = v[yPos];
-					yval = Clamp4(y[yPos++] + YUVoffset4 - ((uAvg + vAvg ) >> 2)); // must be logical shift operator
+					yval = Clamp4(y[yPos] + YUVoffset4 - ((uAvg + vAvg ) >> 2)); // must be logical shift operator
 					if (j%2 == 0) {
 						buff[cnt] = UINT8(Clamp4(vAvg + yval) | (yval << 4));
 						cnt++;
@@ -2390,7 +2468,9 @@
 						buff[cnt] = UINT8(yval | (Clamp4(uAvg + yval) << 4));
 						cnt++;
 					}
-				}
+					yPos++;
+				}
+				yOffset += yw;
 				buff += pitch;
 
 				if (cb) {
@@ -2415,13 +2495,15 @@
 			int pitch16 = pitch/2;
 
 			for (i=0; i < h; i++) {
-				for (j=0; j < w; j++) {
+				UINT32 yPos = yOffset;
+				for (j = 0; j < w; j++) {
 					// Yuv
 					uAvg = u[yPos];
 					vAvg = v[yPos];
 					yval = Clamp6(y[yPos++] + YUVoffset6 - ((uAvg + vAvg ) >> 2)); // must be logical shift operator
 					buff16[j] = (yval << 5) | ((Clamp6(uAvg + yval) >> 1) << 11) | (Clamp6(vAvg + yval) >> 1);
 				}
+				yOffset += yw;
 				buff16 += pitch16;
 
 				if (cb) {
@@ -2435,29 +2517,19 @@
 		ASSERT(false);
 	}
 
-#ifdef __PGFROISUPPORT__
-	if (targetBuff) {
-		// copy valid ROI (m_roi) from temporary buffer (roi) to target buffer
-		if (bpp%8 == 0) {
-			BYTE bypp = bpp/8;
-			buff = buffStart + (levelRoi.top - roi.top)*pitch + (levelRoi.left - roi.left)*bypp;
-			w = levelRoi.Width()*bypp;
-			h = levelRoi.Height();
-
-			for (i=0; i < h; i++) {
-				for (j=0; j < w; j++) {
-					targetBuff[j] = buff[j];
-				}
-				targetBuff += targetPitch;
-				buff += pitch;
-			}
-		} else {
-			// to do
-		}
-
-		delete[] buffStart; buffStart = 0;
+#ifdef _DEBUG
+	// display ROI (RGB) in debugger
+	roiimage.width = w;
+	roiimage.height = h;
+	if (pitch > 0) {
+		roiimage.pitch = pitch;
+		roiimage.data = buff;
+	} else {
+		roiimage.pitch = -pitch;
+		roiimage.data = buff + (h - 1)*pitch;
 	}
 #endif
+
 }			
 
 //////////////////////////////////////////////////////////////////////
@@ -2474,7 +2546,7 @@
 /// @param bpp The number of bits per pixel used in image buffer.
 /// @param channelMap A integer array containing the mapping of PGF channel ordering to expected channel ordering.
 /// @param cb A pointer to a callback procedure. The procedure is called after each copied buffer row. If cb returns true, then it stops proceeding.
-void CPGFImage::GetYUV(int pitch, DataT* buff, BYTE bpp, int channelMap[] /*= NULL*/, CallbackPtr cb /*= NULL*/, void *data /*=NULL*/) const THROW_ {
+void CPGFImage::GetYUV(int pitch, DataT* buff, BYTE bpp, int channelMap[] /*= nullptr*/, CallbackPtr cb /*= nullptr*/, void *data /*=nullptr*/) const {
 	ASSERT(buff);
 	const UINT32 w = m_width[0];
 	const UINT32 h = m_height[0];
@@ -2485,7 +2557,7 @@
 	const double dP = 1.0/h;
 
 	int defMap[] = { 0, 1, 2, 3, 4, 5, 6, 7 }; ASSERT(sizeof(defMap)/sizeof(defMap[0]) == MaxChannels);
-	if (channelMap == NULL) channelMap = defMap;
+	if (channelMap == nullptr) channelMap = defMap;
 	int sampledPos = 0, yPos = 0;
 	DataT uAvg, vAvg;
 	double percent = 0;
@@ -2585,7 +2657,7 @@
 /// @param bpp The number of bits per pixel used in image buffer.
 /// @param channelMap A integer array containing the mapping of input channel ordering to expected channel ordering.
 /// @param cb A pointer to a callback procedure. The procedure is called after each imported buffer row. If cb returns true, then it stops proceeding.
-void CPGFImage::ImportYUV(int pitch, DataT *buff, BYTE bpp, int channelMap[] /*= NULL*/, CallbackPtr cb /*= NULL*/, void *data /*=NULL*/) THROW_ {
+void CPGFImage::ImportYUV(int pitch, DataT *buff, BYTE bpp, int channelMap[] /*= nullptr*/, CallbackPtr cb /*= nullptr*/, void *data /*=nullptr*/) {
 	ASSERT(buff);
 	const double dP = 1.0/m_header.height;
 	const int dataBits = DataTSize*8; ASSERT(dataBits == 16 || dataBits == 32);
@@ -2596,7 +2668,7 @@
 	double percent = 0;
 	int defMap[] = { 0, 1, 2, 3, 4, 5, 6, 7 }; ASSERT(sizeof(defMap)/sizeof(defMap[0]) == MaxChannels);
 
-	if (channelMap == NULL) channelMap = defMap;
+	if (channelMap == nullptr) channelMap = defMap;
 
 	if (m_header.channels == 3)	{
 		ASSERT(bpp%dataBits == 0);

Modified: trunk/Scribus/scribus/third_party/pgf/PGFimage.h
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=23713&path=/trunk/Scribus/scribus/third_party/pgf/PGFimage.h
==============================================================================
--- trunk/Scribus/scribus/third_party/pgf/PGFimage.h	(original)
+++ trunk/Scribus/scribus/third_party/pgf/PGFimage.h	Fri May  8 16:40:48 2020
@@ -32,10 +32,6 @@
 #include "PGFstream.h"
 
 //////////////////////////////////////////////////////////////////////
-// types
-enum ProgressMode { PM_Relative, PM_Absolute };
-
-//////////////////////////////////////////////////////////////////////
 // prototypes
 class CDecoder;
 class CEncoder;
@@ -45,46 +41,40 @@
 /// PGF image class is the main class. You always need a PGF object
 /// for encoding or decoding image data.
 /// Decoding:
-///		pgf.Open(...)
-///		pgf.Read(...)
-///		pgf.GetBitmap(...)
+///		Open()
+///		Read()
+///		GetBitmap()
 /// Encoding:
-///		pgf.SetHeader(...)
-///		pgf.ImportBitmap(...)
-///		pgf.Write(...)
+///		SetHeader()
+///		ImportBitmap()
+///		Write()
 /// @author C. Stamm, R. Spuler
 /// @brief PGF main class
 class CPGFImage {
 public:
 	
 	//////////////////////////////////////////////////////////////////////
-	/// Standard constructor: It is used to create a PGF instance for opening and reading.
+	/// Standard constructor
 	CPGFImage();
 
 	//////////////////////////////////////////////////////////////////////
-	/// Destructor: Destroy internal data structures.
+	/// Destructor
 	virtual ~CPGFImage();
 
 	//////////////////////////////////////////////////////////////////////
-	/// Close PGF image after opening and reading.
-	/// Destructor calls this method during destruction.
-	virtual void Close();
-
-	//////////////////////////////////////////////////////////////////////
-	/// Destroy internal data structures.
-	/// Destructor calls this method during destruction.
-	virtual void Destroy();
+	// Destroy internal data structures. Object state after this is the same as after CPGFImage().
+	void Destroy();
 
 	//////////////////////////////////////////////////////////////////////
 	/// Open a PGF image at current stream position: read pre-header, header, and ckeck image type.
 	/// Precondition: The stream has been opened for reading.
 	/// It might throw an IOException.
 	/// @param stream A PGF stream
-	void Open(CPGFStream* stream) THROW_;
-
-	//////////////////////////////////////////////////////////////////////
-	/// Returns true if the PGF has been opened and not closed.
-	bool IsOpen() const	{ return m_decoder != NULL; }
+	void Open(CPGFStream* stream);
+
+	//////////////////////////////////////////////////////////////////////
+	/// Returns true if the PGF has been opened for reading.
+	bool IsOpen() const	{ return m_decoder != nullptr; }
 
 	//////////////////////////////////////////////////////////////////////
 	/// Read and decode some levels of a PGF image at current stream position.
@@ -98,7 +88,7 @@
 	/// @param level [0, nLevels) The image level of the resulting image in the internal image buffer.
 	/// @param cb A pointer to a callback procedure. The procedure is called after reading a single level. If cb returns true, then it stops proceeding.
 	/// @param data Data Pointer to C++ class container to host callback procedure.
-	void Read(int level = 0, CallbackPtr cb = NULL, void *data = NULL) THROW_;
+	void Read(int level = 0, CallbackPtr cb = nullptr, void *data = nullptr);
 
 #ifdef __PGFROISUPPORT__
 	//////////////////////////////////////////////////////////////////////
@@ -106,11 +96,11 @@
 	/// The origin of the coordinate axis is the top-left corner of the image.
 	/// All coordinates are measured in pixels.
 	/// It might throw an IOException.
-	/// @param rect [inout] Rectangular region of interest (ROI). The rect might be cropped.
+	/// @param rect [inout] Rectangular region of interest (ROI) at level 0. The rect might be cropped.
 	/// @param level [0, nLevels) The image level of the resulting image in the internal image buffer.
 	/// @param cb A pointer to a callback procedure. The procedure is called after reading a single level. If cb returns true, then it stops proceeding.
 	/// @param data Data Pointer to C++ class container to host callback procedure.
-	void Read(PGFRect& rect, int level = 0, CallbackPtr cb = NULL, void *data = NULL) THROW_;
+	void Read(PGFRect& rect, int level = 0, CallbackPtr cb = nullptr, void *data = nullptr);
 #endif
 
 	//////////////////////////////////////////////////////////////////////
@@ -118,14 +108,14 @@
 	/// For details, please refert to Read(...)
 	/// Precondition: The PGF image has been opened with a call of Open(...).
 	/// It might throw an IOException.
-	void ReadPreview() THROW_										{ Read(Levels() - 1); }
+	void ReadPreview()										{ Read(Levels() - 1); }
 
 	//////////////////////////////////////////////////////////////////////
 	/// After you've written a PGF image, you can call this method followed by GetBitmap/GetYUV
 	/// to get a quick reconstruction (coded -> decoded image).
 	/// It might throw an IOException.
 	/// @param level The image level of the resulting image in the internal image buffer.
-	void Reconstruct(int level = 0) THROW_;
+	void Reconstruct(int level = 0);
 
 	//////////////////////////////////////////////////////////////////////
 	/// Get image data in interleaved format: (ordering of RGB data is BGR[A])
@@ -144,7 +134,7 @@
 	/// @param channelMap A integer array containing the mapping of PGF channel ordering to expected channel ordering.
 	/// @param cb A pointer to a callback procedure. The procedure is called after each copied buffer row. If cb returns true, then it stops proceeding.
 	/// @param data Data Pointer to C++ class container to host callback procedure.
-	void GetBitmap(int pitch, UINT8* buff, BYTE bpp, int channelMap[] = NULL, CallbackPtr cb = NULL, void *data = NULL) const THROW_; // throws IOException
+	void GetBitmap(int pitch, UINT8* buff, BYTE bpp, int channelMap[] = nullptr, CallbackPtr cb = nullptr, void *data = nullptr) const; // throws IOException
 
 	//////////////////////////////////////////////////////////////////////
 	/// Get YUV image data in interleaved format: (ordering is YUV[A])
@@ -161,7 +151,7 @@
 	/// @param channelMap A integer array containing the mapping of PGF channel ordering to expected channel ordering.
 	/// @param cb A pointer to a callback procedure. The procedure is called after each copied buffer row. If cb returns true, then it stops proceeding.
 	/// @param data Data Pointer to C++ class container to host callback procedure.
-	void GetYUV(int pitch, DataT* buff, BYTE bpp, int channelMap[] = NULL, CallbackPtr cb = NULL, void *data = NULL) const THROW_; // throws IOException
+	void GetYUV(int pitch, DataT* buff, BYTE bpp, int channelMap[] = nullptr, CallbackPtr cb = nullptr, void *data = nullptr) const; // throws IOException
 
 	//////////////////////////////////////////////////////////////////////
 	/// Import an image from a specified image buffer.
@@ -179,7 +169,7 @@
 	/// @param channelMap A integer array containing the mapping of input channel ordering to expected channel ordering.
 	/// @param cb A pointer to a callback procedure. The procedure is called after each imported buffer row. If cb returns true, then it stops proceeding.
 	/// @param data Data Pointer to C++ class container to host callback procedure.
-	void ImportBitmap(int pitch, UINT8 *buff, BYTE bpp, int channelMap[] = NULL, CallbackPtr cb = NULL, void *data = NULL) THROW_;
+	void ImportBitmap(int pitch, UINT8 *buff, BYTE bpp, int channelMap[] = nullptr, CallbackPtr cb = nullptr, void *data = nullptr);
 
 	//////////////////////////////////////////////////////////////////////
 	/// Import a YUV image from a specified image buffer.
@@ -196,10 +186,10 @@
 	/// @param channelMap A integer array containing the mapping of input channel ordering to expected channel ordering.
 	/// @param cb A pointer to a callback procedure. The procedure is called after each imported buffer row. If cb returns true, then it stops proceeding.
 	/// @param data Data Pointer to C++ class container to host callback procedure.
-	void ImportYUV(int pitch, DataT *buff, BYTE bpp, int channelMap[] = NULL, CallbackPtr cb = NULL, void *data = NULL) THROW_;
-
-	//////////////////////////////////////////////////////////////////////
-	/// Encode and write a entire PGF image (header and image) at current stream position.
+	void ImportYUV(int pitch, DataT *buff, BYTE bpp, int channelMap[] = nullptr, CallbackPtr cb = nullptr, void *data = nullptr);
+
+	//////////////////////////////////////////////////////////////////////
+	/// Encode and write an entire PGF image (header and image) at current stream position.
 	/// A PGF image is structered in levels, numbered between 0 and Levels() - 1.
 	/// Each level can be seen as a single image, containing the same content
 	/// as all other levels, but in a different size (width, height).
@@ -211,7 +201,7 @@
 	/// @param nWrittenBytes [in-out] The number of bytes written into stream are added to the input value.
 	/// @param cb A pointer to a callback procedure. The procedure is called after writing a single level. If cb returns true, then it stops proceeding.
 	/// @param data Data Pointer to C++ class container to host callback procedure.
-	void Write(CPGFStream* stream, UINT32* nWrittenBytes = NULL, CallbackPtr cb = NULL, void *data = NULL) THROW_;
+	void Write(CPGFStream* stream, UINT32* nWrittenBytes = nullptr, CallbackPtr cb = nullptr, void *data = nullptr);
 
 	//////////////////////////////////////////////////////////////////
 	/// Create wavelet transform channels and encoder. Write header at current stream position.
@@ -220,10 +210,10 @@
 	/// It might throw an IOException.
 	/// @param stream A PGF stream
 	/// @return The number of bytes written into stream.
-	UINT32 WriteHeader(CPGFStream* stream) THROW_;
-
-	//////////////////////////////////////////////////////////////////////
-	/// Encode and write the one and only image at current stream position.
+	UINT32 WriteHeader(CPGFStream* stream);
+
+	//////////////////////////////////////////////////////////////////////
+	/// Encode and write an image at current stream position.
 	/// Call this method after WriteHeader(). In case you want to write uncached metadata, 
 	/// then do that after WriteHeader() and before WriteImage(). 
 	/// This method is called inside of Write(stream, ...).
@@ -232,7 +222,7 @@
 	/// @param cb A pointer to a callback procedure. The procedure is called after writing a single level. If cb returns true, then it stops proceeding.
 	/// @param data Data Pointer to C++ class container to host callback procedure.
 	/// @return The number of bytes written into stream.
-	UINT32 WriteImage(CPGFStream* stream, CallbackPtr cb = NULL, void *data = NULL) THROW_;
+	UINT32 WriteImage(CPGFStream* stream, CallbackPtr cb = nullptr, void *data = nullptr);
 
 #ifdef __PGFROISUPPORT__
 	//////////////////////////////////////////////////////////////////
@@ -250,7 +240,7 @@
 	/// @param cb A pointer to a callback procedure. The procedure is called after writing a single level. If cb returns true, then it stops proceeding.
 	/// @param data Data Pointer to C++ class container to host callback procedure.
 	/// @return The number of bytes written into stream.
-	UINT32 Write(int level, CallbackPtr cb = NULL, void *data = NULL) THROW_;
+	UINT32 Write(int level, CallbackPtr cb = nullptr, void *data = nullptr);
 #endif
 
 	/////////////////////////////////////////////////////////////////////
@@ -262,12 +252,18 @@
 	/////////////////////////////////////////////////////////////////////
 	/// Configures the decoder.
 	/// @param useOMP Use parallel threading with Open MP during decoding. Default value: true. Influences the decoding only if the codec has been compiled with OpenMP support.
-	/// @param skipUserData The file might contain user data (metadata). User data ist usually read during Open and stored in memory. Set this flag to false when storing in memory is not needed.
-	void ConfigureDecoder(bool useOMP = true, bool skipUserData = false) { m_useOMPinDecoder = useOMP; m_skipUserData = skipUserData; }
+	/// @param policy The file might contain user data (e.g. metadata). The policy defines the behaviour during Open(). 
+	///               UP_CacheAll:    User data is read and stored completely in a new allocated memory block. It can be accessed by GetUserData().
+	///               UP_CachePrefix: Only prefixSize bytes at the beginning of the user data are stored in a new allocated memory block. It can be accessed by GetUserData().
+	///               UP_Skip:        User data is skipped and nothing is cached. 
+	/// @param prefixSize Is only used in combination with UP_CachePrefix. It defines the number of bytes cached.
+	void ConfigureDecoder(bool useOMP = true, UserdataPolicy policy = UP_CacheAll, UINT32 prefixSize = 0) { ASSERT(prefixSize <= MaxUserDataSize);  m_useOMPinDecoder = useOMP; m_userDataPolicy = (UP_CachePrefix) ? prefixSize : 0xFFFFFFFF - policy; }
 
 	////////////////////////////////////////////////////////////////////
-	/// Reset stream position to start of PGF pre-header
-	void ResetStreamPos() THROW_;
+	/// Reset stream position to start of PGF pre-header or start of data. Must not be called before Open() or before Write(). 
+	/// Use this method after Read() if you want to read the same image several times, e.g. reading different ROIs.
+	/// @param startOfData true: you want to read the same image several times. false: resets stream position to the initial position
+	void ResetStreamPos(bool startOfData);
 
 	//////////////////////////////////////////////////////////////////////
 	/// Set internal PGF image buffer channel.
@@ -277,13 +273,13 @@
 
 	//////////////////////////////////////////////////////////////////////
 	/// Set PGF header and user data.
-	/// Precondition: The PGF image has been closed with Close(...) or never opened with Open(...).
+	/// Precondition: The PGF image has been never opened with Open(...).
 	/// It might throw an IOException.
 	/// @param header A valid and already filled in PGF header structure
 	/// @param flags A combination of additional version flags. In case you use level-wise encoding then set flag = PGFROI.
 	/// @param userData A user-defined memory block containing any kind of cached metadata.
 	/// @param userDataLength The size of user-defined memory block in bytes
-	void SetHeader(const PGFHeader& header, BYTE flags = 0, UINT8* userData = 0, UINT32 userDataLength = 0) THROW_; // throws IOException
+	void SetHeader(const PGFHeader& header, BYTE flags = 0, const UINT8* userData = 0, UINT32 userDataLength = 0); // throws IOException
 
 	//////////////////////////////////////////////////////////////////////
 	/// Set maximum intensity value for image modes with more than eight bits per channel.
@@ -312,7 +308,7 @@
 	/// @param iFirstColor The color table index of the first entry to set.
 	/// @param nColors The number of color table entries to set.
 	/// @param prgbColors A pointer to the array of RGBQUAD structures to set the color table entries.
-	void SetColorTable(UINT32 iFirstColor, UINT32 nColors, const RGBQUAD* prgbColors) THROW_;
+	void SetColorTable(UINT32 iFirstColor, UINT32 nColors, const RGBQUAD* prgbColors);
 
 	//////////////////////////////////////////////////////////////////////
 	/// Return an internal YUV image channel.
@@ -326,7 +322,7 @@
 	/// @param iFirstColor The color table index of the first entry to retrieve.
 	/// @param nColors The number of color table entries to retrieve.
 	/// @param prgbColors A pointer to the array of RGBQUAD structures to retrieve the color table entries.
-	void GetColorTable(UINT32 iFirstColor, UINT32 nColors, RGBQUAD* prgbColors) const THROW_;
+	void GetColorTable(UINT32 iFirstColor, UINT32 nColors, RGBQUAD* prgbColors) const;
 
 	//////////////////////////////////////////////////////////////////////
 	// Returns address of internal color table
@@ -352,9 +348,10 @@
 	//////////////////////////////////////////////////////////////////////
 	/// Return user data and size of user data.
 	/// Precondition: The PGF image has been opened with a call of Open(...).
-	/// @param size [out] Size of user data in bytes.
-	/// @return A pointer to user data or NULL if there is no user data.
-	const UINT8* GetUserData(UINT32& size) const;
+	/// @param cachedSize [out] Size of returned user data in bytes.
+	/// @param pTotalSize [optional out] Pointer to return the size of user data stored in image header in bytes.
+	/// @return A pointer to user data or nullptr if there is no user data available.
+	const UINT8* GetUserData(UINT32& cachedSize, UINT32* pTotalSize = nullptr) const;
 
 	//////////////////////////////////////////////////////////////////////
 	/// Return the length of all encoded headers in bytes.
@@ -370,13 +367,13 @@
 	UINT32 GetEncodedLevelLength(int level) const					{ ASSERT(level >= 0 && level < m_header.nLevels); return m_levelLength[m_header.nLevels - level - 1]; }
 
 	//////////////////////////////////////////////////////////////////////
-	/// Reads the encoded PGF headers and copies it to a target buffer.
+	/// Reads the encoded PGF header and copies it to a target buffer.
 	/// Precondition: The PGF image has been opened with a call of Open(...).
 	/// It might throw an IOException.
 	/// @param target The target buffer
 	/// @param targetLen The length of the target buffer in bytes
 	/// @return The number of bytes copied to the target buffer
-	UINT32 ReadEncodedHeader(UINT8* target, UINT32 targetLen) const THROW_;
+	UINT32 ReadEncodedHeader(UINT8* target, UINT32 targetLen) const;
 
 	//////////////////////////////////////////////////////////////////////
 	/// Reads the data of an encoded PGF level and copies it to a target buffer 
@@ -387,7 +384,7 @@
 	/// @param target The target buffer
 	/// @param targetLen The length of the target buffer in bytes
 	/// @return The number of bytes copied to the target buffer
-	UINT32 ReadEncodedData(int level, UINT8* target, UINT32 targetLen) const THROW_;
+	UINT32 ReadEncodedData(int level, UINT8* target, UINT32 targetLen) const;
 
 	//////////////////////////////////////////////////////////////////////
 	/// Return current image width of given channel in pixels.
@@ -406,21 +403,21 @@
 	//////////////////////////////////////////////////////////////////////
 	/// Return bits per channel of the image's encoder.
 	/// @return Bits per channel
-	BYTE ChannelDepth() const										{ return CurrentChannelDepth(m_preHeader.version); }
+	BYTE ChannelDepth() const										{ return MaxChannelDepth(m_preHeader.version); }
 
 	//////////////////////////////////////////////////////////////////////
 	/// Return image width of channel 0 at given level in pixels.
 	/// The returned width is independent of any Read-operations and ROI.
 	/// @param level A level
 	/// @return Image level width in pixels
-	UINT32 Width(int level = 0) const								{ ASSERT(level >= 0); return LevelWidth(m_header.width, level); }
+	UINT32 Width(int level = 0) const								{ ASSERT(level >= 0); return LevelSizeL(m_header.width, level); }
 
 	//////////////////////////////////////////////////////////////////////
 	/// Return image height of channel 0 at given level in pixels.
 	/// The returned height is independent of any Read-operations and ROI.
 	/// @param level A level
 	/// @return Image level height in pixels
-	UINT32 Height(int level = 0) const								{ ASSERT(level >= 0); return LevelHeight(m_header.height, level); }
+	UINT32 Height(int level = 0) const								{ ASSERT(level >= 0); return LevelSizeL(m_header.height, level); }
 
 	//////////////////////////////////////////////////////////////////////
 	/// Return current image level. 
@@ -435,6 +432,10 @@
 	BYTE Levels() const												{ return m_header.nLevels; }
 
 	//////////////////////////////////////////////////////////////////////
+	/// Return true if all levels have been read 
+	bool IsFullyRead() const										{ return m_currentLevel == 0; }
+
+	//////////////////////////////////////////////////////////////////////
 	/// Return the PGF quality. The quality is inbetween 0 and MaxQuality.
 	/// PGF quality 0 means lossless quality.
 	/// @return PGF quality
@@ -464,6 +465,13 @@
 	/// @return true if the pgf image supports ROI.
 	bool ROIisSupported() const										{ return (m_preHeader.version & PGFROI) == PGFROI; }
 
+#ifdef __PGFROISUPPORT__
+	/// Return ROI of channel 0 at current level in pixels.
+	/// The returned rect is only valid after reading a ROI.
+	/// @return ROI in pixels
+	PGFRect ComputeLevelROI() const;
+#endif
+
 	//////////////////////////////////////////////////////////////////////
 	/// Returns number of used bits per input/output image channel.
 	/// Precondition: header must be initialized.
@@ -471,9 +479,9 @@
 	BYTE UsedBitsPerChannel() const;
 
 	//////////////////////////////////////////////////////////////////////
-	/// Returns images' PGF version
-	/// @return PGF codec version of the image
-	BYTE Version() const											{ return CurrentVersion(m_preHeader.version); }
+	/// Returns the used codec major version of a pgf image
+	/// @return PGF codec major version of this image
+	BYTE Version() const											{ BYTE ver = CodecMajorVersion(m_preHeader.version); return (ver <= 7) ? ver : (BYTE)m_header.version.major; }
 
 	//class methods
 
@@ -484,28 +492,30 @@
 	static bool ImportIsSupported(BYTE mode);
 
 	//////////////////////////////////////////////////////////////////////
-	/// Compute and return image width at given level.
-	/// @param width Original image width (at level 0)
+	/// Compute and return image width/height of LL subband at given level.
+	/// @param size Original image size (e.g. width or height at level 0)
 	/// @param level An image level
-	/// @return Image level width in pixels
-	static UINT32 LevelWidth(UINT32 width, int level)				{ ASSERT(level >= 0); UINT32 w = (width >> level); return ((w << level) == width) ? w : w + 1; }
-
-	//////////////////////////////////////////////////////////////////////
-	/// Compute and return image height at given level.
-	/// @param height Original image height (at level 0)
+	/// @return Image width/height at given level in pixels
+	static UINT32 LevelSizeL(UINT32 size, int level)				{ ASSERT(level >= 0); UINT32 d = 1 << level; return (size + d - 1) >> level; }
+
+	//////////////////////////////////////////////////////////////////////
+	/// Compute and return image width/height of HH subband at given level.
+	/// @param size Original image size (e.g. width or height at level 0)
 	/// @param level An image level
-	/// @return Image level height in pixels
-	static UINT32 LevelHeight(UINT32 height, int level)				{ ASSERT(level >= 0); UINT32 h = (height >> level); return ((h << level) == height) ? h : h + 1; }
-
-	//////////////////////////////////////////////////////////////////////
-	/// Compute and return codec version.
-	/// @return current PGF codec version
-	static BYTE CurrentVersion(BYTE version = PGFVersion);
-
-	//////////////////////////////////////////////////////////////////////
-	/// Compute and return codec version.
-	/// @return current PGF codec version
-	static BYTE CurrentChannelDepth(BYTE version = PGFVersion)		{ return (version & PGF32) ? 32 : 16; }
+	/// @return high pass size at given level in pixels
+	static UINT32 LevelSizeH(UINT32 size, int level)				{ ASSERT(level >= 0); UINT32 d = 1 << (level - 1); return (size + d - 1) >> level; }
+
+	//////////////////////////////////////////////////////////////////////
+	/// Return codec major version.
+	/// @param version pgf pre-header version number
+	/// @return PGF major of given version
+	static BYTE CodecMajorVersion(BYTE version = PGFVersion);
+
+	//////////////////////////////////////////////////////////////////////
+	/// Return maximum channel depth.
+	/// @param version pgf pre-header version number
+	/// @return maximum channel depth in bit of given version (16 or 32 bit)
+	static BYTE MaxChannelDepth(BYTE version = PGFVersion)			{ return (version & PGF32) ? 32 : 16; }
 
 protected:
 	CWaveletTransform* m_wtChannel[MaxChannels];	///< wavelet transformed color channels
@@ -520,12 +530,12 @@
 	PGFPostHeader m_postHeader;		///< PGF post-header
 	UINT64 m_userDataPos;			///< stream position of user data
 	int m_currentLevel;				///< transform level of current image
+	UINT32 m_userDataPolicy;		///< user data (metadata) policy during open
 	BYTE m_quant;					///< quantization parameter
 	bool m_downsample;				///< chrominance channels are downsampled
 	bool m_favorSpeedOverSize;		///< favor encoding speed over compression ratio
 	bool m_useOMPinEncoder;			///< use Open MP in encoder
 	bool m_useOMPinDecoder;			///< use Open MP in decoder
-	bool m_skipUserData;			///< skip user data (metadata) during open
 #ifdef __PGFROISUPPORT__
 	bool m_streamReinitialized;		///< stream has been reinitialized
 	PGFRect m_roi;					///< region of interest
@@ -537,14 +547,16 @@
 	double m_percent;				///< progress [0..1]
 	ProgressMode m_progressMode;	///< progress mode used in Read and Write; PM_Relative is default mode
 
+	void Init();
 	void ComputeLevels();
-	void CompleteHeader();
-	void RgbToYuv(int pitch, UINT8* rgbBuff, BYTE bpp, int channelMap[], CallbackPtr cb, void *data) THROW_;
+	bool CompleteHeader();
+	void RgbToYuv(int pitch, UINT8* rgbBuff, BYTE bpp, int channelMap[], CallbackPtr cb, void *data);
 	void Downsample(int nChannel);
-	UINT32 UpdatePostHeaderSize() THROW_;
-	void WriteLevel() THROW_;
+	UINT32 UpdatePostHeaderSize();
+	void WriteLevel();
 
 #ifdef __PGFROISUPPORT__
+	PGFRect GetAlignedROI(int c = 0) const;
 	void SetROI(PGFRect rect);
 #endif
 

Modified: trunk/Scribus/scribus/third_party/pgf/PGFplatform.h
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=23713&path=/trunk/Scribus/scribus/third_party/pgf/PGFplatform.h
==============================================================================
--- trunk/Scribus/scribus/third_party/pgf/PGFplatform.h	(original)
+++ trunk/Scribus/scribus/third_party/pgf/PGFplatform.h	Fri May  8 16:40:48 2020
@@ -1,642 +1,638 @@
-/*
- * The Progressive Graphics File; http://www.libpgf.org
- * 
- * $Date: 2007-06-12 19:27:47 +0200 (Di, 12 Jun 2007) $
- * $Revision: 307 $
- * 
- * This file Copyright (C) 2006 xeraina GmbH, Switzerland
- * 
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE
- * as published by the Free Software Foundation; either version 2.1
- * of the License, or (at your option) any later version.
- * 
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- * 
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
- */
-
-//////////////////////////////////////////////////////////////////////
-/// @file PGFplatform.h
-/// @brief PGF platform specific definitions
-/// @author C. Stamm
-
-#ifndef PGF_PGFPLATFORM_H
-#define PGF_PGFPLATFORM_H
-
-#include <cassert>
-#include <cmath>
-#include <cstdlib>
-
-//-------------------------------------------------------------------------------
-// Endianess detection taken from lcms2 header.
-// This list can be endless, so only some checks are performed over here.
-//-------------------------------------------------------------------------------
-#if defined(_HOST_BIG_ENDIAN) || defined(__BIG_ENDIAN__) || defined(WORDS_BIGENDIAN)
-#define PGF_USE_BIG_ENDIAN 1
-#endif
-
-#if defined(__sgi__) || defined(__sgi) || defined(__powerpc__) || defined(__sparc) || defined(__sparc__)
-#define PGF_USE_BIG_ENDIAN 1
-#endif
-
-#if defined(__ppc__) || defined(__s390__) || defined(__s390x__)
-#define PGF_USE_BIG_ENDIAN 1
-#endif
-
-#ifdef TARGET_CPU_PPC
-#define PGF_USE_BIG_ENDIAN 1
-#endif
-
-//-------------------------------------------------------------------------------
-// ROI support
-//-------------------------------------------------------------------------------
-#ifndef NPGFROI
-#define __PGFROISUPPORT__ // without ROI support the program code gets simpler and smaller
-#endif
-
-//-------------------------------------------------------------------------------
-// 32 bit per channel support
-//-------------------------------------------------------------------------------
-#ifndef NPGF32
-#define __PGF32SUPPORT__ // without 32 bit the memory consumption during encoding and decoding is much lesser
-#endif
-
-//-------------------------------------------------------------------------------
-//	32 Bit platform constants
-//-------------------------------------------------------------------------------
-#define WordWidth			32					///< WordBytes*8
-#define WordWidthLog		5					///< ld of WordWidth
-#define WordMask			0xFFFFFFE0			///< least WordWidthLog bits are zero
-#define WordBytes			4					///< sizeof(UINT32)
-#define WordBytesMask		0xFFFFFFFC			///< least WordBytesLog bits are zero
-#define WordBytesLog		2					///< ld of WordBytes
-
-//-------------------------------------------------------------------------------
-// Alignment macros (used in PGF based libraries)
-//-------------------------------------------------------------------------------
-#define DWWIDTHBITS(bits)	(((bits) + WordWidth - 1) & WordMask)		///< aligns scanline width in bits to DWORD value
-#define DWWIDTH(bytes)		(((bytes) + WordBytes - 1) & WordBytesMask)	///< aligns scanline width in bytes to DWORD value
-#define DWWIDTHREST(bytes)	((WordBytes - (bytes)%WordBytes)%WordBytes)	///< DWWIDTH(bytes) - bytes
-
-//-------------------------------------------------------------------------------
-// Min-Max macros
-//-------------------------------------------------------------------------------
-#ifndef __min
-	#define __min(x, y)		((x) <= (y) ? (x) : (y))
-	#define __max(x, y)		((x) >= (y) ? (x) : (y))
-#endif // __min
-
-//-------------------------------------------------------------------------------
-//	Defines -- Adobe image modes.
-//-------------------------------------------------------------------------------
-#define ImageModeBitmap				0
-#define ImageModeGrayScale			1
-#define ImageModeIndexedColor		2
-#define ImageModeRGBColor			3
-#define ImageModeCMYKColor			4
-#define ImageModeHSLColor			5
-#define ImageModeHSBColor			6
-#define ImageModeMultichannel		7
-#define ImageModeDuotone			8
-#define ImageModeLabColor			9
-#define ImageModeGray16				10		// 565
-#define ImageModeRGB48				11
-#define ImageModeLab48				12
-#define ImageModeCMYK64				13
-#define ImageModeDeepMultichannel	14
-#define ImageModeDuotone16			15
-// pgf extension
-#define ImageModeRGBA				17
-#define ImageModeGray32				18		// MSB is 0 (can be interpreted as signed 15.16 fixed point format)
-#define ImageModeRGB12				19
-#define ImageModeRGB16				20
-#define ImageModeUnknown			255
-
-
-//-------------------------------------------------------------------------------
-// WINDOWS 
-//-------------------------------------------------------------------------------
-#if defined(WIN32) || defined(WINCE) || defined(WIN64)
-#define VC_EXTRALEAN		// Exclude rarely-used stuff from Windows headers
-
-//-------------------------------------------------------------------------------
-// MFC
-//-------------------------------------------------------------------------------
-#ifdef _MFC_VER
-
-#include <afxwin.h>         // MFC core and standard components
-#include <afxext.h>         // MFC extensions
-#include <afxdtctl.h>		// MFC support for Internet Explorer 4 Common Controls
-#ifndef _AFX_NO_AFXCMN_SUPPORT
-#include <afxcmn.h>			// MFC support for Windows Common Controls
-#endif // _AFX_NO_AFXCMN_SUPPORT
-#include <afx.h>
-
-#else
-
-#include <windows.h>
-#include <ole2.h>
-
-#endif // _MFC_VER 
-//-------------------------------------------------------------------------------
-
-#define DllExport   __declspec( dllexport ) 
-
-//-------------------------------------------------------------------------------
-// unsigned number type definitions
-//-------------------------------------------------------------------------------
-typedef unsigned char		UINT8;
-typedef unsigned char		BYTE;
-typedef unsigned short		UINT16;
-typedef unsigned short      WORD;
-typedef	unsigned int		UINT32;
-typedef unsigned long       DWORD;
-typedef unsigned long       ULONG;
-typedef unsigned __int64	UINT64; 
-typedef unsigned __int64	ULONGLONG; 
-
-//-------------------------------------------------------------------------------
-// signed number type definitions
-//-------------------------------------------------------------------------------
-typedef signed char			INT8;
-typedef signed short		INT16;
-typedef signed int			INT32;
-typedef signed int			BOOL;
-typedef signed long			LONG;
-typedef signed __int64		INT64;
-typedef signed __int64		LONGLONG;
-
-//-------------------------------------------------------------------------------
-// other types
-//-------------------------------------------------------------------------------
-typedef int OSError;
-typedef bool (__cdecl *CallbackPtr)(double percent, bool escapeAllowed, void *data);
-
-//-------------------------------------------------------------------------------
-// struct type definitions
-//-------------------------------------------------------------------------------
-
-//-------------------------------------------------------------------------------
-// DEBUG macros
-//-------------------------------------------------------------------------------
-#ifndef ASSERT
-	#ifdef _DEBUG
-		#define ASSERT(x)	assert(x)
-	#else
-		#if defined(__GNUC__) 
-			#define ASSERT(ignore)((void) 0) 
-		#elif _MSC_VER >= 1300 
-			#define ASSERT		__noop
-		#else
-			#define ASSERT ((void)0)
-		#endif
-	#endif //_DEBUG
-#endif //ASSERT
-
-//-------------------------------------------------------------------------------
-// Exception handling macros
-//-------------------------------------------------------------------------------
-#ifdef NEXCEPTIONS
-	extern OSError _PGF_Error_;
-	extern OSError GetLastPGFError();
-
-	#define ReturnWithError(err) { _PGF_Error_ = err; return; }
-	#define ReturnWithError2(err, ret) { _PGF_Error_ = err; return ret; }
-#else
-	#define ReturnWithError(err) throw IOException(err)
-	#define ReturnWithError2(err, ret) throw IOException(err)
-#endif //NEXCEPTIONS
-
-#if _MSC_VER >= 1300
-	//#define THROW_ throw(...)
-	#pragma warning( disable : 4290 )
-	#define THROW_ throw(IOException)
-#else
-	#define THROW_
-#endif
-
-//-------------------------------------------------------------------------------
-// constants
-//-------------------------------------------------------------------------------
-#define FSFromStart		FILE_BEGIN				// 0
-#define FSFromCurrent	FILE_CURRENT			// 1
-#define FSFromEnd		FILE_END				// 2
-
-#define INVALID_SET_FILE_POINTER ((DWORD)-1)
-
-//-------------------------------------------------------------------------------
-// IO Error constants
-//-------------------------------------------------------------------------------
-#define NoError				ERROR_SUCCESS		///< no error
-#define AppError			0x20000000			///< all application error messages must be larger than this value
-#define InsufficientMemory	0x20000001			///< memory allocation wasn't successfull
-#define InvalidStreamPos	0x20000002			///< invalid memory stream position
-#define EscapePressed		0x20000003			///< user break by ESC
-#define WrongVersion		0x20000004			///< wrong pgf version 
-#define FormatCannotRead	0x20000005			///< wrong data file format
-#define ImageTooSmall		0x20000006			///< image is too small
-#define ZlibError			0x20000007			///< error in zlib functions
-#define ColorTableError		0x20000008			///< errors related to color table size
-#define PNGError			0x20000009			///< errors in png functions
-#define MissingData			0x2000000A			///< expected data cannot be read
-
-//-------------------------------------------------------------------------------
-// methods
-//-------------------------------------------------------------------------------
-inline OSError FileRead(HANDLE hFile, int *count, void *buffPtr) {
-	if (ReadFile(hFile, buffPtr, *count, (ULONG *)count, NULL)) {
-		return NoError;
-	} else {
-		return GetLastError();
-	}
-}
-
-inline OSError FileWrite(HANDLE hFile, int *count, void *buffPtr) {
-	if (WriteFile(hFile, buffPtr, *count, (ULONG *)count, NULL)) {
-		return NoError;
-	} else {
-		return GetLastError();
-	}
-}
-
-inline OSError GetFPos(HANDLE hFile, UINT64 *pos) {
-#ifdef WINCE
-	LARGE_INTEGER li;
-	li.QuadPart = 0;
-
-	li.LowPart = SetFilePointer (hFile, li.LowPart, &li.HighPart, FILE_CURRENT);
-	if (li.LowPart == INVALID_SET_FILE_POINTER) {
-		OSError err = GetLastError();
-		if (err != NoError) {
-			return err;
-		}
-	}
-	*pos = li.QuadPart;
-	return NoError;
-#else
-	LARGE_INTEGER li;
-	li.QuadPart = 0;
-	if (SetFilePointerEx(hFile, li, (PLARGE_INTEGER)pos, FILE_CURRENT)) {
-		return NoError;
-	} else {
-		return GetLastError();
-	}
-#endif
-}
-
-inline OSError SetFPos(HANDLE hFile, int posMode, INT64 posOff) {
-#ifdef WINCE
-	LARGE_INTEGER li;
-	li.QuadPart = posOff;
-
-	if (SetFilePointer (hFile, li.LowPart, &li.HighPart, posMode) == INVALID_SET_FILE_POINTER) {
-		OSError err = GetLastError();
-		if (err != NoError) {
-			return err;
-		}
-	}
-	return NoError;
-#else
-	LARGE_INTEGER li;
-	li.QuadPart = posOff;
-	if (SetFilePointerEx(hFile, li, NULL, posMode)) {
-		return NoError;
-	} else {
-		return GetLastError();
-	}
-#endif
-}
-#endif //WIN32
-
-
-//-------------------------------------------------------------------------------
-// Apple OSX
-//-------------------------------------------------------------------------------
-#ifdef __APPLE__
-#define __POSIX__ 
-#endif // __APPLE__
-
-
-//-------------------------------------------------------------------------------
-// LINUX
-//-------------------------------------------------------------------------------
-#if defined(__linux__) || defined(__GLIBC__)
-#define __POSIX__
-#endif // __linux__ or __GLIBC__
-
-
-//-------------------------------------------------------------------------------
-// SOLARIS
-//-------------------------------------------------------------------------------
-#ifdef __sun
-#define __POSIX__
-#endif // __sun
-
-
-//-------------------------------------------------------------------------------
-// *BSD and Haiku
-//-------------------------------------------------------------------------------
-#if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__HAIKU__)
-#ifndef __POSIX__ 
-#define __POSIX__ 
-#endif 
-
-#ifndef off64_t 
-#define off64_t off_t 
-#endif 
-
-#ifndef lseek64 
-#define lseek64 lseek 
-#endif 
-
-#endif // __NetBSD__ or __OpenBSD__ or __FreeBSD__ or __HAIKU__
-
-
-//-------------------------------------------------------------------------------
-// POSIX *NIXes
-//-------------------------------------------------------------------------------
-
-#ifdef __POSIX__
-#include <unistd.h>
-#include <errno.h>
-#include <stdint.h>		// for int64_t and uint64_t
-#include <string.h>		// memcpy()
-
-//-------------------------------------------------------------------------------
-// unsigned number type definitions
-//-------------------------------------------------------------------------------
-
-typedef unsigned char		UINT8;
-typedef unsigned char		BYTE;
-typedef unsigned short		UINT16;
-typedef unsigned short		WORD;
-typedef unsigned int		UINT32;
-typedef unsigned int		DWORD;
-typedef unsigned long		ULONG;
-typedef unsigned long long  __Uint64;
-typedef __Uint64			UINT64;
-typedef __Uint64			ULONGLONG;
-
-//-------------------------------------------------------------------------------
-// signed number type definitions
-//-------------------------------------------------------------------------------
-typedef signed char			INT8;
-typedef signed short		INT16;
-typedef signed int			INT32;
-typedef signed int			BOOL;
-typedef signed long			LONG;
-typedef int64_t				INT64;
-typedef int64_t				LONGLONG;
-
-//-------------------------------------------------------------------------------
-// other types
-//-------------------------------------------------------------------------------
-typedef int					OSError;
-typedef int					HANDLE;	
-typedef unsigned long		ULONG_PTR;
-typedef void*				PVOID;
-typedef char*				LPTSTR;
-typedef bool (*CallbackPtr)(double percent, bool escapeAllowed, void *data);
-
-//-------------------------------------------------------------------------------
-// struct type definitions
-//-------------------------------------------------------------------------------
-typedef struct tagRGBTRIPLE {
-	BYTE rgbtBlue;
-	BYTE rgbtGreen;
-	BYTE rgbtRed;
-} RGBTRIPLE;
-
-typedef struct tagRGBQUAD {
-	BYTE rgbBlue;
-	BYTE rgbGreen;
-	BYTE rgbRed;
-	BYTE rgbReserved;
-} RGBQUAD;
-
-typedef union _LARGE_INTEGER {
-  struct {
-    DWORD LowPart;
-    LONG HighPart;
-  } u;
-  LONGLONG QuadPart;
-} LARGE_INTEGER, *PLARGE_INTEGER;
-#endif // __POSIX__
-
-
-#if defined(__POSIX__) || defined(WINCE)
-// CMYK macros
-#define GetKValue(cmyk)      ((BYTE)(cmyk))
-#define GetYValue(cmyk)      ((BYTE)((cmyk)>> 8))
-#define GetMValue(cmyk)      ((BYTE)((cmyk)>>16))
-#define GetCValue(cmyk)      ((BYTE)((cmyk)>>24))
-#define CMYK(c,m,y,k)		 ((COLORREF)((((BYTE)(k)|((WORD)((BYTE)(y))<<8))|(((DWORD)(BYTE)(m))<<16))|(((DWORD)(BYTE)(c))<<24)))
-
-//-------------------------------------------------------------------------------
-// methods
-//-------------------------------------------------------------------------------
-/* The MulDiv function multiplies two 32-bit values and then divides the 64-bit 
- * result by a third 32-bit value. The return value is rounded up or down to 
- * the nearest integer.
- * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winprog/winprog/muldiv.asp
- * */
-__inline int MulDiv(int nNumber, int nNumerator, int nDenominator) {
-	INT64 multRes = nNumber*nNumerator;
-	INT32 divRes = INT32(multRes/nDenominator);
-	return divRes;
-}
-#endif // __POSIX__ or WINCE
-
-
-#ifdef __POSIX__
-//-------------------------------------------------------------------------------
-// DEBUG macros
-//-------------------------------------------------------------------------------
-#ifndef ASSERT
-	#ifdef _DEBUG
-		#define ASSERT(x)	assert(x)
-	#else
-		#define ASSERT(x)	
-	#endif //_DEBUG
-#endif //ASSERT
-
-//-------------------------------------------------------------------------------
-// Exception handling macros
-//-------------------------------------------------------------------------------
-#ifdef NEXCEPTIONS
-	extern OSError _PGF_Error_;
-	extern OSError GetLastPGFError();
-
-	#define ReturnWithError(err) { _PGF_Error_ = err; return; }
-	#define ReturnWithError2(err, ret) { _PGF_Error_ = err; return ret; }
-#else
-	#define ReturnWithError(err) throw IOException(err)
-	#define ReturnWithError2(err, ret) throw IOException(err)
-#endif //NEXCEPTIONS
-
-// Dynamic exceptions specifications are deprecated in C++11
-#if __cplusplus < 201103L
-#define THROW_ throw(IOException)
-#else
-#define THROW_
-#endif
-#define CONST const
-
-//-------------------------------------------------------------------------------
-// constants
-//-------------------------------------------------------------------------------
-#define FSFromStart			SEEK_SET
-#define FSFromCurrent		SEEK_CUR
-#define FSFromEnd			SEEK_END
-
-//-------------------------------------------------------------------------------
-// IO Error constants
-//-------------------------------------------------------------------------------
-#define NoError					0x0000			///< no error
-#define AppError				0x2000			///< all application error messages must be larger than this value
-#define InsufficientMemory		0x2001			///< memory allocation wasn't successfull
-#define InvalidStreamPos		0x2002			///< invalid memory stream position
-#define EscapePressed			0x2003			///< user break by ESC
-#define WrongVersion			0x2004			///< wrong pgf version 
-#define FormatCannotRead		0x2005			///< wrong data file format
-#define ImageTooSmall			0x2006			///< image is too small
-#define ZlibError				0x2007			///< error in zlib functions
-#define ColorTableError			0x2008			///< errors related to color table size
-#define PNGError				0x2009			///< errors in png functions
-#define MissingData				0x200A			///< expected data cannot be read
-
-//-------------------------------------------------------------------------------
-// methods
-//-------------------------------------------------------------------------------
-__inline OSError FileRead(HANDLE hFile, int *count, void *buffPtr) {
-	*count = (int)read(hFile, buffPtr, *count);
-	if (*count != -1) {
-		return NoError;
-	} else {
-		return errno;
-	}
-}
-
-__inline OSError FileWrite(HANDLE hFile, int *count, void *buffPtr) {
-	*count = (int)write(hFile, buffPtr, (size_t)*count);
-	if (*count != -1) {
-		return NoError;
-	} else {
-		return errno;
-	}
-}
-
-__inline OSError GetFPos(HANDLE hFile, UINT64 *pos) {
-	#ifdef __APPLE__
-		off_t ret;
-		if ((ret = lseek(hFile, 0, SEEK_CUR)) == -1) {
-			return errno;
-		} else {
-			*pos = (UINT64)ret;
-			return NoError;
-		}
-	#else
-		off64_t ret;
-		if ((ret = lseek64(hFile, 0, SEEK_CUR)) == -1) {
-			return errno;
-		} else {
-			*pos = (UINT64)ret;
-			return NoError;
-		}
-	#endif
-}
-
-__inline OSError SetFPos(HANDLE hFile, int posMode, INT64 posOff) {
-	#ifdef __APPLE__
-		if ((lseek(hFile, (off_t)posOff, posMode)) == -1) {
-			return errno;
-		} else {
-			return NoError;
-		}
-	#else
-		if ((lseek64(hFile, (off64_t)posOff, posMode)) == -1) {
-			return errno;
-		} else {
-			return NoError;
-		}
-	#endif
-}
-
-#endif /* __POSIX__ */
-//-------------------------------------------------------------------------------
-
-
-//-------------------------------------------------------------------------------
-//	Big Endian
-//-------------------------------------------------------------------------------
-#ifdef PGF_USE_BIG_ENDIAN 
-
-#ifndef _lrotl
-	#define _lrotl(x,n)	(((x) << ((UINT32)(n))) | ((x) >> (32 - (UINT32)(n))))
-#endif
-
-__inline UINT16 ByteSwap(UINT16 wX) {
-	return ((wX & 0xFF00) >> 8) | ((wX & 0x00FF) << 8);
-}
-
-__inline UINT32 ByteSwap(UINT32 dwX) { 
-#ifdef _X86_     
-	_asm mov eax, dwX     
-	_asm bswap eax
-	_asm mov dwX, eax      
-	return dwX; 
-#else     
-	return _lrotl(((dwX & 0xFF00FF00) >> 8) | ((dwX & 0x00FF00FF) << 8), 16); 
-#endif 
-}
-
-#if defined(WIN32) || defined(WIN64)
-__inline UINT64 ByteSwap(UINT64 ui64) { 
-	return _byteswap_uint64(ui64);
-}
-#endif
-
-#define __VAL(x) ByteSwap(x)
-
-#else //PGF_USE_BIG_ENDIAN
-
-	#define __VAL(x) (x)
-
-#endif //PGF_USE_BIG_ENDIAN
- 
-// OpenMP rules (inspired from libraw project)
-// NOTE: Use LIBPGF_DISABLE_OPENMP to disable OpenMP support in whole libpgf
-#define LIBPGF_DISABLE_OPENMP
-#undef LIBPGF_USE_OPENMP
-
-#ifndef LIBPGF_DISABLE_OPENMP
-# if defined (_OPENMP)
-#  if defined (WIN32) || defined(WIN64)
-#   if defined (_MSC_VER) && (_MSC_VER >= 1500)
-//   VS2008 SP1 and VS2010+ : OpenMP works OK
-#    define LIBPGF_USE_OPENMP
-#   elif defined (__INTEL_COMPILER) && (__INTEL_COMPILER >=910)
-//   untested on 9.x and 10.x, Intel documentation claims OpenMP 2.5 support in 9.1
-#    define LIBPGF_USE_OPENMP
-#   else
-#    undef LIBPGF_USE_OPENMP
-#   endif
-//  Not Win32
-#  elif (defined(__APPLE__) || defined(__MACOSX__)) && defined(_REENTRANT)
-#   undef LIBPGF_USE_OPENMP
-#  else
-#   define LIBPGF_USE_OPENMP
-#  endif
-# endif // defined (_OPENMP)
-#endif // ifndef LIBPGF_DISABLE_OPENMP
-#ifdef LIBPGF_USE_OPENMP
-#include <omp.h>
-#endif
-
-#endif //PGF_PGFPLATFORM_H
+/*
+ * The Progressive Graphics File; http://www.libpgf.org
+ * 
+ * $Date: 2007-06-12 19:27:47 +0200 (Di, 12 Jun 2007) $
+ * $Revision: 307 $
+ * 
+ * This file Copyright (C) 2006 xeraina GmbH, Switzerland
+ * 
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE
+ * as published by the Free Software Foundation; either version 2.1
+ * of the License, or (at your option) any later version.
+ * 
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ * 
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+
+//////////////////////////////////////////////////////////////////////
+/// @file PGFplatform.h
+/// @brief PGF platform specific definitions
+/// @author C. Stamm
+
+#ifndef PGF_PGFPLATFORM_H
+#define PGF_PGFPLATFORM_H
+
+#include <cassert>
+#include <cmath>
+#include <cstdlib>
+
+//-------------------------------------------------------------------------------
+// Endianess detection taken from lcms2 header.
+// This list can be endless, so only some checks are performed over here.
+//-------------------------------------------------------------------------------
+#if defined(_HOST_BIG_ENDIAN) || defined(__BIG_ENDIAN__) || defined(WORDS_BIGENDIAN)
+#define PGF_USE_BIG_ENDIAN 1
+#endif
+
+#if defined(__sgi__) || defined(__sgi) || defined(__powerpc__) || defined(__sparc) || defined(__sparc__)
+#define PGF_USE_BIG_ENDIAN 1
+#endif
+
+#if defined(__ppc__) || defined(__s390__) || defined(__s390x__)
+#define PGF_USE_BIG_ENDIAN 1
+#endif
+
+#ifdef TARGET_CPU_PPC
+#define PGF_USE_BIG_ENDIAN 1
+#endif
+
+//-------------------------------------------------------------------------------
+// ROI support
+//-------------------------------------------------------------------------------
+#ifndef NPGFROI
+#define __PGFROISUPPORT__ // without ROI support the program code gets simpler and smaller
+#endif
+
+//-------------------------------------------------------------------------------
+// 32 bit per channel support
+//-------------------------------------------------------------------------------
+#ifndef NPGF32
+#define __PGF32SUPPORT__ // without 32 bit the memory consumption during encoding and decoding is much lesser
+#endif
+
+//-------------------------------------------------------------------------------
+//	32 Bit platform constants
+//-------------------------------------------------------------------------------
+#define WordWidth			32					///< WordBytes*8
+#define WordWidthLog		5					///< ld of WordWidth
+#define WordMask			0xFFFFFFE0			///< least WordWidthLog bits are zero
+#define WordBytes			4					///< sizeof(UINT32)
+#define WordBytesMask		0xFFFFFFFC			///< least WordBytesLog bits are zero
+#define WordBytesLog		2					///< ld of WordBytes
+
+//-------------------------------------------------------------------------------
+// Alignment macros (used in PGF based libraries)
+//-------------------------------------------------------------------------------
+#define DWWIDTHBITS(bits)	(((bits) + WordWidth - 1) & WordMask)		///< aligns scanline width in bits to DWORD value
+#define DWWIDTH(bytes)		(((bytes) + WordBytes - 1) & WordBytesMask)	///< aligns scanline width in bytes to DWORD value
+#define DWWIDTHREST(bytes)	((WordBytes - (bytes)%WordBytes)%WordBytes)	///< DWWIDTH(bytes) - bytes
+
+//-------------------------------------------------------------------------------
+// Min-Max macros
+//-------------------------------------------------------------------------------
+#ifndef __min
+	#define __min(x, y)		((x) <= (y) ? (x) : (y))
+	#define __max(x, y)		((x) >= (y) ? (x) : (y))
+#endif // __min
+
+//-------------------------------------------------------------------------------
+//	Defines -- Adobe image modes.
+//-------------------------------------------------------------------------------
+#define ImageModeBitmap				0
+#define ImageModeGrayScale			1
+#define ImageModeIndexedColor		2
+#define ImageModeRGBColor			3
+#define ImageModeCMYKColor			4
+#define ImageModeHSLColor			5
+#define ImageModeHSBColor			6
+#define ImageModeMultichannel		7
+#define ImageModeDuotone			8
+#define ImageModeLabColor			9
+#define ImageModeGray16				10		// 565
+#define ImageModeRGB48				11
+#define ImageModeLab48				12
+#define ImageModeCMYK64				13
+#define ImageModeDeepMultichannel	14
+#define ImageModeDuotone16			15
+// pgf extension
+#define ImageModeRGBA				17
+#define ImageModeGray32				18		// MSB is 0 (can be interpreted as signed 15.16 fixed point format)
+#define ImageModeRGB12				19
+#define ImageModeRGB16				20
+#define ImageModeUnknown			255
+
+
+//-------------------------------------------------------------------------------
+// WINDOWS 
+//-------------------------------------------------------------------------------
+#if defined(WIN32) || defined(WINCE) || defined(WIN64)
+#define VC_EXTRALEAN		// Exclude rarely-used stuff from Windows headers
+
+//-------------------------------------------------------------------------------
+// MFC
+//-------------------------------------------------------------------------------
+#ifdef _MFC_VER
+#ifndef _WIN32_WINNT            // Specifies that the minimum required platform is Windows Vista.
+#define _WIN32_WINNT 0x0600     // Change this to the appropriate value to target other versions of Windows.
+#endif
+#include <afx.h>
+#include <afxwin.h>         // MFC core and standard components
+#include <afxext.h>         // MFC extensions
+#include <afxdtctl.h>		// MFC support for Internet Explorer 4 Common Controls
+#ifndef _AFX_NO_AFXCMN_SUPPORT
+#include <afxcmn.h>			// MFC support for Windows Common Controls
+#endif // _AFX_NO_AFXCMN_SUPPORT
+
+#else
+
+#include <windows.h>
+#include <ole2.h>
+
+#endif // _MFC_VER 
+//-------------------------------------------------------------------------------
+
+#define DllExport   __declspec( dllexport ) 
+
+//-------------------------------------------------------------------------------
+// unsigned number type definitions
+//-------------------------------------------------------------------------------
+typedef unsigned char		UINT8;
+typedef unsigned char		BYTE;
+typedef unsigned short		UINT16;
+typedef unsigned short      WORD;
+typedef	unsigned int		UINT32;
+typedef unsigned long       DWORD;
+typedef unsigned long       ULONG;
+typedef unsigned __int64	UINT64; 
+typedef unsigned __int64	ULONGLONG; 
+
+//-------------------------------------------------------------------------------
+// signed number type definitions
+//-------------------------------------------------------------------------------
+typedef signed char			INT8;
+typedef signed short		INT16;
+typedef signed int			INT32;
+typedef signed int			BOOL;
+typedef signed long			LONG;
+typedef signed __int64		INT64;
+typedef signed __int64		LONGLONG;
+
+//-------------------------------------------------------------------------------
+// other types
+//-------------------------------------------------------------------------------
+typedef int OSError;
+typedef bool (__cdecl *CallbackPtr)(double percent, bool escapeAllowed, void *data);
+
+//-------------------------------------------------------------------------------
+// struct type definitions
+//-------------------------------------------------------------------------------
+
+//-------------------------------------------------------------------------------
+// DEBUG macros
+//-------------------------------------------------------------------------------
+#ifndef ASSERT
+	#ifdef _DEBUG
+		#define ASSERT(x)	assert(x)
+	#else
+		#if defined(__GNUC__) 
+			#define ASSERT(ignore)((void) 0) 
+		#elif _MSC_VER >= 1300 
+			#define ASSERT		__noop
+		#else
+			#define ASSERT ((void)0)
+		#endif
+	#endif //_DEBUG
+#endif //ASSERT
+
+//-------------------------------------------------------------------------------
+// Exception handling macros
+//-------------------------------------------------------------------------------
+#ifdef NEXCEPTIONS
+	extern OSError _PGF_Error_;
+	extern OSError GetLastPGFError();
+
+	#define ReturnWithError(err) { _PGF_Error_ = err; return; }
+	#define ReturnWithError2(err, ret) { _PGF_Error_ = err; return ret; }
+#else
+	#define ReturnWithError(err) throw IOException(err)
+	#define ReturnWithError2(err, ret) throw IOException(err)
+#endif //NEXCEPTIONS
+
+//-------------------------------------------------------------------------------
+// constants
+//-------------------------------------------------------------------------------
+#define FSFromStart		FILE_BEGIN				// 0
+#define FSFromCurrent	FILE_CURRENT			// 1
+#define FSFromEnd		FILE_END				// 2
+
+#define INVALID_SET_FILE_POINTER ((DWORD)-1)
+
+//-------------------------------------------------------------------------------
+// IO Error constants
+//-------------------------------------------------------------------------------
+#define NoError				ERROR_SUCCESS		///< no error
+#define AppError			0x20000000			///< all application error messages must be larger than this value
+#define InsufficientMemory	0x20000001			///< memory allocation was not successfull
+#define InvalidStreamPos	0x20000002			///< invalid memory stream position
+#define EscapePressed		0x20000003			///< user break by ESC
+#define WrongVersion		0x20000004			///< wrong PGF version 
+#define FormatCannotRead	0x20000005			///< wrong data file format
+#define ImageTooSmall		0x20000006			///< image is too small
+#define ZlibError			0x20000007			///< error in zlib functions
+#define ColorTableError		0x20000008			///< errors related to color table size
+#define PNGError			0x20000009			///< errors in png functions
+#define MissingData			0x2000000A			///< expected data cannot be read
+
+//-------------------------------------------------------------------------------
+// methods
+//-------------------------------------------------------------------------------
+inline OSError FileRead(HANDLE hFile, int *count, void *buffPtr) {
+	if (ReadFile(hFile, buffPtr, *count, (ULONG *)count, nullptr)) {
+		return NoError;
+	} else {
+		return GetLastError();
+	}
+}
+
+inline OSError FileWrite(HANDLE hFile, int *count, void *buffPtr) {
+	if (WriteFile(hFile, buffPtr, *count, (ULONG *)count, nullptr)) {
+		return NoError;
+	} else {
+		return GetLastError();
+	}
+}
+
+inline OSError GetFPos(HANDLE hFile, UINT64 *pos) {
+#ifdef WINCE
+	LARGE_INTEGER li;
+	li.QuadPart = 0;
+
+	li.LowPart = SetFilePointer (hFile, li.LowPart, &li.HighPart, FILE_CURRENT);
+	if (li.LowPart == INVALID_SET_FILE_POINTER) {
+		OSError err = GetLastError();
+		if (err != NoError) {
+			return err;
+		}
+	}
+	*pos = li.QuadPart;
+	return NoError;
+#else
+	LARGE_INTEGER li;
+	li.QuadPart = 0;
+	if (SetFilePointerEx(hFile, li, (PLARGE_INTEGER)pos, FILE_CURRENT)) {
+		return NoError;
+	} else {
+		return GetLastError();
+	}
+#endif
+}
+
+inline OSError SetFPos(HANDLE hFile, int posMode, INT64 posOff) {
+#ifdef WINCE
+	LARGE_INTEGER li;
+	li.QuadPart = posOff;
+
+	if (SetFilePointer (hFile, li.LowPart, &li.HighPart, posMode) == INVALID_SET_FILE_POINTER) {
+		OSError err = GetLastError();
+		if (err != NoError) {
+			return err;
+		}
+	}
+	return NoError;
+#else
+	LARGE_INTEGER li;
+	li.QuadPart = posOff;
+	if (SetFilePointerEx(hFile, li, nullptr, posMode)) {
+		return NoError;
+	} else {
+		return GetLastError();
+	}
+#endif
+}
+#endif //WIN32
+
+
+//-------------------------------------------------------------------------------
+// Apple OSX
+//-------------------------------------------------------------------------------
+#ifdef __APPLE__
+#define __POSIX__ 
+#endif // __APPLE__
+
+
+//-------------------------------------------------------------------------------
+// LINUX
+//-------------------------------------------------------------------------------
+#if defined(__linux__) || defined(__GLIBC__)
+#define __POSIX__
+#endif // __linux__ or __GLIBC__
+
+
+//-------------------------------------------------------------------------------
+// SOLARIS
+//-------------------------------------------------------------------------------
+#ifdef __sun
+#define __POSIX__
+#endif // __sun
+
+
+//-------------------------------------------------------------------------------
+// *BSD and Haiku
+//-------------------------------------------------------------------------------
+#if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__HAIKU__)
+#ifndef __POSIX__ 
+#define __POSIX__ 
+#endif 
+
+#ifndef off64_t 
+#define off64_t off_t 
+#endif 
+
+#ifndef lseek64 
+#define lseek64 lseek 
+#endif 
+
+#endif // __NetBSD__ or __OpenBSD__ or __FreeBSD__ or __HAIKU__
+
+
+//-------------------------------------------------------------------------------
+// POSIX *NIXes
+//-------------------------------------------------------------------------------
+
+#ifdef __POSIX__
+#include <unistd.h>
+#include <errno.h>
+#include <stdint.h>		// for int64_t and uint64_t
+#include <string.h>		// memcpy()
+
+#undef major
+
+//-------------------------------------------------------------------------------
+// unsigned number type definitions
+//-------------------------------------------------------------------------------
+
+typedef unsigned char		UINT8;
+typedef unsigned char		BYTE;
+typedef unsigned short		UINT16;
+typedef unsigned short		WORD;
+typedef unsigned int		UINT32;
+typedef unsigned int		DWORD;
+typedef unsigned long		ULONG;
+typedef unsigned long long  __Uint64;
+typedef __Uint64			UINT64;
+typedef __Uint64			ULONGLONG;
+
+//-------------------------------------------------------------------------------
+// signed number type definitions
+//-------------------------------------------------------------------------------
+typedef signed char			INT8;
+typedef signed short		INT16;
+typedef signed int			INT32;
+typedef signed int			BOOL;
+typedef signed long			LONG;
+typedef int64_t				INT64;
+typedef int64_t				LONGLONG;
+
+//-------------------------------------------------------------------------------
+// other types
+//-------------------------------------------------------------------------------
+typedef int					OSError;
+typedef int					HANDLE;	
+typedef unsigned long		ULONG_PTR;
+typedef void*				PVOID;
+typedef char*				LPTSTR;
+typedef bool (*CallbackPtr)(double percent, bool escapeAllowed, void *data);
+
+//-------------------------------------------------------------------------------
+// struct type definitions
+//-------------------------------------------------------------------------------
+typedef struct tagRGBTRIPLE {
+	BYTE rgbtBlue;
+	BYTE rgbtGreen;
+	BYTE rgbtRed;
+} RGBTRIPLE;
+
+typedef struct tagRGBQUAD {
+	BYTE rgbBlue;
+	BYTE rgbGreen;
+	BYTE rgbRed;
+	BYTE rgbReserved;
+} RGBQUAD;
+
+typedef union _LARGE_INTEGER {
+  struct {
+    DWORD LowPart;
+    LONG HighPart;
+  } u;
+  LONGLONG QuadPart;
+} LARGE_INTEGER, *PLARGE_INTEGER;
+#endif // __POSIX__
+
+
+#if defined(__POSIX__) || defined(WINCE)
+// CMYK macros
+#define GetKValue(cmyk)      ((BYTE)(cmyk))
+#define GetYValue(cmyk)      ((BYTE)((cmyk)>> 8))
+#define GetMValue(cmyk)      ((BYTE)((cmyk)>>16))
+#define GetCValue(cmyk)      ((BYTE)((cmyk)>>24))
+#define CMYK(c,m,y,k)		 ((COLORREF)((((BYTE)(k)|((WORD)((BYTE)(y))<<8))|(((DWORD)(BYTE)(m))<<16))|(((DWORD)(BYTE)(c))<<24)))
+
+//-------------------------------------------------------------------------------
+// methods
+//-------------------------------------------------------------------------------
+/* The MulDiv function multiplies two 32-bit values and then divides the 64-bit 
+ * result by a third 32-bit value. The return value is rounded up or down to 
+ * the nearest integer.
+ * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winprog/winprog/muldiv.asp
+ * */
+__inline int MulDiv(int nNumber, int nNumerator, int nDenominator) {
+	INT64 multRes = nNumber*nNumerator;
+	INT32 divRes = INT32(multRes/nDenominator);
+	return divRes;
+}
+#endif // __POSIX__ or WINCE
+
+
+#ifdef __POSIX__
+//-------------------------------------------------------------------------------
+// DEBUG macros
+//-------------------------------------------------------------------------------
+#ifndef ASSERT
+	#ifdef _DEBUG
+		#define ASSERT(x)	assert(x)
+	#else
+		#define ASSERT(x)	
+	#endif //_DEBUG
+#endif //ASSERT
+
+//-------------------------------------------------------------------------------
+// Exception handling macros
+//-------------------------------------------------------------------------------
+#ifdef NEXCEPTIONS
+	extern OSError _PGF_Error_;
+	extern OSError GetLastPGFError();
+
+	#define ReturnWithError(err) { _PGF_Error_ = err; return; }
+	#define ReturnWithError2(err, ret) { _PGF_Error_ = err; return ret; }
+#else
+	#define ReturnWithError(err) throw IOException(err)
+	#define ReturnWithError2(err, ret) throw IOException(err)
+#endif //NEXCEPTIONS
+
+// Dynamic exceptions specifications are deprecated in C++11
+#if __cplusplus < 201103L
+#define THROW_ throw(IOException)
+#else
+#define THROW_
+#endif
+#define CONST const
+
+//-------------------------------------------------------------------------------
+// constants
+//-------------------------------------------------------------------------------
+#define FSFromStart			SEEK_SET
+#define FSFromCurrent		SEEK_CUR
+#define FSFromEnd			SEEK_END
+
+//-------------------------------------------------------------------------------
+// IO Error constants
+//-------------------------------------------------------------------------------
+#define NoError					0x0000			///< no error
+#define AppError				0x2000			///< all application error messages must be larger than this value
+#define InsufficientMemory		0x2001			///< memory allocation wasn't successfull
+#define InvalidStreamPos		0x2002			///< invalid memory stream position
+#define EscapePressed			0x2003			///< user break by ESC
+#define WrongVersion			0x2004			///< wrong pgf version 
+#define FormatCannotRead		0x2005			///< wrong data file format
+#define ImageTooSmall			0x2006			///< image is too small
+#define ZlibError				0x2007			///< error in zlib functions
+#define ColorTableError			0x2008			///< errors related to color table size
+#define PNGError				0x2009			///< errors in png functions
+#define MissingData				0x200A			///< expected data cannot be read
+
+//-------------------------------------------------------------------------------
+// methods
+//-------------------------------------------------------------------------------
+__inline OSError FileRead(HANDLE hFile, int *count, void *buffPtr) {
+	*count = (int)read(hFile, buffPtr, *count);
+	if (*count != -1) {
+		return NoError;
+	} else {
+		return errno;
+	}
+}
+
+__inline OSError FileWrite(HANDLE hFile, int *count, void *buffPtr) {
+	*count = (int)write(hFile, buffPtr, (size_t)*count);
+	if (*count != -1) {
+		return NoError;
+	} else {
+		return errno;
+	}
+}
+
+__inline OSError GetFPos(HANDLE hFile, UINT64 *pos) {
+	#ifdef __APPLE__
+		off_t ret;
+		if ((ret = lseek(hFile, 0, SEEK_CUR)) == -1) {
+			return errno;
+		} else {
+			*pos = (UINT64)ret;
+			return NoError;
+		}
+	#else
+		off64_t ret;
+		if ((ret = lseek64(hFile, 0, SEEK_CUR)) == -1) {
+			return errno;
+		} else {
+			*pos = (UINT64)ret;
+			return NoError;
+		}
+	#endif
+}
+
+__inline OSError SetFPos(HANDLE hFile, int posMode, INT64 posOff) {
+	#ifdef __APPLE__
+		if ((lseek(hFile, (off_t)posOff, posMode)) == -1) {
+			return errno;
+		} else {
+			return NoError;
+		}
+	#else
+		if ((lseek64(hFile, (off64_t)posOff, posMode)) == -1) {
+			return errno;
+		} else {
+			return NoError;
+		}
+	#endif
+}
+
+#endif /* __POSIX__ */
+//-------------------------------------------------------------------------------
+
+
+//-------------------------------------------------------------------------------
+//	Big Endian
+//-------------------------------------------------------------------------------
+#ifdef PGF_USE_BIG_ENDIAN 
+
+#ifndef _lrotl
+	#define _lrotl(x,n)	(((x) << ((UINT32)(n))) | ((x) >> (32 - (UINT32)(n))))
+#endif
+
+__inline UINT16 ByteSwap(UINT16 wX) {
+	return ((wX & 0xFF00) >> 8) | ((wX & 0x00FF) << 8);
+}
+
+__inline UINT32 ByteSwap(UINT32 dwX) { 
+#ifdef _X86_     
+	_asm mov eax, dwX     
+	_asm bswap eax
+	_asm mov dwX, eax      
+	return dwX; 
+#else     
+	return _lrotl(((dwX & 0xFF00FF00) >> 8) | ((dwX & 0x00FF00FF) << 8), 16); 
+#endif 
+}
+
+#if defined(WIN32) || defined(WIN64)
+__inline UINT64 ByteSwap(UINT64 ui64) { 
+	return _byteswap_uint64(ui64);
+}
+#endif
+
+#define __VAL(x) ByteSwap(x)
+
+#else //PGF_USE_BIG_ENDIAN
+
+	#define __VAL(x) (x)
+
+#endif //PGF_USE_BIG_ENDIAN
+ 
+// OpenMP rules (inspired from libraw project)
+// NOTE: Use LIBPGF_DISABLE_OPENMP to disable OpenMP support in whole libpgf
+#define LIBPGF_DISABLE_OPENMP
+#undef LIBPGF_USE_OPENMP
+
+#ifndef LIBPGF_DISABLE_OPENMP
+# if defined (_OPENMP)
+#  if defined (WIN32) || defined(WIN64)
+#   if defined (_MSC_VER) && (_MSC_VER >= 1500)
+//   VS2008 SP1 and VS2010+ : OpenMP works OK
+#    define LIBPGF_USE_OPENMP
+#   elif defined (__INTEL_COMPILER) && (__INTEL_COMPILER >=910)
+//   untested on 9.x and 10.x, Intel documentation claims OpenMP 2.5 support in 9.1
+#    define LIBPGF_USE_OPENMP
+#   else
+#    undef LIBPGF_USE_OPENMP
+#   endif
+//  Not Win32
+#  elif (defined(__APPLE__) || defined(__MACOSX__)) && defined(_REENTRANT)
+#   undef LIBPGF_USE_OPENMP
+#  else
+#   define LIBPGF_USE_OPENMP
+#  endif
+# endif // defined (_OPENMP)
+#endif // ifndef LIBPGF_DISABLE_OPENMP
+#ifdef LIBPGF_USE_OPENMP
+#include <omp.h>
+#endif
+
+#endif //PGF_PGFPLATFORM_H

Modified: trunk/Scribus/scribus/third_party/pgf/PGFstream.cpp
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=23713&path=/trunk/Scribus/scribus/third_party/pgf/PGFstream.cpp
==============================================================================
--- trunk/Scribus/scribus/third_party/pgf/PGFstream.cpp	(original)
+++ trunk/Scribus/scribus/third_party/pgf/PGFstream.cpp	Fri May  8 16:40:48 2020
@@ -35,7 +35,7 @@
 //////////////////////////////////////////////////////////////////////
 // CPGFFileStream
 //////////////////////////////////////////////////////////////////////
-void CPGFFileStream::Write(int *count, void *buffPtr) THROW_ {
+void CPGFFileStream::Write(int *count, void *buffPtr) {
 	ASSERT(count);
 	ASSERT(buffPtr);
 	ASSERT(IsValid());
@@ -45,7 +45,7 @@
 }
 
 //////////////////////////////////////////////////////////////////////
-void CPGFFileStream::Read(int *count, void *buffPtr) THROW_ {
+void CPGFFileStream::Read(int *count, void *buffPtr) {
 	ASSERT(count);
 	ASSERT(buffPtr);
 	ASSERT(IsValid());
@@ -54,14 +54,14 @@
 }
 
 //////////////////////////////////////////////////////////////////////
-void CPGFFileStream::SetPos(short posMode, INT64 posOff) THROW_ {
+void CPGFFileStream::SetPos(short posMode, INT64 posOff) {
 	ASSERT(IsValid());
 	OSError err;
 	if ((err = SetFPos(m_hFile, posMode, posOff)) != NoError) ReturnWithError(err);
 }
 
 //////////////////////////////////////////////////////////////////////
-UINT64 CPGFFileStream::GetPos() const THROW_ {
+UINT64 CPGFFileStream::GetPos() const {
 	ASSERT(IsValid());
 	OSError err;
 	UINT64 pos = 0;
@@ -75,7 +75,7 @@
 //////////////////////////////////////////////////////////////////////
 /// Allocate memory block of given size
 /// @param size Memory size
-CPGFMemoryStream::CPGFMemoryStream(size_t size) THROW_ 
+CPGFMemoryStream::CPGFMemoryStream(size_t size) 
 : m_size(size)
 , m_allocated(true) {
 	m_buffer = m_pos = m_eos = new(std::nothrow) UINT8[m_size];
@@ -86,7 +86,7 @@
 /// Use already allocated memory of given size
 /// @param pBuffer Memory location
 /// @param size Memory size
-CPGFMemoryStream::CPGFMemoryStream(UINT8 *pBuffer, size_t size) THROW_ 
+CPGFMemoryStream::CPGFMemoryStream(UINT8 *pBuffer, size_t size) 
 : m_buffer(pBuffer)
 , m_pos(pBuffer)
 , m_eos(pBuffer + size)
@@ -99,7 +99,7 @@
 /// Use already allocated memory of given size
 /// @param pBuffer Memory location
 /// @param size Memory size
-void CPGFMemoryStream::Reinitialize(UINT8 *pBuffer, size_t size) THROW_ {
+void CPGFMemoryStream::Reinitialize(UINT8 *pBuffer, size_t size) {
 	if (!m_allocated) {
 		m_buffer = m_pos = pBuffer;
 		m_size = size;
@@ -108,7 +108,7 @@
 }
 
 //////////////////////////////////////////////////////////////////////
-void CPGFMemoryStream::Write(int *count, void *buffPtr) THROW_ {
+void CPGFMemoryStream::Write(int *count, void *buffPtr) {
 	ASSERT(count);
 	ASSERT(buffPtr);
 	ASSERT(IsValid());
@@ -165,7 +165,7 @@
 }
 
 //////////////////////////////////////////////////////////////////////
-void CPGFMemoryStream::SetPos(short posMode, INT64 posOff) THROW_ {
+void CPGFMemoryStream::SetPos(short posMode, INT64 posOff) {
 	ASSERT(IsValid());
 	switch(posMode) {
 	case FSFromStart:
@@ -189,7 +189,7 @@
 // CPGFMemFileStream
 #ifdef _MFC_VER
 //////////////////////////////////////////////////////////////////////
-void CPGFMemFileStream::Write(int *count, void *buffPtr) THROW_ {
+void CPGFMemFileStream::Write(int *count, void *buffPtr) {
 	ASSERT(count);
 	ASSERT(buffPtr);
 	ASSERT(IsValid());
@@ -197,7 +197,7 @@
 }
 
 //////////////////////////////////////////////////////////////////////
-void CPGFMemFileStream::Read(int *count, void *buffPtr) THROW_ {
+void CPGFMemFileStream::Read(int *count, void *buffPtr) {
 	ASSERT(count);
 	ASSERT(buffPtr);
 	ASSERT(IsValid());
@@ -205,13 +205,13 @@
 }
 
 //////////////////////////////////////////////////////////////////////
-void CPGFMemFileStream::SetPos(short posMode, INT64 posOff) THROW_ {
+void CPGFMemFileStream::SetPos(short posMode, INT64 posOff) {
 	ASSERT(IsValid());
 	m_memFile->Seek(posOff, posMode); 
 }
 
 //////////////////////////////////////////////////////////////////////
-UINT64 CPGFMemFileStream::GetPos() const THROW_ {
+UINT64 CPGFMemFileStream::GetPos() const {
 	return (UINT64)m_memFile->GetPosition();
 }
 #endif // _MFC_VER
@@ -220,7 +220,7 @@
 // CPGFIStream
 #if defined(WIN32) || defined(WINCE)
 //////////////////////////////////////////////////////////////////////
-void CPGFIStream::Write(int *count, void *buffPtr) THROW_ {
+void CPGFIStream::Write(int *count, void *buffPtr) {
 	ASSERT(count);
 	ASSERT(buffPtr);
 	ASSERT(IsValid());
@@ -232,7 +232,7 @@
 }
 
 //////////////////////////////////////////////////////////////////////
-void CPGFIStream::Read(int *count, void *buffPtr) THROW_ {
+void CPGFIStream::Read(int *count, void *buffPtr) {
 	ASSERT(count);
 	ASSERT(buffPtr);
 	ASSERT(IsValid());
@@ -244,20 +244,20 @@
 }
 
 //////////////////////////////////////////////////////////////////////
-void CPGFIStream::SetPos(short posMode, INT64 posOff) THROW_ {
+void CPGFIStream::SetPos(short posMode, INT64 posOff) {
 	ASSERT(IsValid());
 	
 	LARGE_INTEGER li;
 	li.QuadPart = posOff;
 
-	HRESULT hr = m_stream->Seek(li, posMode, NULL); 
+	HRESULT hr = m_stream->Seek(li, posMode, nullptr); 
 	if (FAILED(hr)) {
 		ReturnWithError(hr);
 	}
 }
 
 //////////////////////////////////////////////////////////////////////
-UINT64 CPGFIStream::GetPos() const THROW_ {
+UINT64 CPGFIStream::GetPos() const {
 	ASSERT(IsValid());
 	
 	LARGE_INTEGER n;

Modified: trunk/Scribus/scribus/third_party/pgf/PGFstream.h
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=23713&path=/trunk/Scribus/scribus/third_party/pgf/PGFstream.h
==============================================================================
--- trunk/Scribus/scribus/third_party/pgf/PGFstream.h	(original)
+++ trunk/Scribus/scribus/third_party/pgf/PGFstream.h	Fri May  8 16:40:48 2020
@@ -92,10 +92,10 @@
 	HANDLE GetHandle() { return m_hFile; }
 
 	virtual ~CPGFFileStream() { m_hFile = 0; }
-	virtual void Write(int *count, void *buffer) THROW_; // throws IOException 
-	virtual void Read(int *count, void *buffer) THROW_; // throws IOException 
-	virtual void SetPos(short posMode, INT64 posOff) THROW_; // throws IOException
-	virtual UINT64 GetPos() const THROW_; // throws IOException
+	virtual void Write(int *count, void *buffer); // throws IOException 
+	virtual void Read(int *count, void *buffer); // throws IOException 
+	virtual void SetPos(short posMode, INT64 posOff); // throws IOException
+	virtual UINT64 GetPos() const; // throws IOException
 	virtual bool   IsValid() const	{ return m_hFile != 0; }
 };
 
@@ -113,17 +113,17 @@
 public:
 	/// Constructor
 	/// @param size Size of new allocated memory buffer
-	CPGFMemoryStream(size_t size) THROW_;
+	CPGFMemoryStream(size_t size);
 	
 	/// Constructor. Use already allocated memory of given size
 	/// @param pBuffer Memory location
 	/// @param size Memory size
-	CPGFMemoryStream(UINT8 *pBuffer, size_t size) THROW_;
+	CPGFMemoryStream(UINT8 *pBuffer, size_t size);
 	
 	/// Use already allocated memory of given size
 	/// @param pBuffer Memory location
 	/// @param size Memory size
-	void Reinitialize(UINT8 *pBuffer, size_t size) THROW_;
+	void Reinitialize(UINT8 *pBuffer, size_t size);
 	
 	virtual ~CPGFMemoryStream() { 
 		m_pos = 0; 
@@ -133,9 +133,9 @@
 		}
 	}
 
-	virtual void Write(int *count, void *buffer) THROW_; // throws IOException 
+	virtual void Write(int *count, void *buffer); // throws IOException 
 	virtual void Read(int *count, void *buffer);
-	virtual void SetPos(short posMode, INT64 posOff) THROW_; // throws IOException
+	virtual void SetPos(short posMode, INT64 posOff); // throws IOException
 	virtual UINT64 GetPos() const { ASSERT(IsValid()); return m_pos - m_buffer; }
 	virtual bool   IsValid() const	{ return m_buffer != 0; }
 
@@ -161,12 +161,12 @@
 	CMemFile *m_memFile;	///< MFC memory file
 public:
 	CPGFMemFileStream(CMemFile *memFile) : m_memFile(memFile) {}
-	virtual bool	IsValid() const	{ return m_memFile != NULL; }
+	virtual bool	IsValid() const	{ return m_memFile != nullptr; }
 	virtual ~CPGFMemFileStream() {}
-	virtual void Write(int *count, void *buffer) THROW_; // throws IOException 
-	virtual void Read(int *count, void *buffer) THROW_; // throws IOException 
-	virtual void SetPos(short posMode, INT64 posOff) THROW_; // throws IOException
-	virtual UINT64 GetPos() const THROW_; // throws IOException
+	virtual void Write(int *count, void *buffer); // throws IOException 
+	virtual void Read(int *count, void *buffer); // throws IOException 
+	virtual void SetPos(short posMode, INT64 posOff); // throws IOException
+	virtual UINT64 GetPos() const; // throws IOException
 };
 #endif
 
@@ -179,14 +179,14 @@
 protected:
 	IStream *m_stream;	///< COM+ IStream
 public:
-	CPGFIStream(IStream *stream) : m_stream(stream) {}
+	CPGFIStream(IStream *stream) : m_stream(stream) { m_stream->AddRef(); }
 	virtual bool IsValid() const	{ return m_stream != 0; }
-	virtual ~CPGFIStream() {}
-	virtual void Write(int *count, void *buffer) THROW_; // throws IOException 
-	virtual void Read(int *count, void *buffer) THROW_; // throws IOException 
-	virtual void SetPos(short posMode, INT64 posOff) THROW_; // throws IOException
-	virtual UINT64 GetPos() const THROW_; // throws IOException
-	IStream* GetIStream() const		{ return m_stream; }
+	virtual ~CPGFIStream() { m_stream->Release(); }
+	virtual void Write(int *count, void *buffer); // throws IOException 
+	virtual void Read(int *count, void *buffer); // throws IOException 
+	virtual void SetPos(short posMode, INT64 posOff); // throws IOException
+	virtual UINT64 GetPos() const; // throws IOException
+	IStream* GetIStream() const { return m_stream; }
 };
 #endif
 

Modified: trunk/Scribus/scribus/third_party/pgf/PGFtypes.h
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=23713&path=/trunk/Scribus/scribus/third_party/pgf/PGFtypes.h
==============================================================================
--- trunk/Scribus/scribus/third_party/pgf/PGFtypes.h	(original)
+++ trunk/Scribus/scribus/third_party/pgf/PGFtypes.h	Fri May  8 16:40:48 2020
@@ -30,11 +30,6 @@
 #define PGF_PGFTYPES_H
 
 #include "PGFplatform.h"
-
-//-------------------------------------------------------------------------------
-//	Constraints
-//-------------------------------------------------------------------------------
-// BufferSize <= UINT16_MAX
 
 //-------------------------------------------------------------------------------
 //	Codec versions
@@ -43,11 +38,22 @@
 // Version 4:	DataT: INT32 instead of INT16, allows 31 bit per pixel and channel (backward compatibility assured)
 // Version 5:	ROI, new block-reordering scheme (backward compatibility assured)
 // Version 6:	modified data structure PGFPreHeader: hSize (header size) is now a UINT32 instead of a UINT16 (backward compatibility assured)
+// Version 7:	last two bytes in header are now used for extended version numbers; new data representation for bitmaps (backward compatibility assured)
 //
 //-------------------------------------------------------------------------------
-#define PGFCodecVersion		"6.14.12"			///< Major number
-												///< Minor number: Year (2) Week (2)
-#define PGFCodecVersionID   0x061412			///< Codec version ID to use for API check in client implementation
+#define PGFMajorNumber		7
+#define PGFYear				19
+#define	PGFWeek				3
+
+#define PPCAT_NX(A, B) A ## B
+#define PPCAT(A, B) PPCAT_NX(A, B)
+#define STRINGIZE_NX(A) #A
+#define STRINGIZE(A) STRINGIZE_NX(A)
+
+//#define PGFCodecVersionID		0x071822
+#define PGFCodecVersionID PPCAT(PPCAT(PPCAT(0x0, PGFMajorNumber), PGFYear), PGFWeek)
+//#define PGFCodecVersion		"7.19.3"			///< Major number, Minor number: Year (2) Week (2)
+#define PGFCodecVersion STRINGIZE(PPCAT(PPCAT(PPCAT(PPCAT(PGFMajorNumber, .), PGFYear), .), PGFWeek))
 
 //-------------------------------------------------------------------------------
 //	Image constants
@@ -63,18 +69,19 @@
 #define PGF32				4					///< 32 bit values are used -> allows at maximum 31 bits, otherwise 16 bit values are used -> allows at maximum 15 bits
 #define PGFROI				8					///< supports Regions Of Interest
 #define Version5			16					///< new coding scheme since major version 5
-#define Version6			32					///< new HeaderSize: 32 bits instead of 16 bits 
+#define Version6			32					///< hSize in PGFPreHeader uses 32 bits instead of 16 bits 
+#define Version7			64					///< Codec major and minor version number stored in PGFHeader
 // version numbers
 #ifdef __PGF32SUPPORT__
-#define PGFVersion			(Version2 | PGF32 | Version5 | Version6)	///< current standard version
-#else
-#define PGFVersion			(Version2 |         Version5 | Version6)	///< current standard version
+#define PGFVersion			(Version2 | PGF32 | Version5 | Version6 | Version7)	///< current standard version
+#else
+#define PGFVersion			(Version2 |         Version5 | Version6 | Version7)	///< current standard version
 #endif
 
 //-------------------------------------------------------------------------------
 //	Coder constants
 //-------------------------------------------------------------------------------
-#define BufferSize			16384				///< must be a multiple of WordWidth
+#define BufferSize			16384				///< must be a multiple of WordWidth, BufferSize <= UINT16_MAX
 #define RLblockSizeLen		15					///< block size length (< 16): ld(BufferSize) < RLblockSizeLen <= 2*ld(BufferSize)
 #define LinBlockSize		8					///< side length of a coefficient block in a HH or LL subband
 #define InterBlockSize		4					///< side length of a coefficient block in a HL or LH subband
@@ -89,10 +96,12 @@
 //-------------------------------------------------------------------------------
 // Types
 //-------------------------------------------------------------------------------
-enum Orientation { LL=0, HL=1, LH=2, HH=3 };
+enum Orientation		{ LL = 0, HL = 1, LH = 2, HH = 3 };
+enum ProgressMode		{ PM_Relative, PM_Absolute };
+enum UserdataPolicy		{ UP_Skip = 0, UP_CachePrefix = 1, UP_CacheAll = 2 };
 
 /// general PGF file structure
-/// PGFPreHeaderV6 PGFHeader PGFPostHeader LevelLengths Level_n-1 Level_n-2 ... Level_0
+/// PGFPreHeader PGFHeader [PGFPostHeader] LevelLengths Level_n-1 Level_n-2 ... Level_0
 /// PGFPostHeader ::= [ColorTable] [UserData]
 /// LevelLengths  ::= UINT32[nLevels]
 
@@ -112,8 +121,26 @@
 /// @author C. Stamm
 /// @brief PGF pre-header
 struct PGFPreHeader : PGFMagicVersion {
-	UINT32 hSize;				///< total size of PGFHeader, [ColorTable], and [UserData] in bytes
+	UINT32 hSize;				///< total size of PGFHeader, [ColorTable], and [UserData] in bytes (since Version 6: 4 Bytes)
 	// total: 8 Bytes
+};
+
+/////////////////////////////////////////////////////////////////////
+/// Version number since major version 7
+/// @author C. Stamm
+/// @brief version number stored in header since major version 7 
+struct PGFVersionNumber {
+	PGFVersionNumber(UINT8 _major, UINT8 _year, UINT8 _week) : major(_major), year(_year), week(_week) {}
+
+#ifdef PGF_USE_BIG_ENDIAN
+	UINT16 week  : 6;	///< week number in a year
+	UINT16 year  : 6;	///< year since 2000 (year 2001 = 1)
+	UINT16 major : 4;	///< major version number
+#else
+	UINT16 major : 4;	///< major version number
+	UINT16 year  : 6;	///< year since 2000 (year 2001 = 1)
+	UINT16 week  : 6;	///< week number in a year
+#endif // PGF_USE_BIG_ENDIAN
 };
 
 /////////////////////////////////////////////////////////////////////
@@ -121,16 +148,16 @@
 /// @author C. Stamm
 /// @brief PGF header
 struct PGFHeader {
-	PGFHeader() : width(0), height(0), nLevels(0), quality(0), bpp(0), channels(0), mode(ImageModeUnknown), usedBitsPerChannel(0), reserved1(0), reserved2(0) {}
+	PGFHeader() : width(0), height(0), nLevels(0), quality(0), bpp(0), channels(0), mode(ImageModeUnknown), usedBitsPerChannel(0), version(0, 0, 0) {}
 	UINT32 width;				///< image width in pixels
 	UINT32 height;				///< image height in pixels
-	UINT8 nLevels;				///< number of DWT levels
+	UINT8 nLevels;				///< number of FWT transforms
 	UINT8 quality;				///< quantization parameter: 0=lossless, 4=standard, 6=poor quality
 	UINT8 bpp;					///< bits per pixel
 	UINT8 channels;				///< number of channels
 	UINT8 mode;					///< image mode according to Adobe's image modes
 	UINT8 usedBitsPerChannel;	///< number of used bits per channel in 16- and 32-bit per channel modes
-	UINT8 reserved1, reserved2;	///< not used
+	PGFVersionNumber version;	///< codec version number: (since Version 7)
 	// total: 16 Bytes
 };
 
@@ -139,9 +166,10 @@
 /// @author C. Stamm
 /// @brief Optional PGF post-header
 struct PGFPostHeader {
-	RGBQUAD clut[ColorTableLen];///< color table for indexed color images
-	UINT8 *userData;			///< user data of size userDataLen
-	UINT32 userDataLen;			///< user data size in bytes
+	RGBQUAD clut[ColorTableLen];///< color table for indexed color images (optional part of file header)
+	UINT8 *userData;			///< user data of size userDataLen (optional part of file header)
+	UINT32 userDataLen;			///< user data size in bytes (not part of file header)
+	UINT32 cachedUserDataLen;	///< cached user data size in bytes (not part of file header)
 };
 
 /////////////////////////////////////////////////////////////////////
@@ -149,14 +177,6 @@
 /// @author C. Stamm
 /// @brief Block header used with ROI coding scheme 
 union ROIBlockHeader {
-	/// Constructor
-	/// @param v Buffer size
-	ROIBlockHeader(UINT16 v) { val = v; }
-	/// Constructor
-	/// @param size Buffer size
-	/// @param end 0/1 Flag; 1: last part of a tile
-	ROIBlockHeader(UINT32 size, bool end)	{ ASSERT(size < (1 << RLblockSizeLen)); rbh.bufferSize = size; rbh.tileEnd = end; }
-	
 	UINT16 val; ///< unstructured union value
 	/// @brief Named ROI block header (part of the union)
 	struct RBH {
@@ -169,6 +189,15 @@
 #endif // PGF_USE_BIG_ENDIAN
 	} rbh;	///< ROI block header
 	// total: 2 Bytes
+
+	/// Constructor
+	/// @param v Buffer size
+	ROIBlockHeader(UINT16 v) { val = v; }
+
+	/// Constructor
+	/// @param size Buffer size
+	/// @param end 0/1 Flag; 1: last part of a tile
+	ROIBlockHeader(UINT32 size, bool end) { ASSERT(size < (1 << RLblockSizeLen)); rbh.bufferSize = size; rbh.tileEnd = end; }
 };
 
 #pragma pack()
@@ -178,13 +207,14 @@
 /// @author C. Stamm
 /// @brief PGF exception
 struct IOException {
+	OSError error;				///< operating system error code
+	
 	/// Standard constructor
 	IOException() : error(NoError) {}
+	
 	/// Constructor
 	/// @param err Run-time error
 	IOException(OSError err) : error(err) {}
-
-	OSError error;				///< operating system error code
 };
 
 /////////////////////////////////////////////////////////////////////
@@ -192,8 +222,11 @@
 /// @author C. Stamm
 /// @brief Rectangle
 struct PGFRect {
+	UINT32 left, top, right, bottom;
+
 	/// Standard constructor
 	PGFRect() : left(0), top(0), right(0), bottom(0) {}
+	
 	/// Constructor
 	/// @param x Left offset
 	/// @param y Top offset
@@ -201,18 +234,34 @@
 	/// @param height Rectangle height
 	PGFRect(UINT32 x, UINT32 y, UINT32 width, UINT32 height) : left(x), top(y), right(x + width), bottom(y + height) {}
 
+#ifdef WIN32
+	PGFRect(const RECT& rect) : left(rect.left), top(rect.top), right(rect.right), bottom(rect.bottom) {
+		ASSERT(rect.left >= 0 && rect.right >= 0 && rect.left <= rect.right);
+		ASSERT(rect.top >= 0 && rect.bottom >= 0 && rect.top <= rect.bottom);
+	}
+	
+	PGFRect& operator=(const RECT& rect) {
+		left = rect.left; top = rect.top; right = rect.right; bottom = rect.bottom;
+		return *this;
+	}
+	
+	operator RECT() {
+		RECT rect = { (LONG)left, (LONG)top, (LONG)right, (LONG)bottom };
+		return rect;
+	}
+#endif
+
 	/// @return Rectangle width
 	UINT32 Width() const					{ return right - left; }
+	
 	/// @return Rectangle height
 	UINT32 Height() const					{ return bottom - top; }
 	
-	/// Test if point (x,y) is inside this rectangle
+	/// Test if point (x,y) is inside this rectangle (inclusive top-left edges, exclusive bottom-right edges)
 	/// @param x Point coordinate x
 	/// @param y Point coordinate y
-	/// @return True if point (x,y) is inside this rectangle
+	/// @return True if point (x,y) is inside this rectangle (inclusive top-left edges, exclusive bottom-right edges)
 	bool IsInside(UINT32 x, UINT32 y) const { return (x >= left && x < right && y >= top && y < bottom); }
-
-	UINT32 left, top, right, bottom;
 };
 
 #ifdef __PGF32SUPPORT__
@@ -229,7 +278,8 @@
 #define MagicVersionSize	sizeof(PGFMagicVersion)
 #define PreHeaderSize		sizeof(PGFPreHeader)
 #define HeaderSize			sizeof(PGFHeader)
-#define ColorTableSize		ColorTableLen*sizeof(RGBQUAD)
+#define ColorTableSize		(ColorTableLen*sizeof(RGBQUAD))
 #define DataTSize			sizeof(DataT)
+#define MaxUserDataSize		0x7FFFFFFF
 
 #endif //PGF_PGFTYPES_H

Modified: trunk/Scribus/scribus/third_party/pgf/Subband.cpp
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=23713&path=/trunk/Scribus/scribus/third_party/pgf/Subband.cpp
==============================================================================
--- trunk/Scribus/scribus/third_party/pgf/Subband.cpp	(original)
+++ trunk/Scribus/scribus/third_party/pgf/Subband.cpp	Fri May  8 16:40:48 2020
@@ -38,8 +38,8 @@
 , m_size(0)
 , m_level(0)
 , m_orientation(LL)
+, m_data(0)
 , m_dataPos(0)
-, m_data(0)
 #ifdef __PGFROISUPPORT__
 , m_nTiles(0)
 #endif
@@ -174,7 +174,7 @@
 /// @param tile True if just a rectangular region is extracted, false if the entire subband is extracted.
 /// @param tileX Tile index in x-direction
 /// @param tileY Tile index in y-direction
-void CSubband::ExtractTile(CEncoder& encoder, bool tile /*= false*/, UINT32 tileX /*= 0*/, UINT32 tileY /*= 0*/) THROW_ {
+void CSubband::ExtractTile(CEncoder& encoder, bool tile /*= false*/, UINT32 tileX /*= 0*/, UINT32 tileY /*= 0*/) {
 #ifdef __PGFROISUPPORT__
 	if (tile) {
 		// compute tile position and size
@@ -186,6 +186,7 @@
 	} else 
 #endif
 	{
+		tileX; tileY; tile; // prevents from unreferenced formal parameter warning
 		// write values into buffer using partitiong scheme
 		encoder.Partition(this, m_width, m_height, 0, m_width);
 	}
@@ -199,7 +200,7 @@
 /// @param tile True if just a rectangular region is placed, false if the entire subband is placed.
 /// @param tileX Tile index in x-direction
 /// @param tileY Tile index in y-direction
-void CSubband::PlaceTile(CDecoder& decoder, int quantParam, bool tile /*= false*/, UINT32 tileX /*= 0*/, UINT32 tileY /*= 0*/) THROW_ {
+void CSubband::PlaceTile(CDecoder& decoder, int quantParam, bool tile /*= false*/, UINT32 tileX /*= 0*/, UINT32 tileY /*= 0*/) {
 	// allocate memory
 	if (!AllocMemory()) ReturnWithError(InsufficientMemory);
 
@@ -225,6 +226,7 @@
 	} else 
 #endif
 	{
+		tileX; tileY; tile; // prevents from unreferenced formal parameter warning
 		// read values into buffer using partitiong scheme
 		decoder.Partition(this, quantParam, m_width, m_height, 0, m_width);
 	}
@@ -233,6 +235,17 @@
 
 
 #ifdef __PGFROISUPPORT__
+//////////////////////////////////////////////////////////////////////
+/// Set ROI
+void CSubband::SetAlignedROI(const PGFRect& roi) {
+	ASSERT(roi.left <= m_width); 
+	ASSERT(roi.top <= m_height); 
+	
+	m_ROI = roi; 
+	if (m_ROI.right > m_width) m_ROI.right = m_width; 
+	if (m_ROI.bottom > m_height) m_ROI.bottom = m_height;
+}
+
 //////////////////////////////////////////////////////////////////////
 /// Compute tile position and size.
 /// @param tileX Tile index in x-direction
@@ -242,6 +255,7 @@
 /// @param w [out] Tile width
 /// @param h [out] Tile height
 void CSubband::TilePosition(UINT32 tileX, UINT32 tileY, UINT32& xPos, UINT32& yPos, UINT32& w, UINT32& h) const {
+	ASSERT(tileX < m_nTiles); ASSERT(tileY < m_nTiles);
 	// example
 	// band = HH, w = 30, ldTiles = 2 -> 4 tiles in a row/column
 	// --> tile widths
@@ -254,7 +268,6 @@
 	// C D E F
 
 	UINT32 nTiles = m_nTiles;
-	ASSERT(tileX < nTiles); ASSERT(tileY < nTiles);
 	UINT32 m;
 	UINT32 left = 0, right = nTiles;
 	UINT32 top = 0, bottom = nTiles;
@@ -291,4 +304,85 @@
 	ASSERT(yPos < m_height && (yPos + h <= m_height));
 }
 
-#endif
+//////////////////////////////////////////////////////////////////////
+/// Compute tile index and extrem position (x,y) of given position (xPos, yPos).
+void CSubband::TileIndex(bool topLeft, UINT32 xPos, UINT32 yPos, UINT32& tileX, UINT32& tileY, UINT32& x, UINT32& y) const {
+	UINT32 m;
+	UINT32 left = 0, right = m_width;
+	UINT32 top = 0, bottom = m_height;
+	UINT32 nTiles = m_nTiles;
+
+	if (xPos > m_width) xPos = m_width;
+	if (yPos > m_height) yPos = m_height;
+
+	if (topLeft) {
+		// compute tileX with binary search
+		tileX = 0;
+		while (nTiles > 1) {
+			nTiles >>= 1;
+			m = left + ((right - left + 1) >> 1);
+			if (xPos < m) {
+				// exclusive m
+				right = m;
+			} else {
+				tileX += nTiles;
+				left = m;
+			}
+		}
+		x = left;
+		ASSERT(tileX >= 0 && tileX < m_nTiles);
+
+		// compute tileY with binary search
+		nTiles = m_nTiles;
+		tileY = 0;
+		while (nTiles > 1) {
+			nTiles >>= 1;
+			m = top + ((bottom - top + 1) >> 1);
+			if (yPos < m) {
+				// exclusive m
+				bottom = m;
+			} else {
+				tileY += nTiles;
+				top = m;
+			}
+		}
+		y = top;
+		ASSERT(tileY >= 0 && tileY < m_nTiles);
+
+	} else {
+		// compute tileX with binary search
+		tileX = 1;
+		while (nTiles > 1) {
+			nTiles >>= 1;
+			m = left + ((right - left + 1) >> 1);
+			if (xPos <= m) {
+				// inclusive m
+				right = m;
+			} else {
+				tileX += nTiles;
+				left = m;
+			}
+		}
+		x = right;
+		ASSERT(tileX > 0 && tileX <= m_nTiles);
+
+		// compute tileY with binary search
+		nTiles = m_nTiles;
+		tileY = 1;
+		while (nTiles > 1) {
+			nTiles >>= 1;
+			m = top + ((bottom - top + 1) >> 1);
+			if (yPos <= m) {
+				// inclusive m
+				bottom = m;
+			} else {
+				tileY += nTiles;
+				top = m;
+			}
+		}
+		y = bottom;
+		ASSERT(tileY > 0 && tileY <= m_nTiles);
+	}
+}
+
+#endif

Modified: trunk/Scribus/scribus/third_party/pgf/Subband.h
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=23713&path=/trunk/Scribus/scribus/third_party/pgf/Subband.h
==============================================================================
--- trunk/Scribus/scribus/third_party/pgf/Subband.h	(original)
+++ trunk/Scribus/scribus/third_party/pgf/Subband.h	Fri May  8 16:40:48 2020
@@ -41,6 +41,7 @@
 /// @brief Wavelet channel class
 class CSubband {
 	friend class CWaveletTransform;
+	friend class CRoiIndices;
 
 public:
 	//////////////////////////////////////////////////////////////////////
@@ -68,7 +69,7 @@
 	/// @param tile True if just a rectangular region is extracted, false if the entire subband is extracted.
 	/// @param tileX Tile index in x-direction
 	/// @param tileY Tile index in y-direction
-	void ExtractTile(CEncoder& encoder, bool tile = false, UINT32 tileX = 0, UINT32 tileY = 0) THROW_;
+	void ExtractTile(CEncoder& encoder, bool tile = false, UINT32 tileX = 0, UINT32 tileY = 0);
 
 	/////////////////////////////////////////////////////////////////////
 	/// Decoding and dequantization of this subband.
@@ -78,7 +79,7 @@
 	/// @param tile True if just a rectangular region is placed, false if the entire subband is placed.
 	/// @param tileX Tile index in x-direction
 	/// @param tileY Tile index in y-direction
-	void PlaceTile(CDecoder& decoder, int quantParam, bool tile = false, UINT32 tileX = 0, UINT32 tileY = 0) THROW_;
+	void PlaceTile(CDecoder& decoder, int quantParam, bool tile = false, UINT32 tileX = 0, UINT32 tileY = 0);
 
 	//////////////////////////////////////////////////////////////////////
 	/// Perform subband quantization with given quantization parameter.
@@ -152,9 +153,10 @@
 #ifdef __PGFROISUPPORT__
 	UINT32 BufferWidth() const			{ return m_ROI.Width(); }
 	void TilePosition(UINT32 tileX, UINT32 tileY, UINT32& left, UINT32& top, UINT32& w, UINT32& h) const;
-	const PGFRect& GetROI() const		{ return m_ROI; }
+	void TileIndex(bool topLeft, UINT32 xPos, UINT32 yPos, UINT32& tileX, UINT32& tileY, UINT32& x, UINT32& y) const;
+	const PGFRect& GetAlignedROI() const { return m_ROI; }
 	void SetNTiles(UINT32 nTiles)		{ m_nTiles = nTiles; }
-	void SetROI(const PGFRect& roi)		{ ASSERT(roi.right <= m_width); ASSERT(roi.bottom <= m_height); m_ROI = roi; }
+	void SetAlignedROI(const PGFRect& roi);
 	void InitBuffPos(UINT32 left = 0, UINT32 top = 0)	{ m_dataPos = top*BufferWidth() + left; ASSERT(m_dataPos < m_size); }
 #else
 	void InitBuffPos()					{ m_dataPos = 0; }
@@ -170,7 +172,7 @@
 	DataT* m_data;					///< buffer
 
 #ifdef __PGFROISUPPORT__
-	PGFRect m_ROI;					///< region of interest
+	PGFRect m_ROI;					///< region of interest (block aligned)
 	UINT32	m_nTiles;				///< number of tiles in one dimension in this subband
 #endif
 };

Modified: trunk/Scribus/scribus/third_party/pgf/WaveletTransform.cpp
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=23713&path=/trunk/Scribus/scribus/third_party/pgf/WaveletTransform.cpp
==============================================================================
--- trunk/Scribus/scribus/third_party/pgf/WaveletTransform.cpp	(original)
+++ trunk/Scribus/scribus/third_party/pgf/WaveletTransform.cpp	Fri May  8 16:40:48 2020
@@ -38,14 +38,14 @@
 // @param levels The number of levels (>= 0)
 // @param data Input data of subband LL at level 0
 CWaveletTransform::CWaveletTransform(UINT32 width, UINT32 height, int levels, DataT* data) 
-: m_nLevels(levels + 1)
-, m_subband(0) 
+: m_nLevels(levels + 1) // m_nLevels in CPGFImage determines the number of FWT steps; this.m_nLevels determines the number subband-planes
+, m_subband(nullptr)
+#ifdef __PGFROISUPPORT__
+, m_indices(nullptr)
+#endif
 {
 	ASSERT(m_nLevels > 0 && m_nLevels <= MaxLevel + 1);
 	InitSubbands(width, height, data);
-#ifdef __PGFROISUPPORT__
-	m_ROIindices.SetLevels(levels + 1);
-#endif
 }
 
 /////////////////////////////////////////////////////////////////////
@@ -77,11 +77,11 @@
 
 //////////////////////////////////////////////////////////////////////////
 // Compute fast forward wavelet transform of LL subband at given level and
-// stores result on all 4 subbands of level + 1.
+// stores result in all 4 subbands of level + 1.
 // Wavelet transform used in writing a PGF file
 // Forward Transform of srcBand and split and store it into subbands on destLevel
-// high pass filter at even positions: 1/4(-2, 4, -2)
-// low pass filter at odd positions: 1/8(-1, 2, 6, 2, -1)
+// low pass filter at even positions: 1/8[-1, 2, (6), 2, -1]
+// high pass filter at odd positions: 1/4[-2, (4), -2]
 // @param level A wavelet transform pyramid level (>= 0 && < Levels())
 // @param quant A quantization value (linear scalar quantization)
 // @return error in case of a memory allocation problem
@@ -100,18 +100,17 @@
 		if (!m_subband[destLevel][i].AllocMemory()) return InsufficientMemory;
 	}
 
- 	if (height >= FilterHeight) {
-		// transform LL subband
+ 	if (height >= FilterSize) { // changed from FilterSizeH to FilterSize
 		// top border handling
 		row0 = src; row1 = row0 + width; row2 = row1 + width;
 		ForwardRow(row0, width);
 		ForwardRow(row1, width);
 		ForwardRow(row2, width);
 		for (UINT32 k=0; k < width; k++) {
-			row1[k] -= ((row0[k] + row2[k] + c1) >> 1);
-			row0[k] += ((row1[k] + c1) >> 1);
-		}
-		LinearToMallat(destLevel, row0, row1, width);
+			row1[k] -= ((row0[k] + row2[k] + c1) >> 1); // high pass
+			row0[k] += ((row1[k] + c1) >> 1); // low pass
+		}
+		InterleavedToSubbands(destLevel, row0, row1, width);
 		row0 = row1; row1 = row2; row2 += width; row3 = row2 + width;
 
 		// middle part
@@ -119,27 +118,27 @@
 			ForwardRow(row2, width);
 			ForwardRow(row3, width);
 			for (UINT32 k=0; k < width; k++) {
-				row2[k] -= ((row1[k] + row3[k] + c1) >> 1);
-				row1[k] += ((row0[k] + row2[k] + c2) >> 2);
+				row2[k] -= ((row1[k] + row3[k] + c1) >> 1); // high pass filter
+				row1[k] += ((row0[k] + row2[k] + c2) >> 2); // low pass filter
 			}
-			LinearToMallat(destLevel, row1, row2, width);
+			InterleavedToSubbands(destLevel, row1, row2, width);
 			row0 = row2; row1 = row3; row2 = row3 + width; row3 = row2 + width;
 		}
 
 		// bottom border handling
 		if (height & 1) {
 			for (UINT32 k=0; k < width; k++) {
-				row1[k] += ((row0[k] + c1) >> 1);
+				row1[k] += ((row0[k] + c1) >> 1); // low pass
 			}
-			LinearToMallat(destLevel, row1, NULL, width);
+			InterleavedToSubbands(destLevel, row1, nullptr, width);
 			row0 = row1; row1 += width;
 		} else {
 			ForwardRow(row2, width);
 			for (UINT32 k=0; k < width; k++) {
-				row2[k] -= row1[k];
-				row1[k] += ((row0[k] + row2[k] + c2) >> 2);
+				row2[k] -= row1[k]; // high pass
+				row1[k] += ((row0[k] + row2[k] + c2) >> 2); // low pass
 			}
-			LinearToMallat(destLevel, row1, row2, width);
+			InterleavedToSubbands(destLevel, row1, row2, width);
 			row0 = row1; row1 = row2; row2 += width;
 		}
 	} else {
@@ -149,12 +148,12 @@
 		for (UINT32 k=0; k < height; k += 2) {
 			ForwardRow(row0, width);
 			ForwardRow(row1, width);
-			LinearToMallat(destLevel, row0, row1, width);
+			InterleavedToSubbands(destLevel, row0, row1, width);
 			row0 += width << 1; row1 += width << 1;
 		}
 		// bottom
 		if (height & 1) {
-			LinearToMallat(destLevel, row0, NULL, width);
+			InterleavedToSubbands(destLevel, row0, nullptr, width);
 		}
 	}
 
@@ -176,37 +175,37 @@
 
 //////////////////////////////////////////////////////////////
 // Forward transform one row
-// high pass filter at even positions: 1/4(-2, 4, -2)
-// low pass filter at odd positions: 1/8(-1, 2, 6, 2, -1)
+// low pass filter at even positions: 1/8[-1, 2, (6), 2, -1]
+// high pass filter at odd positions: 1/4[-2, (4), -2]
 void CWaveletTransform::ForwardRow(DataT* src, UINT32 width) {
-	if (width >= FilterWidth) {
+	if (width >= FilterSize) {
 		UINT32 i = 3;
 
 		// left border handling
-		src[1] -= ((src[0] + src[2] + c1) >> 1);
-		src[0] += ((src[1] + c1) >> 1);
+		src[1] -= ((src[0] + src[2] + c1) >> 1); // high pass
+		src[0] += ((src[1] + c1) >> 1); // low pass
 		
 		// middle part
 		for (; i < width-1; i += 2) {
-			src[i] -= ((src[i-1] + src[i+1] + c1) >> 1);
-			src[i-1] += ((src[i-2] + src[i] + c2) >> 2);
+			src[i] -= ((src[i-1] + src[i+1] + c1) >> 1); // high pass
+			src[i-1] += ((src[i-2] + src[i] + c2) >> 2); // low pass
 		}
 
 		// right border handling
 		if (width & 1) {
-			src[i-1] += ((src[i-2] + c1) >> 1);
+			src[i-1] += ((src[i-2] + c1) >> 1); // low pass
 		} else {
-			src[i] -= src[i-1];
-			src[i-1] += ((src[i-2] + src[i] + c2) >> 2);
+			src[i] -= src[i-1]; // high pass
+			src[i-1] += ((src[i-2] + src[i] + c2) >> 2); // low pass
 		}
 	}
 }
 
 /////////////////////////////////////////////////////////////////
-// Copy transformed rows loRow and hiRow to subbands LL,HL,LH,HH
-void CWaveletTransform::LinearToMallat(int destLevel, DataT* loRow, DataT* hiRow, UINT32 width) {
+// Copy transformed and interleaved (L,H,L,H,...) rows loRow and hiRow to subbands LL,HL,LH,HH
+void CWaveletTransform::InterleavedToSubbands(int destLevel, DataT* loRow, DataT* hiRow, UINT32 width) {
 	const UINT32 wquot = width >> 1;
-	const bool wrem = width & 1;
+	const bool wrem = (width & 1);
 	CSubband &ll = m_subband[destLevel][LL], &hl = m_subband[destLevel][HL];
 	CSubband &lh = m_subband[destLevel][LH], &hh = m_subband[destLevel][HH];
 
@@ -235,8 +234,9 @@
 // stores result in LL subband of level - 1.
 // Inverse wavelet transform used in reading a PGF file
 // Inverse Transform srcLevel and combine to destBand
-// inverse high pass filter for even positions: 1/4(-1, 4, -1)
-// inverse low pass filter for odd positions: 1/8(-1, 4, 6, 4, -1)
+// low-pass coefficients at even positions, high-pass coefficients at odd positions
+// inverse filter for even positions: 1/4[-1, (4), -1]
+// inverse filter for odd positions: 1/8[-1, 4, (6), 4, -1]
 // @param srcLevel A wavelet transform pyramid level (> 0 && <= Levels())
 // @param w [out] A pointer to the returned width of subband LL (in pixels)
 // @param h [out] A pointer to the returned height of subband LL (in pixels)
@@ -251,14 +251,14 @@
 
 	// allocate memory for the results of the inverse transform 
 	if (!destBand->AllocMemory()) return InsufficientMemory;
-	DataT *dest = destBand->GetBuffer(), *origin = dest, *row0, *row1, *row2, *row3;
+	DataT *origin = destBand->GetBuffer(), *row0, *row1, *row2, *row3;
 
 #ifdef __PGFROISUPPORT__
-	PGFRect destROI = destBand->GetROI();	// is valid only after AllocMemory
-	width = destROI.Width();
-	height = destROI.Height();
-	const UINT32 destWidth = width; // destination buffer width
-	const UINT32 destHeight = height; // destination buffer height
+	PGFRect destROI = destBand->GetAlignedROI();	
+	const UINT32 destWidth  = destROI.Width();  // destination buffer width
+	const UINT32 destHeight = destROI.Height(); // destination buffer height
+	width = destWidth;		// destination working width
+	height = destHeight;	// destination working height
 
 	// update destination ROI
 	if (destROI.top & 1) {
@@ -274,15 +274,15 @@
 
 	// init source buffer position
 	const UINT32 leftD = destROI.left >> 1;
-	const UINT32 left0 = m_subband[srcLevel][LL].GetROI().left;
-	const UINT32 left1 = m_subband[srcLevel][HL].GetROI().left;
+	const UINT32 left0 = m_subband[srcLevel][LL].GetAlignedROI().left;
+	const UINT32 left1 = m_subband[srcLevel][HL].GetAlignedROI().left;
 	const UINT32 topD = destROI.top >> 1;
-	const UINT32 top0 = m_subband[srcLevel][LL].GetROI().top;
-	const UINT32 top1 = m_subband[srcLevel][LH].GetROI().top;
-	ASSERT(m_subband[srcLevel][LH].GetROI().left == left0);
-	ASSERT(m_subband[srcLevel][HH].GetROI().left == left1);
-	ASSERT(m_subband[srcLevel][HL].GetROI().top == top0);
-	ASSERT(m_subband[srcLevel][HH].GetROI().top == top1);
+	const UINT32 top0 = m_subband[srcLevel][LL].GetAlignedROI().top;
+	const UINT32 top1 = m_subband[srcLevel][LH].GetAlignedROI().top;
+	ASSERT(m_subband[srcLevel][LH].GetAlignedROI().left == left0);
+	ASSERT(m_subband[srcLevel][HH].GetAlignedROI().left == left1);
+	ASSERT(m_subband[srcLevel][HL].GetAlignedROI().top == top0);
+	ASSERT(m_subband[srcLevel][HH].GetAlignedROI().top == top1);
 
 	UINT32 srcOffsetX[2] = { 0, 0 };
 	UINT32 srcOffsetY[2] = { 0, 0 };
@@ -323,7 +323,7 @@
 			srcOffsetY[1] = top0 - top1;
 		}
 	}
-		
+
 	m_subband[srcLevel][LL].InitBuffPos(srcOffsetX[0], srcOffsetY[0]);
 	m_subband[srcLevel][HL].InitBuffPos(srcOffsetX[1], srcOffsetY[0]);
 	m_subband[srcLevel][LH].InitBuffPos(srcOffsetX[0], srcOffsetY[1]);
@@ -337,26 +337,26 @@
 	const UINT32 destHeight = height; // destination buffer height
 
 	// init source buffer position
-	for (int i=0; i < NSubbands; i++) {
+	for (int i = 0; i < NSubbands; i++) {
 		m_subband[srcLevel][i].InitBuffPos();
 	}
 #endif
 
-	if (destHeight >= FilterHeight) {
+	if (destHeight >= FilterSize) { // changed from FilterSizeH to FilterSize
 		// top border handling
 		row0 = origin; row1 = row0 + destWidth;
-		MallatToLinear(srcLevel, row0, row1, width);
-		for (UINT32 k=0; k < width; k++) {
-			row0[k] -= ((row1[k] + c1) >> 1);
+		SubbandsToInterleaved(srcLevel, row0, row1, width);
+		for (UINT32 k = 0; k < width; k++) {
+			row0[k] -= ((row1[k] + c1) >> 1); // even
 		}
 
 		// middle part
 		row2 = row1 + destWidth; row3 = row2 + destWidth;
-		for (UINT32 i=destROI.top + 2; i < destROI.bottom - 1; i += 2) {
-			MallatToLinear(srcLevel, row2, row3, width);
-			for (UINT32 k=0; k < width; k++) {
-				row2[k] -= ((row1[k] + row3[k] + c2) >> 2);
-				row1[k] += ((row0[k] + row2[k] + c1) >> 1);
+		for (UINT32 i = destROI.top + 2; i < destROI.bottom - 1; i += 2) {
+			SubbandsToInterleaved(srcLevel, row2, row3, width);
+			for (UINT32 k = 0; k < width; k++) {
+				row2[k] -= ((row1[k] + row3[k] + c2) >> 2); // even
+				row1[k] += ((row0[k] + row2[k] + c1) >> 1); // odd
 			}
 			InverseRow(row0, width);
 			InverseRow(row1, width);
@@ -365,17 +365,17 @@
 
 		// bottom border handling
 		if (height & 1) {
-			MallatToLinear(srcLevel, row2, NULL, width);
-			for (UINT32 k=0; k < width; k++) {
-				row2[k] -= ((row1[k] + c1) >> 1);
-				row1[k] += ((row0[k] + row2[k] + c1) >> 1);
+			SubbandsToInterleaved(srcLevel, row2, nullptr, width);
+			for (UINT32 k = 0; k < width; k++) {
+				row2[k] -= ((row1[k] + c1) >> 1); // even
+				row1[k] += ((row0[k] + row2[k] + c1) >> 1); // odd
 			}
 			InverseRow(row0, width);
 			InverseRow(row1, width);
 			InverseRow(row2, width);
 			row0 = row1; row1 = row2; row2 += destWidth;
 		} else {
-			for (UINT32 k=0; k < width; k++) {
+			for (UINT32 k = 0; k < width; k++) {
 				row1[k] += row0[k];
 			}
 			InverseRow(row0, width);
@@ -386,63 +386,64 @@
 		// height is too small
 		row0 = origin; row1 = row0 + destWidth;
 		// first part
-		for (UINT32 k=0; k < height; k += 2) {
-			MallatToLinear(srcLevel, row0, row1, width);
+		for (UINT32 k = 0; k < height; k += 2) {
+			SubbandsToInterleaved(srcLevel, row0, row1, width);
 			InverseRow(row0, width);
 			InverseRow(row1, width);
 			row0 += destWidth << 1; row1 += destWidth << 1;
 		}
 		// bottom
 		if (height & 1) {
-			MallatToLinear(srcLevel, row0, NULL, width);
+			SubbandsToInterleaved(srcLevel, row0, nullptr, width);
 			InverseRow(row0, width);
-		} 
+		}
 	}
 
 	// free memory of the current srcLevel
-	for (int i=0; i < NSubbands; i++) {
+	for (int i = 0; i < NSubbands; i++) {
 		m_subband[srcLevel][i].FreeMemory();
 	}
 
 	// return info
 	*w = destWidth;
-	*h = height;
-	*data = dest;
+	*h = destHeight;
+	*data = destBand->GetBuffer();
 	return NoError;
 }
 
 //////////////////////////////////////////////////////////////////////
 // Inverse Wavelet Transform of one row
-// inverse high pass filter for even positions: 1/4(-1, 4, -1)
-// inverse low pass filter for odd positions: 1/8(-1, 4, 6, 4, -1)
+// low-pass coefficients at even positions, high-pass coefficients at odd positions
+// inverse filter for even positions: 1/4[-1, (4), -1]
+// inverse filter for odd positions: 1/8[-1, 4, (6), 4, -1]
 void CWaveletTransform::InverseRow(DataT* dest, UINT32 width) {
-	if (width >= FilterWidth) {
+	if (width >= FilterSize) {
 		UINT32 i = 2;
 
 		// left border handling
-		dest[0] -= ((dest[1] + c1) >> 1);
+		dest[0] -= ((dest[1] + c1) >> 1); // even
 
 		// middle part
 		for (; i < width - 1; i += 2) {
-			dest[i] -= ((dest[i-1] + dest[i+1] + c2) >> 2);
-			dest[i-1] += ((dest[i-2] + dest[i] + c1) >> 1);
+			dest[i] -= ((dest[i-1] + dest[i+1] + c2) >> 2); // even
+			dest[i-1] += ((dest[i-2] + dest[i] + c1) >> 1); // odd
 		}
 
 		// right border handling
 		if (width & 1) {
-			dest[i] -= ((dest[i-1] + c1) >> 1);
-			dest[i-1] += ((dest[i-2] + dest[i] + c1) >> 1);
+			dest[i] -= ((dest[i-1] + c1) >> 1); // even
+			dest[i-1] += ((dest[i-2] + dest[i] + c1) >> 1); // odd
 		} else {
-			dest[i-1] += dest[i-2];
+			dest[i-1] += dest[i-2]; // odd
 		}
 	}
 }
 
 ///////////////////////////////////////////////////////////////////
-// Copy transformed coefficients from subbands LL,HL,LH,HH to interleaved format
-void CWaveletTransform::MallatToLinear(int srcLevel, DataT* loRow, DataT* hiRow, UINT32 width) {
+// Copy transformed coefficients from subbands LL,HL,LH,HH to interleaved format (L,H,L,H,...)
+void CWaveletTransform::SubbandsToInterleaved(int srcLevel, DataT* loRow, DataT* hiRow, UINT32 width) {
 	const UINT32 wquot = width >> 1;
-	const bool wrem = width & 1;
+	const bool wrem = (width & 1);
 	CSubband &ll = m_subband[srcLevel][LL], &hl = m_subband[srcLevel][HL];
 	CSubband &lh = m_subband[srcLevel][LH], &hh = m_subband[srcLevel][HH];
 
@@ -512,99 +513,57 @@
 
 #ifdef __PGFROISUPPORT__
 //////////////////////////////////////////////////////////////////////
-/// Compute and store ROIs for each level
-/// @param rect rectangular region of interest (ROI)
-void CWaveletTransform::SetROI(const PGFRect& rect) {
+/// Compute and store ROIs for nLevels
+/// @param roi rectangular region of interest at level 0
+void CWaveletTransform::SetROI(PGFRect roi) {
+	const UINT32 delta = (FilterSize >> 1) << m_nLevels;
+
 	// create tile indices
-	m_ROIindices.CreateIndices();
-
-	// compute tile indices
-	m_ROIindices.ComputeIndices(m_subband[0][LL].GetWidth(), m_subband[0][LL].GetHeight(), rect);
-
-	// compute ROIs
-	UINT32 w, h;
-	PGFRect r;
-
-	for (int i=0; i < m_nLevels; i++) {
-		const PGFRect& indices = m_ROIindices.GetIndices(i);
-
-		for (int o=0; o < NSubbands; o++) {
-			CSubband& subband = m_subband[i][o];
-
-			subband.SetNTiles(m_ROIindices.GetNofTiles(i)); // must be called before TilePosition()
-			subband.TilePosition(indices.left, indices.top, r.left, r.top, w, h);
-			subband.TilePosition(indices.right - 1, indices.bottom - 1, r.right, r.bottom, w, h);
-			r.right += w;
-			r.bottom += h;
-			subband.SetROI(r);
-		}
-	}
-}
-
-/////////////////////////////////////////////////////////////////////
-
-/////////////////////////////////////////////////////////////////////
-void CRoiIndices::CreateIndices() {
-	if (!m_indices) {
-		// create tile indices 
-		m_indices = new PGFRect[m_nLevels];
-	}
-}
-
-//////////////////////////////////////////////////////////////////////
-/// Computes a tile index either in x- or y-direction for a given image position.
-/// @param width PGF image width
-/// @param height PGF image height
-/// @param pos A valid image position: (0 <= pos < width) or (0 <= pos < height)
-/// @param horizontal If true, then pos must be a x-value, otherwise a y-value
-/// @param isMin If true, then pos is left/top, else pos right/bottom
-void CRoiIndices::ComputeTileIndex(UINT32 width, UINT32 height, UINT32 pos, bool horizontal, bool isMin) {
-	ASSERT(m_indices);
-
-	UINT32 m;
-	UINT32 tileIndex = 0;
-	UINT32 tileMin = 0, tileMax = (horizontal) ? width : height;
-	ASSERT(pos <= tileMax);
-
-	// compute tile index with binary search
-	for (int i=m_nLevels - 1; i >= 0; i--) {
-		// store values
-		if (horizontal) {
-			if (isMin) {
-				m_indices[i].left = tileIndex;
-			} else {
-				m_indices[i].right = tileIndex + 1;
-			}
-		} else {
-			if (isMin) {
-				m_indices[i].top = tileIndex;
-			} else {
-				m_indices[i].bottom = tileIndex + 1;
-			}
-		}
-
-		// compute values
-		tileIndex <<= 1;
-		m = tileMin + (tileMax - tileMin)/2;
-		if (pos >= m) {
-			tileMin = m;
-			tileIndex++;
-		} else {
-			tileMax = m;
-		}
-	}
-}
-
-/////////////////////////////////////////////////////////////////////
-/// Compute tile indices for given rectangle (ROI)
-/// @param width PGF image width
-/// @param height PGF image height
-/// @param rect ROI
-void CRoiIndices::ComputeIndices(UINT32 width, UINT32 height, const PGFRect& rect) {
-	ComputeTileIndex(width, height, rect.left, true, true);
-	ComputeTileIndex(width, height, rect.top, false, true);
-	ComputeTileIndex(width, height, rect.right, true, false);
-	ComputeTileIndex(width, height, rect.bottom, false, false);
+	delete[] m_indices;
+	m_indices = new PGFRect[m_nLevels];
+
+	// enlarge rect: add margin
+	roi.left = (roi.left > delta) ? roi.left - delta : 0;
+	roi.top  = (roi.top  > delta) ? roi.top  - delta : 0;
+	roi.right += delta; 
+	roi.bottom += delta; 
+
+	for (int l = 0; l < m_nLevels; l++) {
+		PGFRect alignedROI;
+		PGFRect& indices = m_indices[l];
+		UINT32 nTiles = GetNofTiles(l);
+		CSubband& subband = m_subband[l][LL];
+
+		// use roi to determine the necessary tile indices (for all subbands the same) and aligned ROI for LL subband
+		subband.SetNTiles(nTiles); // must be called before TileIndex()
+		subband.TileIndex(true, roi.left, roi.top, indices.left, indices.top, alignedROI.left, alignedROI.top);
+		subband.TileIndex(false, roi.right, roi.bottom, indices.right, indices.bottom, alignedROI.right, alignedROI.bottom);
+		subband.SetAlignedROI(alignedROI);
+		ASSERT(l == 0 ||
+			(m_indices[l-1].left >= 2*m_indices[l].left &&
+			m_indices[l-1].top >= 2*m_indices[l].top &&
+			m_indices[l-1].right <= 2*m_indices[l].right &&
+			m_indices[l-1].bottom <= 2*m_indices[l].bottom));
+
+		// determine aligned ROI of other three subbands
+		PGFRect aroi;
+		UINT32 w, h;
+		for (int b = 1; b < NSubbands; b++) {
+			CSubband& sb = m_subband[l][b];
+			sb.SetNTiles(nTiles); // must be called before TilePosition()
+			sb.TilePosition(indices.left, indices.top, aroi.left, aroi.top, w, h);
+			sb.TilePosition(indices.right - 1, indices.bottom - 1, aroi.right, aroi.bottom, w, h);
+			aroi.right += w;
+			aroi.bottom += h;
+			sb.SetAlignedROI(aroi);
+		}
+
+		// use aligned ROI of LL subband for next level
+		roi.left = alignedROI.left >> 1;
+		roi.top = alignedROI.top >> 1;
+		roi.right = (alignedROI.right + 1) >> 1;
+		roi.bottom = (alignedROI.bottom + 1) >> 1;
+	}
 }
 
 #endif // __PGFROISUPPORT__

Modified: trunk/Scribus/scribus/third_party/pgf/WaveletTransform.h
URL: http://scribus.net/websvn/diff.php?repname=Scribus&rev=23713&path=/trunk/Scribus/scribus/third_party/pgf/WaveletTransform.h
==============================================================================
--- trunk/Scribus/scribus/third_party/pgf/WaveletTransform.h	(original)
+++ trunk/Scribus/scribus/third_party/pgf/WaveletTransform.h	Fri May  8 16:40:48 2020
@@ -34,8 +34,9 @@
 
 //////////////////////////////////////////////////////////////////////
 // Constants
-#define FilterWidth			5					///< number of coefficients of the row wavelet filter
-#define FilterHeight		3					///< number of coefficients of the column wavelet filter
+const UINT32 FilterSizeL = 5;					///< number of coefficients of the low pass filter
+const UINT32 FilterSizeH = 3;					///< number of coefficients of the high pass filter
+const UINT32 FilterSize = __max(FilterSizeL, FilterSizeH);
 
 #ifdef __PGFROISUPPORT__
 //////////////////////////////////////////////////////////////////////
@@ -43,36 +44,6 @@
 /// @author C. Stamm
 /// @brief ROI indices
 class CRoiIndices {
-	friend class CWaveletTransform;
-
-	//////////////////////////////////////////////////////////////////////
-	/// Constructor: Creates a ROI helper object
-	CRoiIndices() 
-	: m_nLevels(0)
-	, m_indices(0) 
-	{}
-
-	//////////////////////////////////////////////////////////////////////
-	/// Destructor
-	~CRoiIndices() { Destroy(); }
-
-	void Destroy()								{ delete[] m_indices; m_indices = 0; }
-	void CreateIndices();
-	void ComputeIndices(UINT32 width, UINT32 height, const PGFRect& rect);
-	const PGFRect& GetIndices(int level) const	{ ASSERT(m_indices); ASSERT(level >= 0 && level < m_nLevels); return m_indices[level]; }
-	void SetLevels(int levels)					{ ASSERT(levels > 0); m_nLevels = levels; }
-	void ComputeTileIndex(UINT32 width, UINT32 height, UINT32 pos, bool horizontal, bool isMin);
-
-public:
-	//////////////////////////////////////////////////////////////////////
-	/// Returns the number of tiles in one dimension at given level.
-	/// @param level A wavelet transform pyramid level (>= 0 && < Levels())
-	UINT32 GetNofTiles(int level) const			{ ASSERT(level >= 0 && level < m_nLevels); return 1 << (m_nLevels - level - 1); }
-
-private:
-	int      m_nLevels;			///< number of levels of the image
-	PGFRect *m_indices;			///< array of tile indices (index is level)
-
 };
 #endif //__PGFROISUPPORT__
 
@@ -91,7 +62,7 @@
 	/// @param height The height of the original image (at level 0) in pixels
 	/// @param levels The number of levels (>= 0)
 	/// @param data Input data of subband LL at level 0
-	CWaveletTransform(UINT32 width, UINT32 height, int levels, DataT* data = NULL);
+	CWaveletTransform(UINT32 width, UINT32 height, int levels, DataT* data = nullptr);
 
 	//////////////////////////////////////////////////////////////////////
 	/// Destructor
@@ -99,7 +70,7 @@
 	
 	//////////////////////////////////////////////////////////////////////
 	/// Compute fast forward wavelet transform of LL subband at given level and
-	/// stores result on all 4 subbands of level + 1.
+	/// stores result in all 4 subbands of level + 1.
 	/// @param level A wavelet transform pyramid level (>= 0 && < Levels())
 	/// @param quant A quantization value (linear scalar quantization)
 	/// @return error in case of a memory allocation problem
@@ -126,45 +97,48 @@
 	
 #ifdef __PGFROISUPPORT__
 	//////////////////////////////////////////////////////////////////////
-	/// Compute and store ROIs for each level
-	/// @param rect rectangular region of interest (ROI)
-	void SetROI(const PGFRect& rect);
+	/// Compute and store ROIs for nLevels
+	/// @param rect rectangular region of interest (ROI) at level 0
+	void SetROI(PGFRect rect);
 
 	//////////////////////////////////////////////////////////////////////
-	/// Get tile indices of a ROI at given level.
+	/// Checks the relevance of a given tile at given level.
 	/// @param level A valid subband level.
-	const PGFRect& GetTileIndices(int level) const		{ return m_ROIindices.GetIndices(level); }
+	/// @param tileX x-index of the given tile
+	/// @param tileY y-index of the given tile
+	const bool TileIsRelevant(int level, UINT32 tileX, UINT32 tileY) const { ASSERT(m_indices); ASSERT(level >= 0 && level < m_nLevels); return m_indices[level].IsInside(tileX, tileY); }
 
 	//////////////////////////////////////////////////////////////////////
-	/// Get number of tiles in x- or y-direction at given level.
+	/// Get number of tiles in x- or y-direction at given level. 
+	/// This number is independent of the given ROI.
 	/// @param level A valid subband level.
-	UINT32 GetNofTiles(int level) const					{ return m_ROIindices.GetNofTiles(level); }
+	UINT32 GetNofTiles(int level) const { ASSERT(level >= 0 && level < m_nLevels); return 1 << (m_nLevels - level - 1); }
 
 	//////////////////////////////////////////////////////////////////////
 	/// Return ROI at given level.
 	/// @param level A valid subband level.
-	const PGFRect& GetROI(int level) const				{ return m_subband[level][LL].GetROI(); }
+	const PGFRect& GetAlignedROI(int level) const		{ return m_subband[level][LL].GetAlignedROI(); }
 
 #endif // __PGFROISUPPORT__
 
 private:
 	void Destroy() { 
-		delete[] m_subband; m_subband = 0; 
+		delete[] m_subband; m_subband = nullptr;
 	#ifdef __PGFROISUPPORT__
-		m_ROIindices.Destroy(); 
+		delete[] m_indices; m_indices = nullptr;
 	#endif
 	}
 	void InitSubbands(UINT32 width, UINT32 height, DataT* data);
 	void ForwardRow(DataT* buff, UINT32 width);
 	void InverseRow(DataT* buff, UINT32 width);
-	void LinearToMallat(int destLevel,DataT* loRow, DataT* hiRow, UINT32 width);
-	void MallatToLinear(int srcLevel, DataT* loRow, DataT* hiRow, UINT32 width);
+	void InterleavedToSubbands(int destLevel, DataT* loRow, DataT* hiRow, UINT32 width);
+	void SubbandsToInterleaved(int srcLevel, DataT* loRow, DataT* hiRow, UINT32 width);
 
 #ifdef __PGFROISUPPORT__
-	CRoiIndices		m_ROIindices;				///< ROI indices 
+	PGFRect *m_indices;							///< array of length m_nLevels of tile indices
 #endif //__PGFROISUPPORT__
 
-	int			m_nLevels;						///< number of transform levels: one more than the number of level in PGFimage
+	int			m_nLevels;						///< number of LL levels: one more than header.nLevels in PGFimage
 	CSubband	(*m_subband)[NSubbands];		///< quadtree of subbands: LL HL LH HH
 };
 




More information about the scribus-commit mailing list