001/*
002 * $RCSfile: TIFFFaxDecompressor.java,v $
003 *
004 * 
005 * Copyright (c) 2005 Sun Microsystems, Inc. All  Rights Reserved.
006 * 
007 * Redistribution and use in source and binary forms, with or without
008 * modification, are permitted provided that the following conditions
009 * are met: 
010 * 
011 * - Redistribution of source code must retain the above copyright 
012 *   notice, this  list of conditions and the following disclaimer.
013 * 
014 * - Redistribution in binary form must reproduce the above copyright
015 *   notice, this list of conditions and the following disclaimer in 
016 *   the documentation and/or other materials provided with the
017 *   distribution.
018 * 
019 * Neither the name of Sun Microsystems, Inc. or the names of 
020 * contributors may be used to endorse or promote products derived 
021 * from this software without specific prior written permission.
022 * 
023 * This software is provided "AS IS," without a warranty of any 
024 * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND 
025 * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, 
026 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
027 * EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL 
028 * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF 
029 * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
030 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR 
031 * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
032 * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
033 * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
034 * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
035 * POSSIBILITY OF SUCH DAMAGES. 
036 * 
037 * You acknowledge that this software is not designed or intended for 
038 * use in the design, construction, operation or maintenance of any 
039 * nuclear facility. 
040 *
041 * $Revision: 1.15 $
042 * $Date: 2007/08/31 23:17:28 $
043 * $State: Exp $
044 */
045package com.github.jaiimageio.impl.plugins.tiff;
046
047import java.awt.image.DataBuffer;
048import java.awt.image.DataBufferByte;
049import java.awt.image.BufferedImage;
050import java.awt.image.WritableRaster;
051import java.io.ByteArrayOutputStream;
052import java.io.IOException;
053import java.io.EOFException;
054import java.io.PrintStream;
055
056import javax.imageio.IIOException;
057import javax.imageio.ImageTypeSpecifier;
058
059import com.github.jaiimageio.plugins.tiff.BaselineTIFFTagSet;
060import com.github.jaiimageio.plugins.tiff.TIFFDecompressor;
061import com.github.jaiimageio.plugins.tiff.TIFFField;
062
063public class TIFFFaxDecompressor extends TIFFDecompressor {
064
065    /**
066     * The logical order of bits within a byte.
067     * <pre>
068     * 1 = MSB-to-LSB
069     * 2 = LSB-to-MSB (flipped)
070     * </pre>
071     */
072    protected int fillOrder;
073    protected int compression;
074    private int t4Options;
075    private int t6Options;
076
077    // Variables set by T4Options
078    /**
079     * Uncompressed mode flag: 1 if uncompressed, 0 if not.
080     */
081    protected int uncompressedMode = 0;
082
083    /**
084     * EOL padding flag: 1 if fill bits have been added before an EOL such
085     * that the EOL ends on a byte boundary, 0 otherwise.
086     */
087    protected int fillBits = 0;
088
089    /**
090     * Coding dimensionality: 1 for 2-dimensional, 0 for 1-dimensional.
091     */
092    protected int oneD;
093
094    private byte[] data;
095    private int bitPointer, bytePointer;
096
097    // Output image buffer
098    private byte[] buffer;
099    private int w, h, bitsPerScanline;
100    private int lineBitNum;
101
102    // Data structures needed to store changing elements for the previous
103    // and the current scanline
104    private int changingElemSize = 0;
105    private int prevChangingElems[];
106    private int currChangingElems[];
107
108    // Element at which to start search in getNextChangingElement
109    private int lastChangingElement = 0;
110
111    static int table1[] = {
112        0x00, // 0 bits are left in first byte - SHOULD NOT HAPPEN
113        0x01, // 1 bits are left in first byte
114        0x03, // 2 bits are left in first byte
115        0x07, // 3 bits are left in first byte
116        0x0f, // 4 bits are left in first byte
117        0x1f, // 5 bits are left in first byte
118        0x3f, // 6 bits are left in first byte
119        0x7f, // 7 bits are left in first byte
120        0xff  // 8 bits are left in first byte
121    };
122    
123    static int table2[] = {
124        0x00, // 0
125        0x80, // 1
126        0xc0, // 2
127        0xe0, // 3
128        0xf0, // 4
129        0xf8, // 5
130        0xfc, // 6
131        0xfe, // 7
132        0xff  // 8
133    };
134
135    // Table to be used when fillOrder = 2, for flipping bytes.
136    static byte flipTable[] = {
137         0,  -128,    64,   -64,    32,   -96,    96,   -32, 
138        16,  -112,    80,   -48,    48,   -80,   112,   -16, 
139         8,  -120,    72,   -56,    40,   -88,   104,   -24, 
140        24,  -104,    88,   -40,    56,   -72,   120,    -8, 
141         4,  -124,    68,   -60,    36,   -92,   100,   -28, 
142        20,  -108,    84,   -44,    52,   -76,   116,   -12, 
143        12,  -116,    76,   -52,    44,   -84,   108,   -20, 
144        28,  -100,    92,   -36,    60,   -68,   124,    -4, 
145         2,  -126,    66,   -62,    34,   -94,    98,   -30, 
146        18,  -110,    82,   -46,    50,   -78,   114,   -14, 
147        10,  -118,    74,   -54,    42,   -86,   106,   -22, 
148        26,  -102,    90,   -38,    58,   -70,   122,    -6, 
149         6,  -122,    70,   -58,    38,   -90,   102,   -26, 
150        22,  -106,    86,   -42,    54,   -74,   118,   -10, 
151        14,  -114,    78,   -50,    46,   -82,   110,   -18, 
152        30,   -98,    94,   -34,    62,   -66,   126,    -2, 
153         1,  -127,    65,   -63,    33,   -95,    97,   -31, 
154        17,  -111,    81,   -47,    49,   -79,   113,   -15, 
155         9,  -119,    73,   -55,    41,   -87,   105,   -23, 
156        25,  -103,    89,   -39,    57,   -71,   121,    -7, 
157         5,  -123,    69,   -59,    37,   -91,   101,   -27, 
158        21,  -107,    85,   -43,    53,   -75,   117,   -11, 
159        13,  -115,    77,   -51,    45,   -83,   109,   -19, 
160        29,   -99,    93,   -35,    61,   -67,   125,    -3, 
161         3,  -125,    67,   -61,    35,   -93,    99,   -29, 
162        19,  -109,    83,   -45,    51,   -77,   115,   -13, 
163        11,  -117,    75,   -53,    43,   -85,   107,   -21, 
164        27,  -101,    91,   -37,    59,   -69,   123,    -5, 
165         7,  -121,    71,   -57,    39,   -89,   103,   -25, 
166        23,  -105,    87,   -41,    55,   -73,   119,    -9, 
167        15,  -113,    79,   -49,    47,   -81,   111,   -17, 
168        31,   -97,    95,   -33,    63,   -65,   127,    -1, 
169    };
170    
171    // The main 10 bit white runs lookup table
172    static short white[] = {
173        // 0 - 7
174        6430,   6400,   6400,   6400,   3225,   3225,   3225,   3225, 
175        // 8 - 15
176        944,    944,    944,    944,    976,    976,    976,    976, 
177        // 16 - 23
178        1456,   1456,   1456,   1456,   1488,   1488,   1488,   1488, 
179        // 24 - 31
180        718,    718,    718,    718,    718,    718,    718,    718, 
181        // 32 - 39
182        750,    750,    750,    750,    750,    750,    750,    750, 
183        // 40 - 47
184        1520,   1520,   1520,   1520,   1552,   1552,   1552,   1552, 
185        // 48 - 55
186        428,    428,    428,    428,    428,    428,    428,    428, 
187        // 56 - 63
188        428,    428,    428,    428,    428,    428,    428,    428, 
189        // 64 - 71
190        654,    654,    654,    654,    654,    654,    654,    654, 
191        // 72 - 79
192        1072,   1072,   1072,   1072,   1104,   1104,   1104,   1104, 
193        // 80 - 87
194        1136,   1136,   1136,   1136,   1168,   1168,   1168,   1168, 
195        // 88 - 95
196        1200,   1200,   1200,   1200,   1232,   1232,   1232,   1232, 
197        // 96 - 103
198        622,    622,    622,    622,    622,    622,    622,    622, 
199        // 104 - 111
200        1008,   1008,   1008,   1008,   1040,   1040,   1040,   1040, 
201        // 112 - 119
202        44,     44,     44,     44,     44,     44,     44,     44, 
203        // 120 - 127
204        44,     44,     44,     44,     44,     44,     44,     44, 
205        // 128 - 135
206        396,    396,    396,    396,    396,    396,    396,    396, 
207        // 136 - 143
208        396,    396,    396,    396,    396,    396,    396,    396, 
209        // 144 - 151
210        1712,   1712,   1712,   1712,   1744,   1744,   1744,   1744, 
211        // 152 - 159
212        846,    846,    846,    846,    846,    846,    846,    846, 
213        // 160 - 167
214        1264,   1264,   1264,   1264,   1296,   1296,   1296,   1296, 
215        // 168 - 175
216        1328,   1328,   1328,   1328,   1360,   1360,   1360,   1360, 
217        // 176 - 183
218        1392,   1392,   1392,   1392,   1424,   1424,   1424,   1424, 
219        // 184 - 191
220        686,    686,    686,    686,    686,    686,    686,    686, 
221        // 192 - 199
222        910,    910,    910,    910,    910,    910,    910,    910, 
223        // 200 - 207
224        1968,   1968,   1968,   1968,   2000,   2000,   2000,   2000, 
225        // 208 - 215
226        2032,   2032,   2032,   2032,     16,     16,     16,     16, 
227        // 216 - 223
228        10257,  10257,  10257,  10257,  12305,  12305,  12305,  12305, 
229        // 224 - 231
230        330,    330,    330,    330,    330,    330,    330,    330, 
231        // 232 - 239
232        330,    330,    330,    330,    330,    330,    330,    330, 
233        // 240 - 247
234        330,    330,    330,    330,    330,    330,    330,    330, 
235        // 248 - 255
236        330,    330,    330,    330,    330,    330,    330,    330, 
237        // 256 - 263
238        362,    362,    362,    362,    362,    362,    362,    362, 
239        // 264 - 271
240        362,    362,    362,    362,    362,    362,    362,    362, 
241        // 272 - 279
242        362,    362,    362,    362,    362,    362,    362,    362, 
243        // 280 - 287
244        362,    362,    362,    362,    362,    362,    362,    362, 
245        // 288 - 295
246        878,    878,    878,    878,    878,    878,    878,    878, 
247        // 296 - 303
248        1904,   1904,   1904,   1904,   1936,   1936,   1936,   1936, 
249        // 304 - 311
250        -18413, -18413, -16365, -16365, -14317, -14317, -10221, -10221, 
251        // 312 - 319
252        590,    590,    590,    590,    590,    590,    590,    590, 
253        // 320 - 327
254        782,    782,    782,    782,    782,    782,    782,    782, 
255        // 328 - 335
256        1584,   1584,   1584,   1584,   1616,   1616,   1616,   1616, 
257        // 336 - 343
258        1648,   1648,   1648,   1648,   1680,   1680,   1680,   1680, 
259        // 344 - 351
260        814,    814,    814,    814,    814,    814,    814,    814, 
261        // 352 - 359
262        1776,   1776,   1776,   1776,   1808,   1808,   1808,   1808, 
263        // 360 - 367
264        1840,   1840,   1840,   1840,   1872,   1872,   1872,   1872, 
265        // 368 - 375
266        6157,   6157,   6157,   6157,   6157,   6157,   6157,   6157, 
267        // 376 - 383
268        6157,   6157,   6157,   6157,   6157,   6157,   6157,   6157, 
269        // 384 - 391
270        -12275, -12275, -12275, -12275, -12275, -12275, -12275, -12275, 
271        // 392 - 399
272        -12275, -12275, -12275, -12275, -12275, -12275, -12275, -12275, 
273        // 400 - 407
274        14353,  14353,  14353,  14353,  16401,  16401,  16401,  16401, 
275        // 408 - 415
276        22547,  22547,  24595,  24595,  20497,  20497,  20497,  20497, 
277        // 416 - 423
278        18449,  18449,  18449,  18449,  26643,  26643,  28691,  28691, 
279        // 424 - 431
280        30739,  30739, -32749, -32749, -30701, -30701, -28653, -28653, 
281        // 432 - 439
282        -26605, -26605, -24557, -24557, -22509, -22509, -20461, -20461, 
283        // 440 - 447
284        8207,   8207,   8207,   8207,   8207,   8207,   8207,   8207, 
285        // 448 - 455
286        72,     72,     72,     72,     72,     72,     72,     72, 
287        // 456 - 463
288        72,     72,     72,     72,     72,     72,     72,     72, 
289        // 464 - 471
290        72,     72,     72,     72,     72,     72,     72,     72, 
291        // 472 - 479
292        72,     72,     72,     72,     72,     72,     72,     72, 
293        // 480 - 487
294        72,     72,     72,     72,     72,     72,     72,     72, 
295        // 488 - 495
296        72,     72,     72,     72,     72,     72,     72,     72, 
297        // 496 - 503
298        72,     72,     72,     72,     72,     72,     72,     72, 
299        // 504 - 511
300        72,     72,     72,     72,     72,     72,     72,     72, 
301        // 512 - 519
302        104,    104,    104,    104,    104,    104,    104,    104, 
303        // 520 - 527
304        104,    104,    104,    104,    104,    104,    104,    104, 
305        // 528 - 535
306        104,    104,    104,    104,    104,    104,    104,    104, 
307        // 536 - 543
308        104,    104,    104,    104,    104,    104,    104,    104, 
309        // 544 - 551
310        104,    104,    104,    104,    104,    104,    104,    104, 
311        // 552 - 559
312        104,    104,    104,    104,    104,    104,    104,    104, 
313        // 560 - 567
314        104,    104,    104,    104,    104,    104,    104,    104, 
315        // 568 - 575
316        104,    104,    104,    104,    104,    104,    104,    104, 
317        // 576 - 583
318        4107,   4107,   4107,   4107,   4107,   4107,   4107,   4107, 
319        // 584 - 591
320        4107,   4107,   4107,   4107,   4107,   4107,   4107,   4107, 
321        // 592 - 599
322        4107,   4107,   4107,   4107,   4107,   4107,   4107,   4107, 
323        // 600 - 607
324        4107,   4107,   4107,   4107,   4107,   4107,   4107,   4107, 
325        // 608 - 615
326        266,    266,    266,    266,    266,    266,    266,    266, 
327        // 616 - 623
328        266,    266,    266,    266,    266,    266,    266,    266, 
329        // 624 - 631
330        266,    266,    266,    266,    266,    266,    266,    266, 
331        // 632 - 639
332        266,    266,    266,    266,    266,    266,    266,    266, 
333        // 640 - 647
334        298,    298,    298,    298,    298,    298,    298,    298, 
335        // 648 - 655
336        298,    298,    298,    298,    298,    298,    298,    298, 
337        // 656 - 663
338        298,    298,    298,    298,    298,    298,    298,    298, 
339        // 664 - 671
340        298,    298,    298,    298,    298,    298,    298,    298, 
341        // 672 - 679
342        524,    524,    524,    524,    524,    524,    524,    524, 
343        // 680 - 687
344        524,    524,    524,    524,    524,    524,    524,    524, 
345        // 688 - 695
346        556,    556,    556,    556,    556,    556,    556,    556, 
347        // 696 - 703
348        556,    556,    556,    556,    556,    556,    556,    556, 
349        // 704 - 711
350        136,    136,    136,    136,    136,    136,    136,    136, 
351        // 712 - 719
352        136,    136,    136,    136,    136,    136,    136,    136, 
353        // 720 - 727
354        136,    136,    136,    136,    136,    136,    136,    136, 
355        // 728 - 735
356        136,    136,    136,    136,    136,    136,    136,    136, 
357        // 736 - 743
358        136,    136,    136,    136,    136,    136,    136,    136, 
359        // 744 - 751
360        136,    136,    136,    136,    136,    136,    136,    136, 
361        // 752 - 759
362        136,    136,    136,    136,    136,    136,    136,    136, 
363        // 760 - 767
364        136,    136,    136,    136,    136,    136,    136,    136, 
365        // 768 - 775
366        168,    168,    168,    168,    168,    168,    168,    168, 
367        // 776 - 783
368        168,    168,    168,    168,    168,    168,    168,    168, 
369        // 784 - 791
370        168,    168,    168,    168,    168,    168,    168,    168, 
371        // 792 - 799
372        168,    168,    168,    168,    168,    168,    168,    168, 
373        // 800 - 807
374        168,    168,    168,    168,    168,    168,    168,    168, 
375        // 808 - 815
376        168,    168,    168,    168,    168,    168,    168,    168, 
377        // 816 - 823
378        168,    168,    168,    168,    168,    168,    168,    168, 
379        // 824 - 831
380        168,    168,    168,    168,    168,    168,    168,    168, 
381        // 832 - 839
382        460,    460,    460,    460,    460,    460,    460,    460, 
383        // 840 - 847
384        460,    460,    460,    460,    460,    460,    460,    460, 
385        // 848 - 855
386        492,    492,    492,    492,    492,    492,    492,    492, 
387        // 856 - 863
388        492,    492,    492,    492,    492,    492,    492,    492, 
389        // 864 - 871
390        2059,   2059,   2059,   2059,   2059,   2059,   2059,   2059, 
391        // 872 - 879
392        2059,   2059,   2059,   2059,   2059,   2059,   2059,   2059, 
393        // 880 - 887
394        2059,   2059,   2059,   2059,   2059,   2059,   2059,   2059, 
395        // 888 - 895
396        2059,   2059,   2059,   2059,   2059,   2059,   2059,   2059, 
397        // 896 - 903
398        200,    200,    200,    200,    200,    200,    200,    200, 
399        // 904 - 911
400        200,    200,    200,    200,    200,    200,    200,    200, 
401        // 912 - 919
402        200,    200,    200,    200,    200,    200,    200,    200, 
403        // 920 - 927
404        200,    200,    200,    200,    200,    200,    200,    200, 
405        // 928 - 935
406        200,    200,    200,    200,    200,    200,    200,    200, 
407        // 936 - 943
408        200,    200,    200,    200,    200,    200,    200,    200, 
409        // 944 - 951
410        200,    200,    200,    200,    200,    200,    200,    200, 
411        // 952 - 959
412        200,    200,    200,    200,    200,    200,    200,    200, 
413        // 960 - 967
414        232,    232,    232,    232,    232,    232,    232,    232, 
415        // 968 - 975
416        232,    232,    232,    232,    232,    232,    232,    232, 
417        // 976 - 983
418        232,    232,    232,    232,    232,    232,    232,    232, 
419        // 984 - 991
420        232,    232,    232,    232,    232,    232,    232,    232, 
421        // 992 - 999
422        232,    232,    232,    232,    232,    232,    232,    232, 
423        // 1000 - 1007
424        232,    232,    232,    232,    232,    232,    232,    232, 
425        // 1008 - 1015
426        232,    232,    232,    232,    232,    232,    232,    232, 
427        // 1016 - 1023
428        232,    232,    232,    232,    232,    232,    232,    232, 
429    };
430        
431    // Additional make up codes for both White and Black runs
432    static short additionalMakeup[] = {
433        28679,  28679,  31752,  (short)32777,  
434        (short)33801,  (short)34825,  (short)35849,  (short)36873,
435        (short)29703,  (short)29703,  (short)30727,  (short)30727, 
436        (short)37897,  (short)38921,  (short)39945,  (short)40969
437    };
438
439    // Initial black run look up table, uses the first 4 bits of a code
440    static short initBlack[] = {
441        // 0 - 7
442        3226,  6412,    200,    168,    38,     38,    134,    134,
443        // 8 - 15
444        100,    100,    100,    100,    68,     68,     68,     68
445    };
446
447    // 
448    static short twoBitBlack[] = {292, 260, 226, 226};   // 0 - 3
449
450    // Main black run table, using the last 9 bits of possible 13 bit code
451    static short black[] = {
452        // 0 - 7
453        62,     62,     30,     30,     0,      0,      0,      0, 
454        // 8 - 15
455        0,      0,      0,      0,      0,      0,      0,      0, 
456        // 16 - 23
457        0,      0,      0,      0,      0,      0,      0,      0, 
458        // 24 - 31
459        0,      0,      0,      0,      0,      0,      0,      0, 
460        // 32 - 39
461        3225,   3225,   3225,   3225,   3225,   3225,   3225,   3225, 
462        // 40 - 47
463        3225,   3225,   3225,   3225,   3225,   3225,   3225,   3225, 
464        // 48 - 55
465        3225,   3225,   3225,   3225,   3225,   3225,   3225,   3225, 
466        // 56 - 63
467        3225,   3225,   3225,   3225,   3225,   3225,   3225,   3225, 
468        // 64 - 71
469        588,    588,    588,    588,    588,    588,    588,    588, 
470        // 72 - 79
471        1680,   1680,  20499,  22547,  24595,  26643,   1776,   1776, 
472        // 80 - 87
473        1808,   1808, -24557, -22509, -20461, -18413,   1904,   1904, 
474        // 88 - 95
475        1936,   1936, -16365, -14317,    782,    782,    782,    782, 
476        // 96 - 103
477        814,    814,    814,    814, -12269, -10221,  10257,  10257, 
478        // 104 - 111
479        12305,  12305,  14353,  14353,  16403,  18451,   1712,   1712, 
480        // 112 - 119
481        1744,   1744,  28691,  30739, -32749, -30701, -28653, -26605, 
482        // 120 - 127
483        2061,   2061,   2061,   2061,   2061,   2061,   2061,   2061, 
484        // 128 - 135
485        424,    424,    424,    424,    424,    424,    424,    424, 
486        // 136 - 143
487        424,    424,    424,    424,    424,    424,    424,    424, 
488        // 144 - 151
489        424,    424,    424,    424,    424,    424,    424,    424, 
490        // 152 - 159
491        424,    424,    424,    424,    424,    424,    424,    424, 
492        // 160 - 167
493        750,    750,    750,    750,   1616,   1616,   1648,   1648, 
494        // 168 - 175
495        1424,   1424,   1456,   1456,   1488,   1488,   1520,   1520, 
496        // 176 - 183
497        1840,   1840,   1872,   1872,   1968,   1968,   8209,   8209, 
498        // 184 - 191
499        524,    524,    524,    524,    524,    524,    524,    524, 
500        // 192 - 199
501        556,    556,    556,    556,    556,    556,    556,    556, 
502        // 200 - 207
503        1552,   1552,   1584,   1584,   2000,   2000,   2032,   2032, 
504        // 208 - 215
505        976,    976,   1008,   1008,   1040,   1040,   1072,   1072, 
506        // 216 - 223
507        1296,   1296,   1328,   1328,    718,    718,    718,    718, 
508        // 224 - 231
509        456,    456,    456,    456,    456,    456,    456,    456, 
510        // 232 - 239
511        456,    456,    456,    456,    456,    456,    456,    456, 
512        // 240 - 247
513        456,    456,    456,    456,    456,    456,    456,    456, 
514        // 248 - 255
515        456,    456,    456,    456,    456,    456,    456,    456, 
516        // 256 - 263
517        326,    326,    326,    326,    326,    326,    326,    326, 
518        // 264 - 271
519        326,    326,    326,    326,    326,    326,    326,    326, 
520        // 272 - 279
521        326,    326,    326,    326,    326,    326,    326,    326, 
522        // 280 - 287
523        326,    326,    326,    326,    326,    326,    326,    326, 
524        // 288 - 295
525        326,    326,    326,    326,    326,    326,    326,    326, 
526        // 296 - 303
527        326,    326,    326,    326,    326,    326,    326,    326, 
528        // 304 - 311
529        326,    326,    326,    326,    326,    326,    326,    326, 
530        // 312 - 319
531        326,    326,    326,    326,    326,    326,    326,    326, 
532        // 320 - 327
533        358,    358,    358,    358,    358,    358,    358,    358, 
534        // 328 - 335
535        358,    358,    358,    358,    358,    358,    358,    358, 
536        // 336 - 343
537        358,    358,    358,    358,    358,    358,    358,    358, 
538        // 344 - 351
539        358,    358,    358,    358,    358,    358,    358,    358, 
540        // 352 - 359
541        358,    358,    358,    358,    358,    358,    358,    358, 
542        // 360 - 367
543        358,    358,    358,    358,    358,    358,    358,    358, 
544        // 368 - 375
545        358,    358,    358,    358,    358,    358,    358,    358, 
546        // 376 - 383
547        358,    358,    358,    358,    358,    358,    358,    358, 
548        // 384 - 391
549        490,    490,    490,    490,    490,    490,    490,    490, 
550        // 392 - 399
551        490,    490,    490,    490,    490,    490,    490,    490, 
552        // 400 - 407
553        4113,   4113,   6161,   6161,    848,    848,    880,    880, 
554        // 408 - 415
555        912,    912,    944,    944,    622,    622,    622,    622, 
556        // 416 - 423
557        654,    654,    654,    654,   1104,   1104,   1136,   1136, 
558        // 424 - 431
559        1168,   1168,   1200,   1200,   1232,   1232,   1264,   1264, 
560        // 432 - 439
561        686,    686,    686,    686,   1360,   1360,   1392,   1392, 
562        // 440 - 447
563        12,     12,     12,     12,     12,     12,     12,     12, 
564        // 448 - 455
565        390,    390,    390,    390,    390,    390,    390,    390, 
566        // 456 - 463
567        390,    390,    390,    390,    390,    390,    390,    390, 
568        // 464 - 471
569        390,    390,    390,    390,    390,    390,    390,    390, 
570        // 472 - 479
571        390,    390,    390,    390,    390,    390,    390,    390, 
572        // 480 - 487
573        390,    390,    390,    390,    390,    390,    390,    390, 
574        // 488 - 495
575        390,    390,    390,    390,    390,    390,    390,    390, 
576        // 496 - 503
577        390,    390,    390,    390,    390,    390,    390,    390, 
578        // 504 - 511
579        390,    390,    390,    390,    390,    390,    390,    390, 
580    };
581
582    static byte twoDCodes[] = {
583        // 0 - 7
584        80,     88,     23,     71,     30,     30,     62,     62, 
585        // 8 - 15
586        4,      4,      4,      4,      4,      4,      4,      4, 
587        // 16 - 23
588        11,     11,     11,     11,     11,     11,     11,     11, 
589        // 24 - 31
590        11,     11,     11,     11,     11,     11,     11,     11, 
591        // 32 - 39
592        35,     35,     35,     35,     35,     35,     35,     35, 
593        // 40 - 47
594        35,     35,     35,     35,     35,     35,     35,     35, 
595        // 48 - 55
596        51,     51,     51,     51,     51,     51,     51,     51, 
597        // 56 - 63
598        51,     51,     51,     51,     51,     51,     51,     51, 
599        // 64 - 71
600        41,     41,     41,     41,     41,     41,     41,     41, 
601        // 72 - 79
602        41,     41,     41,     41,     41,     41,     41,     41, 
603        // 80 - 87
604        41,     41,     41,     41,     41,     41,     41,     41, 
605        // 88 - 95
606        41,     41,     41,     41,     41,     41,     41,     41, 
607        // 96 - 103
608        41,     41,     41,     41,     41,     41,     41,     41, 
609        // 104 - 111
610        41,     41,     41,     41,     41,     41,     41,     41, 
611        // 112 - 119
612        41,     41,     41,     41,     41,     41,     41,     41, 
613        // 120 - 127
614        41,     41,     41,     41,     41,     41,     41,     41, 
615    };
616
617    public TIFFFaxDecompressor() {}
618
619    /**
620     * Invokes the superclass method and then sets instance variables on
621     * the basis of the metadata set on this decompressor.
622     */
623    public void beginDecoding() {
624        super.beginDecoding();
625
626        if(metadata instanceof TIFFImageMetadata) {
627            TIFFImageMetadata tmetadata = (TIFFImageMetadata)metadata;
628            TIFFField f;
629
630            f = tmetadata.getTIFFField(BaselineTIFFTagSet.TAG_FILL_ORDER);
631            this.fillOrder = f == null ? 1 : f.getAsInt(0);
632
633            f = tmetadata.getTIFFField(BaselineTIFFTagSet.TAG_COMPRESSION);
634            this.compression = f == null ?
635                BaselineTIFFTagSet.COMPRESSION_CCITT_RLE : f.getAsInt(0);
636
637            f = tmetadata.getTIFFField(BaselineTIFFTagSet.TAG_T4_OPTIONS);
638            this.t4Options = f == null ? 0 : f.getAsInt(0);
639            this.oneD = (int)(t4Options & 0x01);
640            // uncompressedMode - haven't dealt with this yet.
641            this.uncompressedMode = (int)((t4Options & 0x02) >> 1);
642            this.fillBits = (int)((t4Options & 0x04) >> 2);
643            f = tmetadata.getTIFFField(BaselineTIFFTagSet.TAG_T6_OPTIONS);
644            this.t6Options = f == null ? 0 : f.getAsInt(0);
645        } else {
646            this.fillOrder = 1; // MSB-to-LSB
647
648            this.compression = BaselineTIFFTagSet.COMPRESSION_CCITT_RLE; // RLE
649
650            this.t4Options = 0; // Irrelevant as applies to T.4 only
651            this.oneD = 0; // One-dimensional
652            this.uncompressedMode = 0; // Not uncompressed mode
653            this.fillBits = 0; // No fill bits
654            this.t6Options = 0; 
655        }
656    }
657
658    public void decodeRaw(byte[] b, int dstOffset,
659                          int pixelBitStride, // will always be 1
660                          int scanlineStride) throws IOException {
661
662        this.buffer = b;
663
664        this.w = srcWidth;
665        this.h = srcHeight;
666        this.bitsPerScanline = scanlineStride*8;
667        this.lineBitNum = 8*dstOffset;
668
669        this.data = new byte[(int)byteCount];
670        this.bitPointer = 0;
671        this.bytePointer = 0;
672        this.prevChangingElems = new int[w + 1];
673        this.currChangingElems = new int[w + 1];
674
675        stream.seek(offset);
676        stream.readFully(data);
677
678        try {
679            if (compression == BaselineTIFFTagSet.COMPRESSION_CCITT_RLE) {
680                decodeRLE();
681            } else if (compression == BaselineTIFFTagSet.COMPRESSION_CCITT_T_4) {
682                decodeT4();
683            } else if (compression == BaselineTIFFTagSet.COMPRESSION_CCITT_T_6) {
684                this.uncompressedMode = (int)((t6Options & 0x02) >> 1);
685                decodeT6();
686            } else {
687                throw new IIOException("Unknown compression type " + compression);
688            }
689        } catch(ArrayIndexOutOfBoundsException e) {
690            ByteArrayOutputStream baos = new ByteArrayOutputStream();
691            e.printStackTrace(new PrintStream(baos));
692            String s = new String(baos.toByteArray());
693            warning("Ignoring exception:\n "+s);
694        }
695    }
696
697    public void decodeRLE() throws IIOException {
698        for (int i = 0; i < h; i++) {
699            // Decode the line.
700            decodeNextScanline(srcMinY + i);
701
702            // Advance to the next byte boundary if not already there.
703            if (bitPointer != 0) {
704                bytePointer++;
705                bitPointer = 0;
706            }
707
708            // Update the total number of bits.
709            lineBitNum += bitsPerScanline;
710        }
711    }
712
713    public void decodeNextScanline(int lineIndex) throws IIOException {
714        int bits = 0, code = 0, isT = 0;
715        int current, entry, twoBits;
716        boolean isWhite = true;
717        int dstEnd = 0;
718
719        int bitOffset = 0;
720
721        // Initialize starting of the changing elements array
722        changingElemSize = 0;
723
724        // While scanline not complete
725        while (bitOffset < w) {
726
727            // Mark start of white run.
728            int runOffset = bitOffset;
729
730            while (isWhite && bitOffset < w) {
731                // White run
732                current = nextNBits(10);
733                entry = white[current];
734                
735                // Get the 3 fields from the entry
736                isT = entry & 0x0001;
737                bits = (entry >>> 1) & 0x0f;
738                
739                if (bits == 12) {          // Additional Make up code
740                    // Get the next 2 bits
741                    twoBits = nextLesserThan8Bits(2);
742                    // Consolidate the 2 new bits and last 2 bits into 4 bits
743                    current = ((current << 2) & 0x000c) | twoBits; 
744                    entry = additionalMakeup[current];
745                    bits = (entry >>> 1) & 0x07;     // 3 bits 0000 0111
746                    code  = (entry >>> 4) & 0x0fff;  // 12 bits
747                    bitOffset += code; // Skip white run
748
749                    updatePointer(4 - bits);
750                } else if (bits == 0) {     // ERROR
751                    warning("Error 0");
752                    // XXX return?
753                } else if (bits == 15) {    // EOL
754                    //
755                    // Instead of throwing an exception, assume that the
756                    // EOL was premature; emit a warning and return.
757                    //
758                    warning("Premature EOL in white run of line "+lineIndex+
759                            ": read "+bitOffset+" of "+w+" expected pixels.");
760                    return;
761                } else {
762                    // 11 bits - 0000 0111 1111 1111 = 0x07ff
763                    code = (entry >>> 5) & 0x07ff;  
764                    bitOffset += code;
765
766                    updatePointer(10 - bits);
767                    if (isT == 0) {
768                        isWhite = false;
769                        currChangingElems[changingElemSize++] = bitOffset;
770                    }
771                }
772            }
773
774            // Check whether this run completed one width
775            if (bitOffset == w) {
776                // If the white run has not been terminated then ensure that
777                // the next code word is a terminating code for a white run
778                // of length zero.
779                int runLength = bitOffset - runOffset;
780                if(isWhite &&
781                   runLength != 0 && runLength % 64 == 0 &&
782                   nextNBits(8) != 0x35) {
783                    warning("Missing zero white run length terminating code!");
784                    updatePointer(8);
785                }
786                break;
787            }
788
789            // Mark start of black run.
790            runOffset = bitOffset;
791
792            while (isWhite == false && bitOffset < w) {
793                // Black run
794                current = nextLesserThan8Bits(4);
795                entry = initBlack[current];
796                
797                // Get the 3 fields from the entry
798                isT = entry & 0x0001;
799                bits = (entry >>> 1) & 0x000f;
800                code = (entry >>> 5) & 0x07ff;
801
802                if (code == 100) {
803                    current = nextNBits(9);
804                    entry = black[current];
805                    
806                    // Get the 3 fields from the entry
807                    isT = entry & 0x0001;
808                    bits = (entry >>> 1) & 0x000f;
809                    code = (entry >>> 5) & 0x07ff;
810
811                    if (bits == 12) {
812                        // Additional makeup codes
813                        updatePointer(5);
814                        current = nextLesserThan8Bits(4);
815                        entry = additionalMakeup[current];
816                        bits = (entry >>> 1) & 0x07;     // 3 bits 0000 0111
817                        code  = (entry >>> 4) & 0x0fff;  // 12 bits
818
819                        setToBlack(bitOffset, code);
820                        bitOffset += code;
821
822                        updatePointer(4 - bits);
823                    } else if (bits == 15) {
824                        //
825                        // Instead of throwing an exception, assume that the
826                        // EOL was premature; emit a warning and return.
827                        //
828                        warning("Premature EOL in black run of line "+
829                                lineIndex+": read "+bitOffset+" of "+w+
830                                " expected pixels.");
831                        return;
832                    } else {
833                        setToBlack(bitOffset, code);
834                        bitOffset += code;
835
836                        updatePointer(9 - bits);
837                        if (isT == 0) {
838                            isWhite = true;
839                            currChangingElems[changingElemSize++] = bitOffset;
840                        }
841                    }
842                } else if (code == 200) {
843                    // Is a Terminating code
844                    current = nextLesserThan8Bits(2);
845                    entry = twoBitBlack[current];
846                    code = (entry >>> 5) & 0x07ff;
847                    bits = (entry >>> 1) & 0x0f;
848
849                    setToBlack(bitOffset, code);
850                    bitOffset += code;
851
852                    updatePointer(2 - bits);
853                    isWhite = true;
854                    currChangingElems[changingElemSize++] = bitOffset;
855                } else {
856                    // Is a Terminating code
857                    setToBlack(bitOffset, code);
858                    bitOffset += code;
859
860                    updatePointer(4 - bits);
861                    isWhite = true;
862                    currChangingElems[changingElemSize++] = bitOffset;
863                }
864            }
865
866            // Check whether this run completed one width
867            if (bitOffset == w) {
868                // If the black run has not been terminated then ensure that
869                // the next code word is a terminating code for a black run
870                // of length zero.
871                int runLength = bitOffset - runOffset;
872                if(!isWhite &&
873                   runLength != 0 && runLength % 64 == 0 &&
874                   nextNBits(10) != 0x37) {
875                    warning("Missing zero black run length terminating code!");
876                    updatePointer(10);
877                }
878                break;
879            }
880        }
881
882        currChangingElems[changingElemSize++] = bitOffset;
883    }
884
885    public void decodeT4() throws IIOException {
886        int height = h;
887
888        int a0, a1, b1, b2;
889        int[] b = new int[2];
890        int entry, code, bits, color;
891        boolean isWhite;
892        int currIndex = 0;
893        int temp[];
894
895        if(data.length < 2) {
896            throw new IIOException("Insufficient data to read initial EOL.");
897        }
898
899        // The data should start with an EOL code
900        int next12 = nextNBits(12);
901        if(next12 != 1) {
902            warning("T.4 compressed data should begin with EOL.");
903        }
904        updatePointer(12);
905
906        // Find the first one-dimensionally encoded line.
907        int modeFlag = 0;
908        int lines = -1; // indicates imaginary line before first actual line.
909        while(modeFlag != 1) {
910            try {
911                modeFlag = findNextLine();
912                lines++; // Normally 'lines' will be 0 on exiting loop.
913            } catch(EOFException eofe) {
914                throw new IIOException("No reference line present.");
915            }
916        }
917
918        int bitOffset;
919
920        // Then the 1D encoded scanline data will occur, changing elements
921        // array gets set.
922        decodeNextScanline(srcMinY);
923        lines++;
924        lineBitNum += bitsPerScanline;
925
926        while(lines < height) {
927
928            // Every line must begin with an EOL followed by a bit which
929            // indicates whether the following scanline is 1D or 2D encoded.
930            try {
931                modeFlag = findNextLine();
932            } catch(EOFException eofe) {
933                warning("Input exhausted before EOL found at line "+
934                        (srcMinY+lines)+": read 0 of "+w+" expected pixels.");
935                break;
936            }
937            if(modeFlag == 0) {
938                // 2D encoded scanline follows          
939                
940                // Initialize previous scanlines changing elements, and 
941                // initialize current scanline's changing elements array
942                temp = prevChangingElems;
943                prevChangingElems = currChangingElems;
944                currChangingElems = temp;
945                currIndex = 0;
946                
947                // a0 has to be set just before the start of this scanline.
948                a0 = -1;
949                isWhite = true;
950                bitOffset = 0;
951
952                lastChangingElement = 0;
953
954                while (bitOffset < w) {
955                    // Get the next changing element
956                    getNextChangingElement(a0, isWhite, b);
957                    
958                    b1 = b[0];
959                    b2 = b[1];
960                    
961                    // Get the next seven bits
962                    entry = nextLesserThan8Bits(7);
963                    
964                    // Run these through the 2DCodes table
965                    entry = (int)(twoDCodes[entry] & 0xff);
966                    
967                    // Get the code and the number of bits used up
968                    code = (entry & 0x78) >>> 3;
969                    bits = entry & 0x07;
970                    
971                    if (code == 0) {
972                        if (!isWhite) {
973                            setToBlack(bitOffset, b2 - bitOffset);
974                        }
975                        bitOffset = a0 = b2;
976                        
977                        // Set pointer to consume the correct number of bits.
978                        updatePointer(7 - bits);
979                    } else if (code == 1) {
980                        // Horizontal
981                        updatePointer(7 - bits);
982                        
983                        // identify the next 2 codes.
984                        int number;
985                        if (isWhite) {
986                            number = decodeWhiteCodeWord();
987                            bitOffset += number;
988                            currChangingElems[currIndex++] = bitOffset;
989                            
990                            number = decodeBlackCodeWord();
991                            setToBlack(bitOffset, number);
992                            bitOffset += number;
993                            currChangingElems[currIndex++] = bitOffset;
994                        } else {
995                            number = decodeBlackCodeWord();
996                            setToBlack(bitOffset, number);
997                            bitOffset += number;
998                            currChangingElems[currIndex++] = bitOffset;
999                            
1000                            number = decodeWhiteCodeWord();
1001                            bitOffset += number;
1002                            currChangingElems[currIndex++] = bitOffset;
1003                        }
1004                        
1005                        a0 = bitOffset;
1006                    } else if (code <= 8) {
1007                        // Vertical
1008                        a1 = b1 + (code - 5);
1009                        
1010                        currChangingElems[currIndex++] = a1;
1011                        
1012                        // We write the current color till a1 - 1 pos,
1013                        // since a1 is where the next color starts
1014                        if (!isWhite) {
1015                            setToBlack(bitOffset, a1 - bitOffset);
1016                        }
1017                        bitOffset = a0 = a1;
1018                        isWhite = !isWhite;
1019                            
1020                        updatePointer(7 - bits);
1021                    } else {
1022                        warning("Unknown coding mode encountered at line "+
1023                                (srcMinY+lines)+": read "+bitOffset+" of "+w+
1024                                " expected pixels.");
1025
1026                        // Find the next one-dimensionally encoded line.
1027                        int numLinesTested = 0;
1028                        while(modeFlag != 1) {
1029                            try {
1030                                modeFlag = findNextLine();
1031                                numLinesTested++;
1032                            } catch(EOFException eofe) {
1033                                warning("Sync loss at line "+
1034                                        (srcMinY+lines)+": read "+
1035                                        lines+" of "+height+" lines.");
1036                                return;
1037                            }
1038                        }
1039                        lines += numLinesTested - 1;
1040                        updatePointer(13);
1041                        break;
1042                    }
1043                }
1044                
1045                // Add the changing element beyond the current scanline for the
1046                // other color too
1047                currChangingElems[currIndex++] = bitOffset;
1048                changingElemSize = currIndex;
1049            } else { // modeFlag == 1
1050                // 1D encoded scanline follows
1051                decodeNextScanline(srcMinY+lines);
1052            }
1053
1054            lineBitNum += bitsPerScanline;
1055            lines++;
1056        } // while(lines < height)
1057    }
1058
1059    public synchronized void decodeT6() throws IIOException {
1060        int height = h;
1061
1062        int bufferOffset = 0;
1063
1064        int a0, a1, b1, b2;
1065        int entry, code, bits;
1066        byte color;
1067        boolean isWhite;
1068        int currIndex;
1069        int temp[];
1070
1071        // Return values from getNextChangingElement
1072        int[] b = new int[2];
1073        
1074        // uncompressedMode - have written some code for this, but this 
1075        // has not been tested due to lack of test images using this optional
1076        // extension. This code is when code == 11. aastha 03/03/1999
1077
1078        // Local cached reference
1079        int[] cce = currChangingElems;
1080
1081        // Assume invisible preceding row of all white pixels and insert
1082        // both black and white changing elements beyond the end of this
1083        // imaginary scanline.
1084        changingElemSize = 0;
1085        cce[changingElemSize++] = w;
1086        cce[changingElemSize++] = w;
1087
1088        int bitOffset;
1089
1090        for (int lines = 0; lines < height; lines++) {
1091            // a0 has to be set just before the start of the scanline.
1092            a0 = -1;
1093            isWhite = true;
1094        
1095            // Assign the changing elements of the previous scanline to 
1096            // prevChangingElems and start putting this new scanline's
1097            // changing elements into the currChangingElems.
1098            temp = prevChangingElems;
1099            prevChangingElems = currChangingElems;
1100            cce = currChangingElems = temp;
1101            currIndex = 0;
1102
1103            // Start decoding the scanline
1104            bitOffset = 0;
1105
1106            // Reset search start position for getNextChangingElement
1107            lastChangingElement = 0;
1108
1109            // Till one whole scanline is decoded
1110            while (bitOffset < w) {
1111                // Get the next changing element 
1112                getNextChangingElement(a0, isWhite, b);
1113                b1 = b[0];
1114                b2 = b[1];
1115
1116                // Get the next seven bits
1117                entry = nextLesserThan8Bits(7);
1118                // Run these through the 2DCodes table
1119                entry = (int)(twoDCodes[entry] & 0xff);
1120
1121                // Get the code and the number of bits used up
1122                code = (entry & 0x78) >>> 3;
1123                bits = entry & 0x07;
1124                
1125                if (code == 0) { // Pass
1126                    // We always assume WhiteIsZero format for fax.
1127                    if (!isWhite) {
1128                        if(b2 > w) {
1129                            b2 = w;
1130                            warning("Decoded row "+(srcMinY+lines)+
1131                                    " too long; ignoring extra samples.");
1132                        }
1133                        setToBlack(bitOffset, b2 - bitOffset);
1134                    }
1135                    bitOffset = a0 = b2;
1136
1137                    // Set pointer to only consume the correct number of bits.
1138                    updatePointer(7 - bits);
1139                } else if (code == 1) { // Horizontal
1140                    // Set pointer to only consume the correct number of bits.
1141                    updatePointer(7 - bits);
1142                    
1143                    // identify the next 2 alternating color codes.
1144                    int number;
1145                    if (isWhite) {
1146                        // Following are white and black runs
1147                        number = decodeWhiteCodeWord();
1148                        bitOffset += number;
1149                        cce[currIndex++] = bitOffset;
1150
1151                        number = decodeBlackCodeWord();
1152                        if(number > w - bitOffset) {
1153                            number = w - bitOffset;
1154                            warning("Decoded row "+(srcMinY+lines)+
1155                                    " too long; ignoring extra samples.");
1156                        }
1157                        setToBlack(bitOffset, number);
1158                        bitOffset += number;
1159                        cce[currIndex++] = bitOffset;
1160                    } else {
1161                        // First a black run and then a white run follows
1162                        number = decodeBlackCodeWord();
1163                        if(number > w - bitOffset) {
1164                            number = w - bitOffset;
1165                            warning("Decoded row "+(srcMinY+lines)+
1166                                    " too long; ignoring extra samples.");
1167                        }
1168                        setToBlack(bitOffset, number);
1169                        bitOffset += number;
1170                        cce[currIndex++] = bitOffset;
1171
1172                        number = decodeWhiteCodeWord();
1173                        bitOffset += number;
1174                        cce[currIndex++] = bitOffset;
1175                    }
1176                    
1177                    a0 = bitOffset;
1178                } else if (code <= 8) { // Vertical
1179                    a1 = b1 + (code - 5);
1180                    cce[currIndex++] = a1;
1181
1182                    // We write the current color till a1 - 1 pos,
1183                    // since a1 is where the next color starts
1184                    if (!isWhite) {
1185                        if(a1 > w) {
1186                            a1 = w;
1187                            warning("Decoded row "+(srcMinY+lines)+
1188                                    " too long; ignoring extra samples.");
1189                        }
1190                        setToBlack(bitOffset, a1 - bitOffset);
1191                    }
1192                    bitOffset = a0 = a1;
1193                    isWhite = !isWhite;
1194
1195                    updatePointer(7 - bits);
1196                } else if (code == 11) {
1197                    int entranceCode = nextLesserThan8Bits(3);
1198                    if (entranceCode != 7) {
1199                        String msg =
1200                            "Unsupported entrance code "+entranceCode+
1201                            " for extension mode at line "+(srcMinY+lines)+".";
1202                        warning(msg);
1203                    }
1204
1205                    int zeros = 0;
1206                    boolean exit = false;
1207
1208                    while (!exit) {
1209                        while (nextLesserThan8Bits(1) != 1) {
1210                            zeros++;
1211                        }
1212                        
1213                        if (zeros > 5) {
1214                            // Exit code
1215                            
1216                            // Zeros before exit code
1217                            zeros = zeros - 6;
1218
1219                            if (!isWhite && (zeros > 0)) {
1220                                cce[currIndex++] = bitOffset;
1221                            }
1222                            
1223                            // Zeros before the exit code
1224                            bitOffset += zeros;
1225                            if (zeros > 0) {
1226                                // Some zeros have been written
1227                                isWhite = true;
1228                            } 
1229                            
1230                            // Read in the bit which specifies the color of
1231                            // the following run
1232                            if (nextLesserThan8Bits(1) == 0) {
1233                                if (!isWhite) {
1234                                    cce[currIndex++] = bitOffset;
1235                                }
1236                                isWhite = true;
1237                            } else {
1238                                if (isWhite) {
1239                                    cce[currIndex++] = bitOffset;
1240                                }
1241                                isWhite = false;
1242                            }
1243
1244                            exit = true;
1245                        } 
1246
1247                        if (zeros == 5) {
1248                            if (!isWhite) {
1249                                cce[currIndex++] = bitOffset;
1250                            }
1251                            bitOffset += zeros;
1252
1253                            // Last thing written was white
1254                            isWhite = true;
1255                        } else {
1256                            bitOffset += zeros;
1257
1258                            cce[currIndex++] = bitOffset;
1259                            setToBlack(bitOffset, 1);
1260                            ++bitOffset;
1261
1262                            // Last thing written was black
1263                            isWhite = false;
1264                        }
1265
1266                    }
1267                } else {
1268                    String msg =
1269                        "Unknown coding mode encountered at line "+
1270                        (srcMinY+lines)+".";
1271                    warning(msg);
1272                }
1273            } // while bitOffset < w
1274            
1275            // Add the changing element beyond the current scanline for the
1276            // other color too, if not already added previously
1277            if (currIndex <= w)
1278                cce[currIndex++] = bitOffset;
1279
1280            // Number of changing elements in this scanline.
1281            changingElemSize = currIndex;
1282
1283            lineBitNum += bitsPerScanline;
1284        } // for lines < height
1285    }
1286
1287    private void setToBlack(int bitNum, int numBits) {
1288        // bitNum is relative to current scanline so bump it by lineBitNum
1289        bitNum += lineBitNum;
1290
1291        int lastBit = bitNum + numBits;
1292        int byteNum = bitNum >> 3;
1293
1294        // Handle bits in first byte
1295        int shift = bitNum & 0x7;
1296        if (shift > 0) {
1297            int maskVal = 1 << (7 - shift);
1298            byte val = buffer[byteNum];
1299            while (maskVal > 0 && bitNum < lastBit) {
1300                val |= maskVal;
1301                maskVal >>= 1;
1302                ++bitNum;
1303            }
1304            buffer[byteNum] = val;
1305        }
1306
1307        // Fill in 8 bits at a time
1308        byteNum = bitNum >> 3;
1309        while (bitNum < lastBit - 7) {
1310            buffer[byteNum++] = (byte)255;
1311            bitNum += 8;
1312        }
1313
1314        // Fill in remaining bits
1315        while (bitNum < lastBit) {
1316            byteNum = bitNum >> 3;
1317            buffer[byteNum] |= 1 << (7 - (bitNum & 0x7));
1318            ++bitNum;
1319        }
1320    }
1321
1322    // Returns run length
1323    private int decodeWhiteCodeWord() throws IIOException {
1324        int current, entry, bits, isT, twoBits, code = -1;
1325        int runLength = 0;
1326        boolean isWhite = true;
1327
1328        while (isWhite) {
1329            current = nextNBits(10);
1330            entry = white[current];
1331            
1332            // Get the 3 fields from the entry
1333            isT = entry & 0x0001;
1334            bits = (entry >>> 1) & 0x0f;
1335            
1336            if (bits == 12) {           // Additional Make up code
1337                // Get the next 2 bits
1338                twoBits = nextLesserThan8Bits(2);
1339                // Consolidate the 2 new bits and last 2 bits into 4 bits
1340                current = ((current << 2) & 0x000c) | twoBits; 
1341                entry = additionalMakeup[current];
1342                bits = (entry >>> 1) & 0x07;     // 3 bits 0000 0111
1343                code = (entry >>> 4) & 0x0fff;   // 12 bits
1344                runLength += code;
1345                updatePointer(4 - bits);
1346            } else if (bits == 0) {     // ERROR
1347                throw new IIOException("Error 0");
1348            } else if (bits == 15) {    // EOL
1349                throw new IIOException("Error 1");
1350            } else {
1351                // 11 bits - 0000 0111 1111 1111 = 0x07ff
1352                code = (entry >>> 5) & 0x07ff;  
1353                runLength += code;
1354                updatePointer(10 - bits);
1355                if (isT == 0) {
1356                    isWhite = false;
1357                }
1358            }
1359        }
1360
1361        return runLength;
1362    }
1363
1364    // Returns run length
1365    private int decodeBlackCodeWord() throws IIOException {
1366        int current, entry, bits, isT, twoBits, code = -1;
1367        int runLength = 0;
1368        boolean isWhite = false;
1369        
1370        while (!isWhite) {
1371            current = nextLesserThan8Bits(4);
1372            entry = initBlack[current];
1373            
1374            // Get the 3 fields from the entry
1375            isT = entry & 0x0001;
1376            bits = (entry >>> 1) & 0x000f;
1377            code = (entry >>> 5) & 0x07ff;
1378            
1379            if (code == 100) {
1380                current = nextNBits(9);
1381                entry = black[current];
1382                
1383                // Get the 3 fields from the entry
1384                isT = entry & 0x0001;
1385                bits = (entry >>> 1) & 0x000f;
1386                code = (entry >>> 5) & 0x07ff;
1387                
1388                if (bits == 12) {
1389                    // Additional makeup codes              
1390                    updatePointer(5);
1391                    current = nextLesserThan8Bits(4);
1392                    entry = additionalMakeup[current];
1393                    bits = (entry >>> 1) & 0x07;     // 3 bits 0000 0111
1394                    code  = (entry >>> 4) & 0x0fff;  // 12 bits
1395                    runLength += code;
1396                    
1397                    updatePointer(4 - bits);
1398                } else if (bits == 15) {
1399                    // EOL code
1400                    throw new IIOException("Error 2");
1401                } else {
1402                    runLength += code;
1403                    updatePointer(9 - bits);
1404                    if (isT == 0) {
1405                        isWhite = true;
1406                    }
1407                }
1408            } else if (code == 200) {
1409                // Is a Terminating code
1410                current = nextLesserThan8Bits(2);
1411                entry = twoBitBlack[current];
1412                code = (entry >>> 5) & 0x07ff;
1413                runLength += code;
1414                bits = (entry >>> 1) & 0x0f;
1415                updatePointer(2 - bits);
1416                isWhite = true;
1417            } else {
1418                // Is a Terminating code
1419                runLength += code;
1420                updatePointer(4 - bits);
1421                isWhite = true;
1422            }
1423        }
1424
1425        return runLength;
1426    }
1427
1428    private int findNextLine() throws IIOException, EOFException {
1429        // Set maximum and current bit index into the compressed data.
1430        int bitIndexMax = data.length*8 - 1;
1431        int bitIndexMax12 = bitIndexMax - 12;
1432        int bitIndex = bytePointer*8 + bitPointer;
1433
1434        // Loop while at least 12 bits are available.
1435        while(bitIndex <= bitIndexMax12) {
1436            // Get the next 12 bits.
1437            int next12Bits = nextNBits(12);
1438            bitIndex += 12;
1439
1440            // Loop while the 12 bits are not unity, i.e., while the EOL
1441            // has not been reached, and there is at least one bit left.
1442            while(next12Bits != 1 && bitIndex < bitIndexMax) {
1443                next12Bits =
1444                    ((next12Bits & 0x000007ff) << 1) |
1445                    (nextLesserThan8Bits(1) & 0x00000001);
1446                bitIndex++;
1447            }
1448
1449            if(next12Bits == 1) { // now positioned just after EOL
1450                if(oneD == 1) { // two-dimensional coding
1451                    if(bitIndex < bitIndexMax) {
1452                        // check next bit against type of line being sought
1453                        return nextLesserThan8Bits(1);
1454                    }
1455                } else {
1456                    return 1;
1457                }
1458            }
1459        }
1460            
1461        // EOL not found.
1462        throw new EOFException();
1463    }
1464
1465    private void getNextChangingElement(int a0, boolean isWhite, int[] ret) throws IIOException {
1466        // Local copies of instance variables
1467        int[] pce = this.prevChangingElems;
1468        int ces = this.changingElemSize;
1469
1470        // If the previous match was at an odd element, we still
1471        // have to search the preceeding element.
1472        // int start = lastChangingElement & ~0x1;
1473        int start = lastChangingElement > 0 ? lastChangingElement - 1 : 0;
1474        if (isWhite) {
1475            start &= ~0x1; // Search even numbered elements
1476        } else {
1477            start |= 0x1; // Search odd numbered elements
1478        }
1479
1480        int i = start;
1481        for (; i < ces; i += 2) {
1482            int temp = pce[i];
1483            if (temp > a0) {
1484                lastChangingElement = i;
1485                ret[0] = temp;
1486                break;
1487            }
1488        }
1489
1490        if (i + 1 < ces) {
1491            ret[1] = pce[i + 1];
1492        }
1493    }
1494
1495    private int nextNBits(int bitsToGet) throws IIOException {
1496        byte b, next, next2next;
1497        int l = data.length - 1;
1498        int bp = this.bytePointer;
1499            
1500        if (fillOrder == 1) {
1501            b = data[bp];
1502            
1503            if (bp == l) {
1504                next = 0x00;
1505                next2next = 0x00;
1506            } else if ((bp + 1) == l) {
1507                next = data[bp + 1];
1508                next2next = 0x00;
1509            } else {
1510                next = data[bp + 1];
1511                next2next = data[bp + 2];
1512            }
1513        } else if (fillOrder == 2) {
1514            b = flipTable[data[bp] & 0xff];
1515
1516            if (bp == l) {
1517                next = 0x00;
1518                next2next = 0x00;
1519            } else if ((bp + 1) == l) {
1520                next = flipTable[data[bp + 1] & 0xff];
1521                next2next = 0x00;
1522            } else {
1523                next = flipTable[data[bp + 1] & 0xff];
1524                next2next = flipTable[data[bp + 2] & 0xff];
1525            }
1526        } else {
1527            throw new IIOException("Invalid FillOrder");
1528        }
1529
1530        int bitsLeft = 8 - bitPointer;
1531        int bitsFromNextByte = bitsToGet - bitsLeft;
1532        int bitsFromNext2NextByte = 0;
1533        if (bitsFromNextByte > 8) {
1534            bitsFromNext2NextByte = bitsFromNextByte - 8;
1535            bitsFromNextByte = 8;
1536        }
1537        
1538        bytePointer++;
1539
1540        int i1 = (b & table1[bitsLeft]) << (bitsToGet - bitsLeft);
1541        int i2 = (next & table2[bitsFromNextByte]) >>> (8 - bitsFromNextByte);
1542        
1543        int i3 = 0;
1544        if (bitsFromNext2NextByte != 0) {
1545            i2 <<= bitsFromNext2NextByte;
1546            i3 = (next2next & table2[bitsFromNext2NextByte]) >>> 
1547                (8 - bitsFromNext2NextByte);
1548            i2 |= i3;
1549            bytePointer++;
1550            bitPointer = bitsFromNext2NextByte;
1551        } else {
1552            if (bitsFromNextByte == 8) {
1553                bitPointer = 0;
1554                bytePointer++;
1555            } else {
1556                bitPointer = bitsFromNextByte;
1557            }
1558        }
1559        
1560        int i = i1 | i2;
1561        return i;
1562    }
1563
1564    private int nextLesserThan8Bits(int bitsToGet) throws IIOException {
1565        byte b, next;
1566        int l = data.length - 1;
1567        int bp = this.bytePointer;
1568
1569        if (fillOrder == 1) {
1570            b = data[bp];
1571            if (bp == l) {
1572                next = 0x00;
1573            } else {
1574                next = data[bp + 1];
1575            }
1576        } else if (fillOrder == 2) {
1577            b = flipTable[data[bp] & 0xff];
1578            if (bp == l) {
1579                next = 0x00;
1580            } else {
1581                next = flipTable[data[bp + 1] & 0xff];
1582            }
1583        } else {
1584            throw new IIOException("Invalid FillOrder");
1585        }
1586
1587        int bitsLeft = 8 - bitPointer;
1588        int bitsFromNextByte = bitsToGet - bitsLeft;
1589
1590        int shift = bitsLeft - bitsToGet;
1591        int i1, i2;
1592        if (shift >= 0) {
1593            i1 = (b & table1[bitsLeft]) >>> shift;
1594            bitPointer += bitsToGet;
1595            if (bitPointer == 8) {
1596                bitPointer = 0;
1597                bytePointer++;
1598            }
1599        } else {
1600            i1 = (b & table1[bitsLeft]) << (-shift);
1601            i2 = (next & table2[bitsFromNextByte]) >>> (8 - bitsFromNextByte);
1602
1603            i1 |= i2;
1604            bytePointer++;
1605            bitPointer = bitsFromNextByte;
1606        }
1607
1608        return i1;
1609    }
1610
1611    // Move pointer backwards by given amount of bits
1612    private void updatePointer(int bitsToMoveBack) {
1613        if (bitsToMoveBack > 8) {
1614            bytePointer -= bitsToMoveBack/8;
1615            bitsToMoveBack %= 8;
1616        }
1617
1618        int i = bitPointer - bitsToMoveBack;
1619        if (i < 0) {
1620            bytePointer--;
1621            bitPointer = 8 + i;
1622        } else {
1623            bitPointer = i;
1624        }
1625    }
1626    
1627    // Forward warning message to reader
1628    private void warning(String msg) {
1629        if(this.reader instanceof TIFFImageReader) {
1630            ((TIFFImageReader)reader).forwardWarningMessage(msg);
1631        }
1632    }
1633}