2
* The Progressive Graphics File; http://www.libpgf.org
4
* $Date: 2006-06-04 22:05:59 +0200 (So, 04 Jun 2006) $
7
* This file Copyright (C) 2006 xeraina GmbH, Switzerland
9
* This program is free software; you can redistribute it and/or
10
* modify it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE
11
* as published by the Free Software Foundation; either version 2.1
12
* of the License, or (at your option) any later version.
14
* This program is distributed in the hope that it will be useful,
15
* but WITHOUT ANY WARRANTY; without even the implied warranty of
16
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
* GNU General Public License for more details.
19
* You should have received a copy of the GNU General Public License
20
* along with this program; if not, write to the Free Software
21
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29
//////////////////////////////////////////////////////
30
// PGF: file structure
32
// PGFPreHeader PGFHeader PGFPostHeader LevelLengths Level_n-1 Level_n-2 ... Level_0
33
// PGFPostHeader ::= [ColorTable] [UserData]
34
// LevelLengths ::= UINT32[nLevels]
36
//////////////////////////////////////////////////////
39
// output: wavelet coefficients stored in subbands
41
// file (for each buffer: packedLength (16 bit), packed bits)
43
// m_codeBuffer (for each plane: RLcodeLength (16 bit), RLcoded sigBits + m_sign, refBits)
45
// m_sign sigBits refBits [BufferLen, BufferLen, BufferLen]
47
// m_value [BufferSize]
53
#define CodeBufferBitLen (BufferSize*WordWidth) // max number of bits in m_codeBuffer
55
/////////////////////////////////////////////////////////////////////
56
// Default Constructor
57
CDecoder::CDecoder(CPGFStream* stream /*= NULL */)
58
: m_stream(stream), m_startPos(0), m_encodedHeaderLength(0), m_valuePos(0), m_bufferIsAvailable(false)
59
#ifdef __PGFROISUPPORT__
65
/////////////////////////////////////////////////////////////////////
67
// Read pre-header, header, and levelLength
69
CDecoder::CDecoder(CPGFStream* stream, PGFPreHeader& preHeader, PGFHeader& header, PGFPostHeader& postHeader, UINT32*& levelLength) THROW_
70
: m_stream(stream), m_startPos(0), m_encodedHeaderLength(0), m_valuePos(0), m_bufferIsAvailable(false)
71
#ifdef __PGFROISUPPORT__
79
// store current stream position
80
m_startPos = m_stream->GetPos();
82
// read magic and version
83
count = MagicVersionSize;
84
m_stream->Read(&count, &preHeader);
87
if (preHeader.version & Version6) {
88
// 32 bit header size since version 6
93
m_stream->Read(&count, ((UINT8*)&preHeader) + MagicVersionSize);
95
// make sure the values are correct read
96
preHeader.hSize = __VAL(preHeader.hSize);
99
if (memcmp(preHeader.magic, Magic, 3) != 0) {
100
// error condition: wrong Magic number
101
ReturnWithError(FormatCannotRead);
105
count = (preHeader.hSize < HeaderSize) ? preHeader.hSize : HeaderSize;
106
m_stream->Read(&count, &header);
107
// make sure the values are correct read
108
header.height = __VAL(UINT32(header.height));
109
header.width = __VAL(UINT32(header.width));
111
// be ready to read all versions including version 0
112
if (preHeader.version > 0) {
113
#ifndef __PGFROISUPPORT__
115
if (preHeader.version & PGFROI) ReturnWithError(FormatCannotRead);
118
int size = preHeader.hSize - HeaderSize;
122
if (header.mode == ImageModeIndexedColor) {
123
ASSERT(size >= ColorTableSize);
125
count = ColorTableSize;
126
m_stream->Read(&count, postHeader.clut);
127
ASSERT(count == ColorTableSize);
132
// create user data memory block
133
postHeader.userDataLen = size;
134
postHeader.userData = new UINT8[postHeader.userDataLen];
137
count = postHeader.userDataLen;
138
m_stream->Read(&count, postHeader.userData);
139
ASSERT(count == size);
143
// create levelLength
144
levelLength = new UINT32[header.nLevels];
145
if (!levelLength) ReturnWithError(InsufficientMemory);
148
count = header.nLevels*WordBytes;
149
m_stream->Read(&count, levelLength);
151
#ifdef PGF_USE_BIG_ENDIAN
152
// make sure the values are correct read
154
for (int i=0; i < count; i++) {
155
levelLength[i] = __VAL(levelLength[i]);
160
// store current stream position
161
m_encodedHeaderLength = UINT32(m_stream->GetPos() - m_startPos);
164
/////////////////////////////////////////////////////////////////////
166
CDecoder::~CDecoder() {
169
//////////////////////////////////////////////////////////////////////
170
/// Copies data from the open stream to a target buffer.
171
/// It might throw an IOException.
172
/// @param target The target buffer
173
/// @param len The number of bytes to read
174
/// @return The number of bytes copied to the target buffer
175
UINT32 CDecoder::ReadEncodedData(UINT8* target, UINT32 len) const THROW_ {
179
m_stream->Read(&count, target);
184
/////////////////////////////////////////////////////////////////////
185
/// Unpartitions a rectangular region of a given subband.
186
/// Partitioning scheme: The plane is partitioned in squares of side length LinBlockSize.
187
/// Write wavelet coefficients into buffer.
188
/// It might throw an IOException.
189
/// @param band A subband
190
/// @param quantParam Dequantization value
191
/// @param width The width of the rectangle
192
/// @param height The height of the rectangle
193
/// @param startPos The buffer position of the top left corner of the rectangular region
194
/// @param pitch The number of bytes in row of the subband
195
void CDecoder::Partition(CSubband* band, int quantParam, int width, int height, int startPos, int pitch) THROW_ {
198
const div_t ww = div(width, LinBlockSize);
199
const div_t hh = div(height, LinBlockSize);
200
const int ws = pitch - LinBlockSize;
201
const int wr = pitch - ww.rem;
203
int pos, base = startPos, base2;
206
for (i=0; i < hh.quot; i++) {
209
for (j=0; j < ww.quot; j++) {
211
for (y=0; y < LinBlockSize; y++) {
212
for (x=0; x < LinBlockSize; x++) {
213
DequantizeValue(band, pos, quantParam);
218
base2 += LinBlockSize;
222
for (y=0; y < LinBlockSize; y++) {
223
for (x=0; x < ww.rem; x++) {
224
DequantizeValue(band, pos, quantParam);
233
for (j=0; j < ww.quot; j++) {
236
for (y=0; y < hh.rem; y++) {
237
for (x=0; x < LinBlockSize; x++) {
238
DequantizeValue(band, pos, quantParam);
243
base2 += LinBlockSize;
247
for (y=0; y < hh.rem; y++) {
249
for (x=0; x < ww.rem; x++) {
250
DequantizeValue(band, pos, quantParam);
257
////////////////////////////////////////////////////////////////////
258
// Decode and dequantize HL, and LH band of one level
259
// LH and HH are interleaved in the codestream and must be split
260
// Deccoding and dequantization of HL and LH Band (interleaved) using partitioning scheme
261
// partitions the plane in squares of side length InterBlockSize
262
// throws IOException
263
void CDecoder::DecodeInterleaved(CWaveletTransform* wtChannel, int level, int quantParam) THROW_ {
264
CSubband* hlBand = wtChannel->GetSubband(level, HL);
265
CSubband* lhBand = wtChannel->GetSubband(level, LH);
266
const div_t lhH = div(lhBand->GetHeight(), InterBlockSize);
267
const div_t hlW = div(hlBand->GetWidth(), InterBlockSize);
268
const int hlws = hlBand->GetWidth() - InterBlockSize;
269
const int hlwr = hlBand->GetWidth() - hlW.rem;
270
const int lhws = lhBand->GetWidth() - InterBlockSize;
271
const int lhwr = lhBand->GetWidth() - hlW.rem;
274
int hlBase = 0, lhBase = 0, hlBase2, lhBase2;
276
ASSERT(lhBand->GetWidth() >= hlBand->GetWidth());
277
ASSERT(hlBand->GetHeight() >= lhBand->GetHeight());
279
hlBand->AllocMemory();
280
lhBand->AllocMemory();
282
// correct quantParam with normalization factor
284
if (quantParam < 0) quantParam = 0;
287
for (i=0; i < lhH.quot; i++) {
291
for (j=0; j < hlW.quot; j++) {
294
for (y=0; y < InterBlockSize; y++) {
295
for (x=0; x < InterBlockSize; x++) {
296
DequantizeValue(hlBand, hlPos, quantParam);
297
DequantizeValue(lhBand, lhPos, quantParam);
304
hlBase2 += InterBlockSize;
305
lhBase2 += InterBlockSize;
310
for (y=0; y < InterBlockSize; y++) {
311
for (x=0; x < hlW.rem; x++) {
312
DequantizeValue(hlBand, hlPos, quantParam);
313
DequantizeValue(lhBand, lhPos, quantParam);
317
// width difference between HL and LH
318
if (lhBand->GetWidth() > hlBand->GetWidth()) {
319
DequantizeValue(lhBand, lhPos, quantParam);
323
hlBase += hlBand->GetWidth();
324
lhBase += lhBand->GetWidth();
330
for (j=0; j < hlW.quot; j++) {
334
for (y=0; y < lhH.rem; y++) {
335
for (x=0; x < InterBlockSize; x++) {
336
DequantizeValue(hlBand, hlPos, quantParam);
337
DequantizeValue(lhBand, lhPos, quantParam);
344
hlBase2 += InterBlockSize;
345
lhBase2 += InterBlockSize;
350
for (y=0; y < lhH.rem; y++) {
352
for (x=0; x < hlW.rem; x++) {
353
DequantizeValue(hlBand, hlPos, quantParam);
354
DequantizeValue(lhBand, lhPos, quantParam);
358
// width difference between HL and LH
359
if (lhBand->GetWidth() > hlBand->GetWidth()) {
360
DequantizeValue(lhBand, lhPos, quantParam);
364
hlBase += hlBand->GetWidth();
366
// height difference between HL and LH
367
if (hlBand->GetHeight() > lhBand->GetHeight()) {
370
for (j=0; j < hlBand->GetWidth(); j++) {
371
DequantizeValue(hlBand, hlPos, quantParam);
377
////////////////////////////////////////////////////////////////////
378
/// Skip a given number of bytes in the open stream.
379
/// It might throw an IOException.
380
void CDecoder::Skip(UINT64 offset) THROW_ {
381
m_stream->SetPos(FSFromCurrent, offset);
384
//////////////////////////////////////////////////////////////////////
385
/// Dequantization of a single value at given position in subband.
386
/// If encoded data is available, then stores dequantized band value into
387
/// buffer m_value at position m_valuePos.
388
/// Otherwise reads encoded data buffer and decodes it.
389
/// @param band A subband
390
/// @param bandPos A valid position in subband band
391
/// @param quantParam The quantization parameter
392
void CDecoder::DequantizeValue(CSubband* band, UINT32 bandPos, int quantParam) {
393
if (!m_bufferIsAvailable) {
396
band->SetData(bandPos, m_value[m_valuePos] << quantParam);
398
if (m_valuePos == BufferSize) {
399
m_bufferIsAvailable = false;
403
///////////////////////////////////////////////////////
404
// Read next block from stream and decode into buffer
405
// Decoding scheme: <wordLen>(16 bits) [ ROI ] data
406
// ROI ::= <bufferSize>(15 bits) <eofTile>(1 bit)
407
// throws IOException
408
void CDecoder::DecodeBuffer() THROW_ {
410
ROIBlockHeader h(BufferSize);
414
UINT32 filePos = (UINT32)m_stream->GetPos();
415
printf("%d\n", filePos);
419
count = sizeof(UINT16);
420
m_stream->Read(&count, &wordLen); ASSERT(count == sizeof(UINT16));
421
wordLen = __VAL(wordLen);
422
ASSERT(wordLen <= BufferSize);
424
#ifdef __PGFROISUPPORT__
425
// read ROIBlockHeader
427
m_stream->Read(&count, &h.val); ASSERT(count == sizeof(UINT16));
429
// convert ROIBlockHeader
430
h.val = __VAL(h.val);
435
count = wordLen*WordBytes;
436
m_stream->Read(&count, m_codeBuffer);
438
#ifdef PGF_USE_BIG_ENDIAN
441
for (int i=0; i < count; i++) {
442
m_codeBuffer[i] = __VAL(m_codeBuffer[i]);
446
#ifdef __PGFROISUPPORT__
447
ASSERT(m_roi && h.bufferSize <= BufferSize || h.bufferSize == BufferSize);
449
ASSERT(h.bufferSize == BufferSize);
451
BitplaneDecode(h.bufferSize);
454
m_bufferIsAvailable = true;
458
///////////////////////////////////////////////////////
459
// Read next block from stream but don't decode into buffer
460
// Encoding scheme: <wordLen>(16 bits) [ ROI ] data
461
// ROI ::= <bufferSize>(15 bits) <eofTile>(1 bit)
462
// throws IOException
463
void CDecoder::SkipBuffer() THROW_ {
468
count = sizeof(UINT16);
469
m_stream->Read(&count, &wordLen); ASSERT(count == sizeof(UINT16));
470
wordLen = __VAL(wordLen);
471
ASSERT(wordLen <= BufferSize);
473
#ifdef __PGFROISUPPORT__
475
// skip ROIBlockHeader
476
m_stream->SetPos(FSFromCurrent, count);
481
m_stream->SetPos(FSFromCurrent, wordLen*WordBytes);
484
//////////////////////////////////////////////////////////////////////
485
// Decode block into buffer of given size using bit plane coding.
486
// A buffer contains bufferLen UINT32 values, thus, bufferSize bits per bit plane.
487
// Following coding scheme is used:
488
// Buffer ::= <nPlanes>(5 bits) foreach(plane i): Plane[i]
489
// Plane[i] ::= [ Sig1 | Sig2 ] [DWORD alignment] refBits
490
// Sig1 ::= 1 <codeLen>(15 bits) codedSigAndSignBits
491
// Sig2 ::= 0 <sigLen>(15 bits) [Sign1 | Sign2 ] sigBits
492
// Sign1 ::= 1 <codeLen>(15 bits) [DWORD alignment] codedSignBits
493
// Sign2 ::= 0 <signLen>(15 bits) [DWORD alignment] signBits
494
void CDecoder::BitplaneDecode(UINT32 bufferSize) {
495
ASSERT(bufferSize <= BufferSize);
496
const UINT32 bufferLen = AlignWordPos(bufferSize)/WordWidth;
499
UINT32 codePos = 0, codeLen, sigLen, sigPos, signLen, wordPos;
501
UINT32 sigBits[BufferLen];
502
UINT32 signBits[BufferLen];
505
// clear significance vector
506
for (k=0; k < bufferLen; k++) {
507
m_sigFlagVector[k] = 0;
511
for (k=0; k < bufferSize; k++) {
515
// read number of bit planes
516
nPlanes = GetValueBlock(m_codeBuffer, 0, MaxBitPlanesLog);
517
codePos += MaxBitPlanesLog;
519
// loop through all bit planes
520
if (nPlanes == 0) nPlanes = MaxBitPlanes + 1;
521
ASSERT(0 < nPlanes && nPlanes <= MaxBitPlanes + 1);
522
planeMask = 1 << (nPlanes - 1);
524
for (plane = nPlanes - 1; plane >= 0; plane--) {
526
if (GetBit(m_codeBuffer, codePos)) {
527
// RL coding of sigBits is used
531
codeLen = GetValueBlock(m_codeBuffer, codePos, RLblockSizeLen);
533
// run-length decode significant bits and signs from m_codeBuffer and store them to sigBits
534
ASSERT(codeLen < (1 << RLblockSizeLen));
535
m_codePos = codePos + RLblockSizeLen;
536
sigLen = RLDSigsAndSigns(bufferSize, codeLen, sigBits, signBits); ASSERT(sigLen <= bufferSize);
537
//printf("%d\n", sigLen);
539
// adjust code buffer position
540
codePos += RLblockSizeLen + codeLen;
541
codePos = AlignWordPos(codePos); ASSERT(codePos < CodeBufferBitLen);
543
// read refinement bits from m_codeBuffer and compose bit plane
544
sigLen = ComposeBitplane(bufferSize, planeMask, sigBits, &m_codeBuffer[codePos >> WordWidthLog], signBits);
546
// adjust code buffer position
547
codePos += bufferSize - sigLen;
548
codePos = AlignWordPos(codePos); ASSERT(codePos < CodeBufferBitLen);
550
// no RL coding is used
554
sigLen = GetValueBlock(m_codeBuffer, codePos, RLblockSizeLen); ASSERT(sigLen <= BufferSize);
555
codePos += RLblockSizeLen; ASSERT(codePos < CodeBufferBitLen);
557
// read RL code for signBits
558
if (GetBit(m_codeBuffer, codePos)) {
563
codeLen = GetValueBlock(m_codeBuffer, codePos, RLblockSizeLen);
564
codePos += RLblockSizeLen;
566
// RL decode signBits
568
signLen = RLDSigns(bufferSize, codeLen, signBits);
570
// adjust code buffer position
572
codePos = AlignWordPos(codePos); ASSERT(codePos < CodeBufferBitLen);
574
// RL coding of signBits was not efficient and therefore not used
578
signLen = GetValueBlock(m_codeBuffer, codePos, RLblockSizeLen); ASSERT(signLen <= bufferSize);
580
// adjust code buffer position
581
codePos += RLblockSizeLen;
582
codePos = AlignWordPos(codePos); ASSERT(codePos < CodeBufferBitLen);
585
wordPos = codePos >> WordWidthLog; ASSERT(0 <= wordPos && wordPos < BufferSize);
586
signLen = AlignWordPos(signLen) >> WordWidthLog;
587
for (k=0; k < signLen; k++) {
588
signBits[k] = m_codeBuffer[wordPos];
592
// adjust code buffer position
593
codePos = wordPos << WordWidthLog; ASSERT(codePos < CodeBufferBitLen);
596
sigPos = codePos; // position of sigBits
599
codePos = AlignWordPos(codePos);
600
ASSERT(codePos < CodeBufferBitLen);
602
// read significant and refinement bitset from m_codeBuffer
603
sigLen = ComposeBitplane(bufferSize, planeMask, &m_codeBuffer[sigPos >> WordWidthLog], &m_codeBuffer[codePos >> WordWidthLog], signBits);
605
// adjust code buffer position
606
codePos += bufferSize - sigLen;
607
codePos = AlignWordPos(codePos);
613
////////////////////////////////////////////////////////////////////
614
// Reconstruct bitplane from significant bitset and refinement bitset
615
// returns length [bits] of sigBits
616
// input: sigBits, refBits
618
UINT32 CDecoder::ComposeBitplane(UINT32 bufferSize, UINT32 planeMask, UINT32* sigBits, UINT32* refBits, UINT32* signBits) {
623
UINT32 valPos = 0, signPos = 0, refPos = 0;
624
UINT32 sigPos = 0, sigEnd, sigRunLen;
627
while (valPos < bufferSize) {
628
// search next 1 in m_sigFlagVector
629
sigRunLen = SeekBitRange(m_sigFlagVector, valPos, bufferSize - valPos);
631
// search 1's in sigBits[valuePos..valuePos+sigRunLen)
632
// these 1's are significant bits
633
sigEnd = sigPos + sigRunLen;
634
while (sigPos < sigEnd) {
636
zerocnt = SeekBitRange(sigBits, sigPos, sigEnd - sigPos);
639
if (sigPos < sigEnd) {
640
// write bit to m_value
641
SetBitAtPos(valPos, planeMask);
644
SetSign(valPos, GetBit(signBits, signPos));
647
// update significance flag vector
648
SetBit(m_sigFlagVector, valPos);
654
if (valPos < bufferSize) {
655
// write one refinement bit
656
if (GetBit(refBits, refPos)) {
657
SetBitAtPos(valPos, planeMask);
663
ASSERT(sigPos <= bufferSize);
664
ASSERT(refPos <= bufferSize);
665
ASSERT(signPos <= bufferSize);
666
ASSERT(valPos == bufferSize);
671
//////////////////////////////////////////////////////////////////////
672
// Adaptive run-Length decoder for significant bits with a lot of zeros and sign bits.
673
// Returns length of sigBits.
674
// - Decode run of 2^k zeros by a single 0.
675
// - Decode run of count 0's followed by a 1 with codeword: 1<count>x
676
// - x is 0: if a positive sign has been stored, otherwise 1
677
// - Read each bit from m_codeBuffer[m_codePos] and increment m_codePos.
678
UINT32 CDecoder::RLDSigsAndSigns(UINT32 bufferSize, UINT32 codeLen, UINT32* sigBits, UINT32* signBits) {
681
ASSERT(m_codePos < CodeBufferBitLen);
682
const UINT32 inEndPos = m_codePos + codeLen; ASSERT(inEndPos < CodeBufferBitLen);
685
UINT32 runlen = 1 << k; // = 2^k
687
UINT32 sigPos = 0, signPos = 0;
689
ASSERT(inEndPos < CodeBufferBitLen);
690
while (m_codePos < inEndPos) {
691
if (GetBit(m_codeBuffer, m_codePos)) {
694
// extract counter and generate zero run of length count
697
count = GetValueBlock(m_codeBuffer, m_codePos, k);
700
ClearBitBlock(sigBits, sigPos, count);
705
if (sigPos < bufferSize) {
706
SetBit(sigBits, sigPos); sigPos++;
710
if (GetBit(m_codeBuffer, m_codePos)) {
711
SetBit(signBits, signPos);
713
ClearBit(signBits, signPos);
715
signPos++; m_codePos++;
717
// adapt k (half run-length interval)
724
// generate zero run of length 2^k
725
//ASSERT(sigPos + runlen <= BufferSize);
726
ClearBitBlock(sigBits, sigPos, runlen);
729
// adapt k (double run-length interval)
739
/////////////////////////////////////////////////////
740
// Adaptive run-length decoder.
741
// Returns signLen in bits.
742
// decodes codeLen bits from m_codeBuffer at m_codePos
743
// decode run of 2^k 1's by a single 1
744
// decode run of count 1's followed by a 0 with codeword: 0<count>
745
// output is stored in signBits
746
UINT32 CDecoder::RLDSigns(UINT32 bufferSize, UINT32 codeLen, UINT32* signBits) {
748
ASSERT(0 <= m_codePos && m_codePos < CodeBufferBitLen);
749
const UINT32 inEndPos = m_codePos + codeLen; ASSERT(inEndPos < CodeBufferBitLen);
752
UINT32 runlen = 1 << k; // = 2^k
753
UINT32 count = 0, signPos = 0;
755
while (m_codePos < inEndPos) {
756
if (GetBit(m_codeBuffer, m_codePos)) {
758
// generate 1's run of length 2^k
759
SetBitBlock(signBits, signPos, runlen);
762
// adapt k (double run-length interval)
769
// extract counter and generate zero run of length count
772
count = GetValueBlock(m_codeBuffer, m_codePos, k);
775
SetBitBlock(signBits, signPos, count);
779
if (signPos < bufferSize) {
780
ClearBit(signBits, signPos);
784
// adapt k (half run-length interval)
794
////////////////////////////////////////////////////////////////////
796
void CDecoder::DumpBuffer() {
798
for (int i=0; i < BufferSize; i++) {
799
printf("%d", m_value[i]);