forked from JoshDullen/libtiffN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tif_lzw.cs
executable file
·1296 lines (1145 loc) · 35.3 KB
/
tif_lzw.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#if LZW_SUPPORT
// tif_lzw.cs
//
// Based on LIBTIFF, Version 3.9.4 - 15-Jun-2010
// Copyright (c) 2006-2010 by the Authors
// Copyright (c) 1988-1997 Sam Leffler
// Copyright (c) 1991-1997 Silicon Graphics, Inc.
//
// Permission to use, copy, modify, distribute, and sell this software and
// its documentation for any purpose is hereby granted without fee, provided
// that (i) the above copyright notices and this permission notice appear in
// all copies of the software and related documentation, and (ii) the names of
// Sam Leffler and Silicon Graphics may not be used in any advertising or
// publicity relating to the software without the specific, prior written
// permission of Sam Leffler and Silicon Graphics.
//
// THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
// EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
// WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
//
// IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
// ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
// OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
// LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
// OF THIS SOFTWARE.
// TIFF Library.
// Rev 5.0 Lempel-Ziv & Welch Compression Support
//
// This code is derived from the compress program whose code is
// derived from software contributed to Berkeley by James A. Woods,
// derived from original work by Spencer Thomas and Joseph Orost.
//
// The original Berkeley copyright notice appears below in its entirety.
#define LZW_COMPAT // include backwards compatibility code
// Each strip of data is supposed to be terminated by a CODE_EOI.
// If the following #define is included, the decoder will also
// check for end-of-strip w/o seeing this code. This makes the
// library more robust, but also slower.
#define LZW_CHECKEOS // include checks for strips w/o EOI code
using System;
using System.Collections.Generic;
using System.Text;
namespace Free.Ports.LibTiff
{
public static partial class libtiff
{
// NB: The 5.0 spec describes a different algorithm than Aldus
// implements. Specifically, Aldus does code length transitions
// one code earlier than should be done (for real LZW).
// Earlier versions of this library implemented the correct
// LZW algorithm, but emitted codes in a bit order opposite
// to the TIFF spec. Thus, to maintain compatibility w/ Aldus
// we interpret MSB-LSB ordered codes to be images written w/
// old versions of this library, but otherwise adhere to the
// Aldus "off by one" algorithm.
//
// Future revisions to the TIFF spec are expected to "clarify this issue".
static int MAXCODE(int n) { return (1<<n)-1; }
// The TIFF spec specifies that encoded bit
// strings range from 9 to 12 bits.
const int BITS_MIN=9; // start with 9 bits
const int BITS_MAX=12; // max of 12 bit strings
// predefined codes
const int CODE_CLEAR=256; // code to clear string table
const int CODE_EOI=257; // end-of-information code
const int CODE_FIRST=258; // first free code entry
const int CODE_MAX=(1<<BITS_MAX)-1;
const int HSIZE=9001; // 91% occupancy
const int HSHIFT=13-8;
#if LZW_COMPAT
// NB: +1024 is for compatibility with old files
const int CSIZE=CODE_MAX+1024;
#else
const int CSIZE=CODE_MAX+1;
#endif
// State block for each open TIFF file using LZW
// compression/decompression. Note that the predictor
// state block must be first in this data structure.
class LZWBaseState : TIFFPredictorState
{
internal ushort nbits; // # of bits/code
internal ushort maxcode; // maximum code for lzw_nbits
internal ushort free_ent; // next free entry in hash table
internal int nextdata; // next bits of i/o
internal int nextbits; // # of valid bits in lzw_nextdata
internal O rw_mode; // preserve rw_mode from init
}
class hash_t
{
internal int hash;
internal ushort code;
}
// Decoding-specific state.
class code_t
{
internal int next;
internal ushort length; // string len, including this token
internal byte value; // data value
internal byte firstchar; // first token of string
}
delegate bool decodeFunc(TIFF tif, byte[] buf, int cc, ushort s);
class LZWCodecState : LZWBaseState
{
internal const int CHECK_GAP=10000; // enc_ratio check interval
// Decoding specific data
internal int dec_nbitsmask; // lzw_nbits 1 bits, right adjusted
internal int dec_restart; // restart count
#if LZW_CHECKEOS
internal int dec_bitsleft; // available bits in raw data
#endif
internal decodeFunc dec_decode; // regular or backwards compatible
internal int dec_codep; // current recognized code
internal int dec_oldcodep; // previously recognized code
internal int dec_free_entp; // next free entry
internal int dec_maxcodep; // max available entry
internal code_t[] dec_codetab; // kept separate for small machines
// Encoding specific data
internal int enc_oldcode; // last code encountered
internal int enc_checkpoint; // point at which to clear table
internal int enc_ratio; // current compression ratio
internal int enc_incount; // (input) data bytes encoded
internal int enc_outcount; // encoded (output) bytes
internal uint enc_rawlimit; // bound on tif_rawdata buffer
internal hash_t[] enc_hashtab; // kept separate for small machines
}
// LZW Decoder.
static bool LZWSetupDecode(TIFF tif)
{
LZWCodecState sp=tif.tif_data as LZWCodecState;
string module=" LZWSetupDecode";
if(sp==null)
{
// Allocate state block so tag methods have storage to record
// values.
try
{
tif.tif_data=sp=new LZWCodecState();
}
catch
{
TIFFErrorExt(tif.tif_clientdata, "LZWPreDecode", "No space for LZW state block");
return false;
}
sp.dec_codetab=null;
sp.dec_decode=null;
// Setup predictor setup.
TIFFPredictorInit(tif);
sp=tif.tif_data as LZWCodecState;
}
#if DEBUG
if(sp==null) throw new Exception("sp==null");
#endif
if(sp.dec_codetab==null)
{
try
{
sp.dec_codetab=new code_t[CSIZE];
for(int i=0; i<CSIZE; i++)
{
sp.dec_codetab[i]=new code_t();
sp.dec_codetab[i].next=-1;
}
}
catch
{
TIFFErrorExt(tif.tif_clientdata, module, "No space for LZW code table");
return false;
}
// Pre-load the table.
byte code=255;
do
{
sp.dec_codetab[code].value=code;
sp.dec_codetab[code].firstchar=code;
sp.dec_codetab[code].length=1;
sp.dec_codetab[code].next=-1;
} while((code--)!=0);
// Zero-out the unused entries
for(int i=CODE_CLEAR; i<CODE_FIRST; i++)
{
sp.dec_codetab[i].next=0;
sp.dec_codetab[i].length=0;
sp.dec_codetab[i].value=0;
sp.dec_codetab[i].firstchar=0;
}
}
return true;
}
// Setup state for decoding a strip.
static bool LZWPreDecode(TIFF tif, ushort sampleNumber)
{
LZWCodecState sp=tif.tif_data as LZWCodecState;
#if DEBUG
if(sp==null) throw new Exception("sp==null");
#endif
if(sp.dec_codetab==null)
{
tif.tif_setupdecode(tif);
}
// Check for old bit-reversed codes.
if(tif.tif_rawdata[0]==0&&(tif.tif_rawdata[1]&0x1)!=0)
{
#if LZW_COMPAT
if(sp.dec_decode==null)
{
TIFFWarningExt(tif.tif_clientdata, tif.tif_name, "Old-style LZW codes, convert file");
// Override default decoding methods with
// ones that deal with the old coding.
// Otherwise the predictor versions set
// above will call the compatibility routines
// through the dec_decode method.
tif.tif_decoderow=LZWDecodeCompat;
tif.tif_decodestrip=LZWDecodeCompat;
tif.tif_decodetile=LZWDecodeCompat;
// If doing horizontal differencing, must
// re-setup the predictor logic since we
// switched the basic decoder methods...
tif.tif_setupdecode(tif);
sp.dec_decode=LZWDecodeCompat;
}
sp.maxcode=(ushort)MAXCODE(BITS_MIN);
#else // !LZW_COMPAT
if(sp.dec_decode==null)
{
TIFFErrorExt(tif.tif_clientdata, tif.tif_name, "Old-style LZW codes not supported");
sp.dec_decode=LZWDecode;
}
return false;
#endif // !LZW_COMPAT
}
else
{
sp.maxcode=(ushort)(MAXCODE(BITS_MIN)-1);
sp.dec_decode=LZWDecode;
}
sp.nbits=BITS_MIN;
sp.nextbits=0;
sp.nextdata=0;
sp.dec_restart=0;
sp.dec_nbitsmask=MAXCODE(BITS_MIN);
#if LZW_CHECKEOS
sp.dec_bitsleft=(int)(tif.tif_rawcc<<3);
#endif
sp.dec_free_entp=CODE_FIRST;
// Zero entries that are not yet filled in. We do
// this to guard against bogus input data that causes
// us to index into undefined entries. If you can
// come up with a way to safely bounds-check input codes
// while decoding then you can remove this operation.
for(int i=sp.dec_free_entp; i<CSIZE; i++)
{
sp.dec_codetab[i].firstchar=0;
sp.dec_codetab[i].length=0;
sp.dec_codetab[i].value=0;
sp.dec_codetab[i].next=-1;
}
sp.dec_oldcodep=-1;
sp.dec_maxcodep=sp.dec_nbitsmask-1;
return true;
}
// Decode a "hunk of data".
static void codeLoop(TIFF tif, string module)
{
TIFFErrorExt(tif.tif_clientdata, module, "LZWDecode: Bogus encoding, loop in the code table; scanline {0}", tif.tif_row);
}
static bool LZWDecode(TIFF tif, byte[] op0, int occ0, ushort s)
{
string module="LZWDecode";
LZWCodecState sp=tif.tif_data as LZWCodecState;
#if DEBUG
if(sp==null) throw new Exception("sp==null");
if(sp.dec_codetab==null) throw new Exception("sp.dec_codetab==null");
#endif
unsafe
{
fixed(byte* op_=op0)
{
byte* op=op_;
int occ=occ0;
byte* tp;
int codep;
// Restart interrupted output operation.
if(sp.dec_restart!=0)
{
int residue;
codep=sp.dec_codep;
residue=sp.dec_codetab[codep].length-sp.dec_restart;
if(residue>occ)
{
// Residue from previous decode is sufficient
// to satisfy decode request. Skip to the
// start of the decoded string, place decoded
// values in the output buffer, and return.
sp.dec_restart+=occ;
do
{
codep=sp.dec_codetab[codep].next;
residue--;
} while(residue>occ&&codep!=-1);
if(codep!=-1)
{
tp=op+occ;
do
{
tp--;
*tp=sp.dec_codetab[codep].value;
codep=sp.dec_codetab[codep].next;
occ--;
} while(occ!=0&&codep!=-1);
}
return true;
}
// Residue satisfies only part of the decode request.
op+=residue;
occ-=residue;
tp=op;
do
{
tp--;
*tp=sp.dec_codetab[codep].value;
codep=sp.dec_codetab[codep].next;
residue--;
} while(residue!=0&&codep!=-1);
sp.dec_restart=0;
}
ushort code;
uint bp=tif.tif_rawcp;
int nbits=sp.nbits;
int nextdata=sp.nextdata;
int nextbits=sp.nextbits;
int nbitsmask=sp.dec_nbitsmask;
int oldcodep=sp.dec_oldcodep;
int free_entp=sp.dec_free_entp;
int maxcodep=sp.dec_maxcodep;
while(occ>0)
{
#if LZW_CHECKEOS
// This check shouldn't be necessary because each
// strip is suppose to be terminated with CODE_EOI.
if(sp.dec_bitsleft<nbits)
{
TIFFWarningExt(tif.tif_clientdata, module, "Strip {0} not terminated with EOI code", tif.tif_curstrip);
code=CODE_EOI;
}
else
{
nextdata=(nextdata<<8)|tif.tif_rawdata[bp++];
nextbits+=8;
if(nextbits<nbits)
{
nextdata=(nextdata<<8)|tif.tif_rawdata[bp++];
nextbits+=8;
}
code=(ushort)((nextdata>>(nextbits-nbits))&nbitsmask);
nextbits-=nbits;
sp.dec_bitsleft-=nbits;
}
#else
nextdata=(nextdata<<8)|tif.tif_rawdata[bp++];
nextbits+=8;
if(nextbits<nbits)
{
nextdata=(nextdata<<8)|tif.tif_rawdata[bp++];
nextbits+=8;
}
code=(ushort)((nextdata>>(nextbits-nbits))&nbitsmask);
nextbits-=nbits;
#endif
if(code==CODE_EOI) break;
if(code==CODE_CLEAR)
{
free_entp=CODE_FIRST;
for(int i=CODE_FIRST; i<CSIZE; i++)
{
sp.dec_codetab[i].next=0;
sp.dec_codetab[i].length=0;
sp.dec_codetab[i].value=0;
sp.dec_codetab[i].firstchar=0;
}
nbits=BITS_MIN;
nbitsmask=MAXCODE(BITS_MIN);
maxcodep=nbitsmask-1;
#if LZW_CHECKEOS
// This check shouldn't be necessary because each
// strip is suppose to be terminated with CODE_EOI.
if(sp.dec_bitsleft<nbits)
{
TIFFWarningExt(tif.tif_clientdata, module, "Strip {0} not terminated with EOI code", tif.tif_curstrip);
code=CODE_EOI;
}
else
{
nextdata=(nextdata<<8)|tif.tif_rawdata[bp++];
nextbits+=8;
if(nextbits<nbits)
{
nextdata=(nextdata<<8)|tif.tif_rawdata[bp++];
nextbits+=8;
}
code=(ushort)((nextdata>>(nextbits-nbits))&nbitsmask);
nextbits-=nbits;
sp.dec_bitsleft-=nbits;
}
#else
nextdata=(nextdata<<8)|tif.tif_rawdata[bp++];
nextbits+=8;
if(nextbits<nbits)
{
nextdata=(nextdata<<8)|tif.tif_rawdata[bp++];
nextbits+=8;
}
code=(ushort)((nextdata>>(nextbits-nbits))&nbitsmask);
nextbits-=nbits;
#endif
if(code==CODE_EOI) break;
if(code==CODE_CLEAR)
{
TIFFErrorExt(tif.tif_clientdata, tif.tif_name, "LZWDecode: Corrupted LZW table at scanline {0}", tif.tif_row);
return false;
}
*op++=(byte)code;
occ--;
oldcodep=code;
continue;
}
codep=code;
// Add the new entry to the code table.
if(free_entp<0||free_entp>=CSIZE)
{
TIFFErrorExt(tif.tif_clientdata, module, "Corrupted LZW table at scanline {0}", tif.tif_row);
return false;
}
sp.dec_codetab[free_entp].next=oldcodep;
if(oldcodep<0||oldcodep>=CSIZE)
{
TIFFErrorExt(tif.tif_clientdata, module, "Corrupted LZW table at scanline {0}", tif.tif_row);
return false;
}
sp.dec_codetab[free_entp].firstchar=sp.dec_codetab[oldcodep].firstchar;
sp.dec_codetab[free_entp].length=(ushort)(sp.dec_codetab[oldcodep].length+1);
sp.dec_codetab[free_entp].value=(codep<free_entp)?sp.dec_codetab[codep].firstchar:sp.dec_codetab[free_entp].firstchar;
free_entp++;
if(free_entp>maxcodep)
{
nbits++;
if(nbits>BITS_MAX) nbits=BITS_MAX; // should not happen
nbitsmask=MAXCODE(nbits);
maxcodep=nbitsmask-1;
}
oldcodep=codep;
if(code>=256)
{
// Code maps to a string, copy string
// value to output (written in reverse).
if(sp.dec_codetab[codep].length==0)
{
TIFFErrorExt(tif.tif_clientdata, module, "Wrong length of decoded string: data probably corrupted at scanline {0}", tif.tif_row);
return false;
}
if(sp.dec_codetab[codep].length>occ)
{
// String is too long for decode buffer,
// locate portion that will fit, copy to
// the decode buffer, and setup restart
// logic for the next decoding call.
sp.dec_codep=codep;
do
{
codep=sp.dec_codetab[codep].next;
} while(codep!=-1&&sp.dec_codetab[codep].length>occ);
if(codep!=-1)
{
sp.dec_restart=occ;
tp=op+occ;
do
{
tp--;
*tp=sp.dec_codetab[codep].value;
codep=sp.dec_codetab[codep].next;
occ--;
} while(occ!=0&&codep!=-1);
if(codep!=-1) codeLoop(tif, module);
}
break;
}
int len=sp.dec_codetab[codep].length;
tp=op+len;
do
{
tp--;
*tp=sp.dec_codetab[codep].value;
codep=sp.dec_codetab[codep].next;
} while(codep!=-1&&tp>op);
if(codep!=-1)
{
codeLoop(tif, module);
break;
}
#if DEBUG
if(occ<len) throw new Exception("occ<len");
#endif
op+=len;
occ-=len;
}
else
{
*op++=(byte)code; occ--;
}
}
tif.tif_rawcp=bp;
sp.nbits=(ushort)nbits;
sp.nextdata=nextdata;
sp.nextbits=nextbits;
sp.dec_nbitsmask=nbitsmask;
sp.dec_oldcodep=oldcodep;
sp.dec_free_entp=free_entp;
sp.dec_maxcodep=maxcodep;
if(occ>0)
{
TIFFErrorExt(tif.tif_clientdata, module, "Not enough data at scanline {0} (short {1} bytes)", tif.tif_row, occ);
return false;
}
}
}
return true;
}
#if LZW_COMPAT
// Decode a "hunk of data" for old images.
static bool LZWDecodeCompat(TIFF tif, byte[] op0, int occ0, ushort s)
{
string module="LZWDecodeCompat";
LZWCodecState sp=tif.tif_data as LZWCodecState;
#if DEBUG
if(sp==null) throw new Exception("sp==null");
#endif
unsafe
{
fixed(byte* op_=op0)
{
byte* op=op_;
int occ=occ0;
byte* tp;
int codep;
// Restart interrupted output operation.
if(sp.dec_restart!=0)
{
int residue;
codep=sp.dec_codep;
residue=sp.dec_codetab[codep].length-sp.dec_restart;
if(residue>occ)
{
// Residue from previous decode is sufficient
// to satisfy decode request. Skip to the
// start of the decoded string, place decoded
// values in the output buffer, and return.
sp.dec_restart+=occ;
do
{
codep=sp.dec_codetab[codep].next;
residue--;
} while(residue>occ);
tp=op+occ;
do
{
tp--;
*tp=sp.dec_codetab[codep].value;
codep=sp.dec_codetab[codep].next;
occ--;
} while(occ!=0);
return true;
}
// Residue satisfies only part of the decode request.
op+=residue;
occ-=residue;
tp=op;
do
{
tp--;
*tp=sp.dec_codetab[codep].value;
codep=sp.dec_codetab[codep].next;
residue--;
} while(residue!=0);
sp.dec_restart=0;
}
uint bp=tif.tif_rawcp;
int nbits=sp.nbits;
int nextdata=sp.nextdata;
int nextbits=sp.nextbits;
int nbitsmask=sp.dec_nbitsmask;
int oldcodep=sp.dec_oldcodep;
int free_entp=sp.dec_free_entp;
int maxcodep=sp.dec_maxcodep;
int code;
while(occ>0)
{
#if LZW_CHECKEOS
// This check shouldn't be necessary because each
// strip is suppose to be terminated with CODE_EOI.
if(sp.dec_bitsleft<nbits)
{
TIFFWarningExt(tif.tif_clientdata, module, "Strip {0} not terminated with EOI code", tif.tif_curstrip);
code=CODE_EOI;
}
else
{
nextdata|=(int)(((uint)tif.tif_rawdata[bp++])<<nextbits);
nextbits+=8;
if(nextbits<nbits)
{
nextdata|=(int)(((uint)tif.tif_rawdata[bp++])<<nextbits);
nextbits+=8;
}
code=(ushort)(nextdata&nbitsmask);
nextdata>>=nbits;
nextbits-=nbits;
sp.dec_bitsleft-=nbits;
}
#else
nextdata|=(int)(((uint)tif.tif_rawdata[bp++])<<nextbits);
nextbits+=8;
if(nextbits<nbits)
{
nextdata|=(int)(((uint)tif.tif_rawdata[bp++])<<nextbits);
nextbits+=8;
}
code=(ushort)(nextdata&nbitsmask);
nextdata>>=nbits;
nextbits-=nbits;
#endif
if(code==CODE_EOI) break;
if(code==CODE_CLEAR)
{
free_entp=CODE_FIRST;
for(int i=CODE_FIRST; i<CSIZE; i++)
{
sp.dec_codetab[i].next=0;
sp.dec_codetab[i].length=0;
sp.dec_codetab[i].value=0;
sp.dec_codetab[i].firstchar=0;
}
nbits=BITS_MIN;
nbitsmask=MAXCODE(BITS_MIN);
maxcodep=nbitsmask;
#if LZW_CHECKEOS
// This check shouldn't be necessary because each
// strip is suppose to be terminated with CODE_EOI.
if(sp.dec_bitsleft<nbits)
{
TIFFWarningExt(tif.tif_clientdata, module, "Strip {0} not terminated with EOI code", tif.tif_curstrip);
code=CODE_EOI;
}
else
{
nextdata|=(int)(((uint)tif.tif_rawdata[bp++])<<nextbits);
nextbits+=8;
if(nextbits<nbits)
{
nextdata|=(int)(((uint)tif.tif_rawdata[bp++])<<nextbits);
nextbits+=8;
}
code=(ushort)(nextdata&nbitsmask);
nextdata>>=nbits;
nextbits-=nbits;
sp.dec_bitsleft-=nbits;
}
#else
nextdata|=(int)(((uint)tif.tif_rawdata[bp++])<<nextbits);
nextbits+=8;
if(nextbits<nbits)
{
nextdata|=(int)(((uint)tif.tif_rawdata[bp++])<<nextbits);
nextbits+=8;
}
code=(ushort)(nextdata&nbitsmask);
nextdata>>=nbits;
nextbits-=nbits;
#endif
if(code==CODE_EOI) break;
if(code==CODE_CLEAR)
{
TIFFErrorExt(tif.tif_clientdata, tif.tif_name, "LZWDecode: Corrupted LZW table at scanline {0}", tif.tif_row);
return false;
}
*op++=(byte)code;
occ--;
oldcodep=code;
continue;
}
codep=code;
// Add the new entry to the code table.
if(free_entp<0||free_entp>=CSIZE)
{
TIFFErrorExt(tif.tif_clientdata, module, "Corrupted LZW table at scanline {0}", tif.tif_row);
return false;
}
sp.dec_codetab[free_entp].next=oldcodep;
if(oldcodep<0||oldcodep>=CSIZE)
{
TIFFErrorExt(tif.tif_clientdata, module, "Corrupted LZW table at scanline {0}", tif.tif_row);
return false;
}
sp.dec_codetab[free_entp].firstchar=sp.dec_codetab[oldcodep].firstchar;
sp.dec_codetab[free_entp].length=(ushort)(sp.dec_codetab[oldcodep].length+1);
sp.dec_codetab[free_entp].value=(codep<free_entp)?sp.dec_codetab[codep].firstchar:sp.dec_codetab[free_entp].firstchar;
free_entp++;
if(free_entp>maxcodep)
{
nbits++;
if(nbits>BITS_MAX) nbits=BITS_MAX; // should not happen
nbitsmask=MAXCODE(nbits);
maxcodep=nbitsmask;
}
oldcodep=codep;
if(code>=256)
{
byte* op_orig=op;
// Code maps to a string, copy string
// value to output (written in reverse).
if(sp.dec_codetab[codep].length==0)
{
TIFFErrorExt(tif.tif_clientdata, module, "Wrong length of decoded string: data probably corrupted at scanline {0}", tif.tif_row);
return false;
}
if(sp.dec_codetab[codep].length>occ)
{
// String is too long for decode buffer,
// locate portion that will fit, copy to
// the decode buffer, and setup restart
// logic for the next decoding call.
sp.dec_codep=codep;
do
{
codep=sp.dec_codetab[codep].next;
} while(sp.dec_codetab[codep].length>occ);
sp.dec_restart=occ;
tp=op+occ;
do
{
tp--;
*tp=sp.dec_codetab[codep].value;
codep=sp.dec_codetab[codep].next;
occ--;
} while(occ!=0);
break;
}
#if DEBUG
if(occ<sp.dec_codetab[codep].length) throw new Exception("occ<sp.dec_codetab[codep].length");
#endif
op+=sp.dec_codetab[codep].length; occ-=sp.dec_codetab[codep].length;
tp=op;
do
{
tp--;
*tp=sp.dec_codetab[codep].value;
codep=sp.dec_codetab[codep].next;
} while((codep!=-1)&&(tp>op_orig));
}
else
{
*op++=(byte)code; occ--;
}
}
tif.tif_rawcp=bp;
sp.nbits=(ushort)nbits;
sp.nextdata=nextdata;
sp.nextbits=nextbits;
sp.dec_nbitsmask=nbitsmask;
sp.dec_oldcodep=oldcodep;
sp.dec_free_entp=free_entp;
sp.dec_maxcodep=maxcodep;
if(occ>0)
{
TIFFErrorExt(tif.tif_clientdata, module, "Not enough data at scanline {0} (short {1} bytes)", tif.tif_row, occ);
return false;
}
}
}
return true;
}
#endif // LZW_COMPAT
// LZW Encoding.
static bool LZWSetupEncode(TIFF tif)
{
LZWCodecState sp=tif.tif_data as LZWCodecState;
string module="LZWSetupEncode";
#if DEBUG
if(sp==null) throw new Exception("sp=null");
#endif
try
{
sp.enc_hashtab=new hash_t[HSIZE];
for(int i=0; i<HSIZE; i++) sp.enc_hashtab[i]=new hash_t();
}
catch
{
TIFFErrorExt(tif.tif_clientdata, module, "No space for LZW hash table");
return false;
}
return true;
}
// Reset encoding state at the start of a strip.
static bool LZWPreEncode(TIFF tif, ushort sampleNumber)
{
LZWCodecState sp=tif.tif_data as LZWCodecState;
#if DEBUG
if(sp==null) throw new Exception("sp=null");
#endif
if(sp.enc_hashtab==null)
{
tif.tif_setupencode(tif);
}
sp.nbits=BITS_MIN;
sp.maxcode=(ushort)MAXCODE(BITS_MIN);
sp.free_ent=CODE_FIRST;
sp.nextbits=0;
sp.nextdata=0;
sp.enc_checkpoint=LZWCodecState.CHECK_GAP;
sp.enc_ratio=0;
sp.enc_incount=0;
sp.enc_outcount=0;
// The 4 here insures there is space for 2 max-sized
// codes in LZWEncode and LZWPostDecode.
sp.enc_rawlimit=tif.tif_rawdatasize-1-4;
cl_hash(sp); // clear hash table
sp.enc_oldcode=-1; // generates CODE_CLEAR in LZWEncode
return true;
}
// Encode a chunk of pixels.
//
// Uses an open addressing double hashing (no chaining) on the
// prefix code/next character combination. We do a variant of
// Knuth's algorithm D (vol. 3, sec. 6.4) along with G. Knott's
// relatively-prime secondary probe. Here, the modular division
// first probe is gives way to a faster exclusive-or manipulation.
// Also do block compression with an adaptive reset, whereby the
// code table is cleared when the compression ratio decreases,
// but after the table fills The variable-length output codes
// are re-sized at this point, and a CODE_CLEAR is generated
// for the decoder.
static bool LZWEncode(TIFF tif, byte[] buf, int cc, ushort s)
{
LZWCodecState sp=tif.tif_data as LZWCodecState;
if(sp==null) return false;
#if DEBUG
if(sp.enc_hashtab==null) throw new Exception("sp.enc_hashtab==null");
#endif
unsafe
{
fixed(byte* bp_=buf)
{
byte* bp=bp_;
// Load local state.
int incount=sp.enc_incount;
int outcount=sp.enc_outcount;
int checkpoint=sp.enc_checkpoint;
int nextdata=sp.nextdata;
int nextbits=sp.nextbits;
int free_ent=sp.free_ent;
int maxcode=sp.maxcode;
int nbits=sp.nbits;
uint op=tif.tif_rawcp;
uint limit=sp.enc_rawlimit;
int ent=sp.enc_oldcode;
if(ent==-1&&cc>0)
{
// NB: This is safe because it can only happen
// at the start of a strip where we know there
// is space in the data buffer.
nextdata=(nextdata<<nbits)|CODE_CLEAR;
nextbits+=nbits;
tif.tif_rawdata[op++]=(byte)(nextdata>>(nextbits-8));
nextbits-=8;
if(nextbits>=8)
{
tif.tif_rawdata[op++]=(byte)(nextdata>>(nextbits-8));
nextbits-=8;
}
outcount+=nbits;
ent=*bp++;
cc--;
incount++;
}
int disp;
while(cc>0)
{
int c=*bp++; cc--; incount++;