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