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